Optimize exact sdiv by a constant power of 2 to ashr.
[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, LLVMContext *Context) {
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, LLVMContext *Context) {
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, LLVMContext *Context) {
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(*Context, ~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                                          LLVMContext *Context) {
614   if (V->hasOneUse() && V->getType()->isInteger())
615     if (Instruction *I = dyn_cast<Instruction>(V)) {
616       if (I->getOpcode() == Instruction::Mul)
617         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
618           return I->getOperand(0);
619       if (I->getOpcode() == Instruction::Shl)
620         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
621           // The multiplier is really 1 << CST.
622           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
623           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
624           CST = ConstantInt::get(*Context, 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, LLVMContext *Context) {
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, LLVMContext *Context) {
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                               LLVMContext *Context) {
645   uint32_t W = C1->getBitWidth();
646   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
647   if (sign) {
648     LHSExt.sext(W * 2);
649     RHSExt.sext(W * 2);
650   } else {
651     LHSExt.zext(W * 2);
652     RHSExt.zext(W * 2);
653   }
654
655   APInt MulExt = LHSExt * RHSExt;
656
657   if (sign) {
658     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
659     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
660     return MulExt.slt(Min) || MulExt.sgt(Max);
661   } else 
662     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
663 }
664
665
666 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
667 /// specified instruction is a constant integer.  If so, check to see if there
668 /// are any bits set in the constant that are not demanded.  If so, shrink the
669 /// constant and return true.
670 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
671                                    APInt Demanded, LLVMContext *Context) {
672   assert(I && "No instruction?");
673   assert(OpNo < I->getNumOperands() && "Operand index too large");
674
675   // If the operand is not a constant integer, nothing to do.
676   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
677   if (!OpC) return false;
678
679   // If there are no bits set that aren't demanded, nothing to do.
680   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
681   if ((~Demanded & OpC->getValue()) == 0)
682     return false;
683
684   // This instruction is producing bits that are not demanded. Shrink the RHS.
685   Demanded &= OpC->getValue();
686   I->setOperand(OpNo, ConstantInt::get(*Context, Demanded));
687   return true;
688 }
689
690 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
691 // set of known zero and one bits, compute the maximum and minimum values that
692 // could have the specified known zero and known one bits, returning them in
693 // min/max.
694 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
695                                                    const APInt& KnownOne,
696                                                    APInt& Min, APInt& Max) {
697   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
698          KnownZero.getBitWidth() == Min.getBitWidth() &&
699          KnownZero.getBitWidth() == Max.getBitWidth() &&
700          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
701   APInt UnknownBits = ~(KnownZero|KnownOne);
702
703   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
704   // bit if it is unknown.
705   Min = KnownOne;
706   Max = KnownOne|UnknownBits;
707   
708   if (UnknownBits.isNegative()) { // Sign bit is unknown
709     Min.set(Min.getBitWidth()-1);
710     Max.clear(Max.getBitWidth()-1);
711   }
712 }
713
714 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
715 // a set of known zero and one bits, compute the maximum and minimum values that
716 // could have the specified known zero and known one bits, returning them in
717 // min/max.
718 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
719                                                      const APInt &KnownOne,
720                                                      APInt &Min, APInt &Max) {
721   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
722          KnownZero.getBitWidth() == Min.getBitWidth() &&
723          KnownZero.getBitWidth() == Max.getBitWidth() &&
724          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
725   APInt UnknownBits = ~(KnownZero|KnownOne);
726   
727   // The minimum value is when the unknown bits are all zeros.
728   Min = KnownOne;
729   // The maximum value is when the unknown bits are all ones.
730   Max = KnownOne|UnknownBits;
731 }
732
733 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
734 /// SimplifyDemandedBits knows about.  See if the instruction has any
735 /// properties that allow us to simplify its operands.
736 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
737   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
738   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
739   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
740   
741   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
742                                      KnownZero, KnownOne, 0);
743   if (V == 0) return false;
744   if (V == &Inst) return true;
745   ReplaceInstUsesWith(Inst, V);
746   return true;
747 }
748
749 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
750 /// specified instruction operand if possible, updating it in place.  It returns
751 /// true if it made any change and false otherwise.
752 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
753                                         APInt &KnownZero, APInt &KnownOne,
754                                         unsigned Depth) {
755   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
756                                           KnownZero, KnownOne, Depth);
757   if (NewVal == 0) return false;
758   U.set(NewVal);
759   return true;
760 }
761
762
763 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
764 /// value based on the demanded bits.  When this function is called, it is known
765 /// that only the bits set in DemandedMask of the result of V are ever used
766 /// downstream. Consequently, depending on the mask and V, it may be possible
767 /// to replace V with a constant or one of its operands. In such cases, this
768 /// function does the replacement and returns true. In all other cases, it
769 /// returns false after analyzing the expression and setting KnownOne and known
770 /// to be one in the expression.  KnownZero contains all the bits that are known
771 /// to be zero in the expression. These are provided to potentially allow the
772 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
773 /// the expression. KnownOne and KnownZero always follow the invariant that 
774 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
775 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
776 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
777 /// and KnownOne must all be the same.
778 ///
779 /// This returns null if it did not change anything and it permits no
780 /// simplification.  This returns V itself if it did some simplification of V's
781 /// operands based on the information about what bits are demanded. This returns
782 /// some other non-null value if it found out that V is equal to another value
783 /// in the context where the specified bits are demanded, but not for all users.
784 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
785                                              APInt &KnownZero, APInt &KnownOne,
786                                              unsigned Depth) {
787   assert(V != 0 && "Null pointer of Value???");
788   assert(Depth <= 6 && "Limit Search Depth");
789   uint32_t BitWidth = DemandedMask.getBitWidth();
790   const Type *VTy = V->getType();
791   assert((TD || !isa<PointerType>(VTy)) &&
792          "SimplifyDemandedBits needs to know bit widths!");
793   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
794          (!VTy->isIntOrIntVector() ||
795           VTy->getScalarSizeInBits() == BitWidth) &&
796          KnownZero.getBitWidth() == BitWidth &&
797          KnownOne.getBitWidth() == BitWidth &&
798          "Value *V, DemandedMask, KnownZero and KnownOne "
799          "must have same BitWidth");
800   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
801     // We know all of the bits for a constant!
802     KnownOne = CI->getValue() & DemandedMask;
803     KnownZero = ~KnownOne & DemandedMask;
804     return 0;
805   }
806   if (isa<ConstantPointerNull>(V)) {
807     // We know all of the bits for a constant!
808     KnownOne.clear();
809     KnownZero = DemandedMask;
810     return 0;
811   }
812
813   KnownZero.clear();
814   KnownOne.clear();
815   if (DemandedMask == 0) {   // Not demanding any bits from V.
816     if (isa<UndefValue>(V))
817       return 0;
818     return UndefValue::get(VTy);
819   }
820   
821   if (Depth == 6)        // Limit search depth.
822     return 0;
823   
824   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
825   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
826
827   Instruction *I = dyn_cast<Instruction>(V);
828   if (!I) {
829     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
830     return 0;        // Only analyze instructions.
831   }
832
833   // If there are multiple uses of this value and we aren't at the root, then
834   // we can't do any simplifications of the operands, because DemandedMask
835   // only reflects the bits demanded by *one* of the users.
836   if (Depth != 0 && !I->hasOneUse()) {
837     // Despite the fact that we can't simplify this instruction in all User's
838     // context, we can at least compute the knownzero/knownone bits, and we can
839     // do simplifications that apply to *just* the one user if we know that
840     // this instruction has a simpler value in that context.
841     if (I->getOpcode() == Instruction::And) {
842       // If either the LHS or the RHS are Zero, the result is zero.
843       ComputeMaskedBits(I->getOperand(1), DemandedMask,
844                         RHSKnownZero, RHSKnownOne, Depth+1);
845       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
846                         LHSKnownZero, LHSKnownOne, Depth+1);
847       
848       // If all of the demanded bits are known 1 on one side, return the other.
849       // These bits cannot contribute to the result of the 'and' in this
850       // context.
851       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
852           (DemandedMask & ~LHSKnownZero))
853         return I->getOperand(0);
854       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
855           (DemandedMask & ~RHSKnownZero))
856         return I->getOperand(1);
857       
858       // If all of the demanded bits in the inputs are known zeros, return zero.
859       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
860         return Constant::getNullValue(VTy);
861       
862     } else if (I->getOpcode() == Instruction::Or) {
863       // We can simplify (X|Y) -> X or Y in the user's context if we know that
864       // only bits from X or Y are demanded.
865       
866       // If either the LHS or the RHS are One, the result is One.
867       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
868                         RHSKnownZero, RHSKnownOne, Depth+1);
869       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
870                         LHSKnownZero, LHSKnownOne, Depth+1);
871       
872       // If all of the demanded bits are known zero on one side, return the
873       // other.  These bits cannot contribute to the result of the 'or' in this
874       // context.
875       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
876           (DemandedMask & ~LHSKnownOne))
877         return I->getOperand(0);
878       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
879           (DemandedMask & ~RHSKnownOne))
880         return I->getOperand(1);
881       
882       // If all of the potentially set bits on one side are known to be set on
883       // the other side, just use the 'other' side.
884       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
885           (DemandedMask & (~RHSKnownZero)))
886         return I->getOperand(0);
887       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
888           (DemandedMask & (~LHSKnownZero)))
889         return I->getOperand(1);
890     }
891     
892     // Compute the KnownZero/KnownOne bits to simplify things downstream.
893     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
894     return 0;
895   }
896   
897   // If this is the root being simplified, allow it to have multiple uses,
898   // just set the DemandedMask to all bits so that we can try to simplify the
899   // operands.  This allows visitTruncInst (for example) to simplify the
900   // operand of a trunc without duplicating all the logic below.
901   if (Depth == 0 && !V->hasOneUse())
902     DemandedMask = APInt::getAllOnesValue(BitWidth);
903   
904   switch (I->getOpcode()) {
905   default:
906     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
907     break;
908   case Instruction::And:
909     // If either the LHS or the RHS are Zero, the result is zero.
910     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
911                              RHSKnownZero, RHSKnownOne, Depth+1) ||
912         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
913                              LHSKnownZero, LHSKnownOne, Depth+1))
914       return I;
915     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
916     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
917
918     // If all of the demanded bits are known 1 on one side, return the other.
919     // These bits cannot contribute to the result of the 'and'.
920     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
921         (DemandedMask & ~LHSKnownZero))
922       return I->getOperand(0);
923     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
924         (DemandedMask & ~RHSKnownZero))
925       return I->getOperand(1);
926     
927     // If all of the demanded bits in the inputs are known zeros, return zero.
928     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
929       return Constant::getNullValue(VTy);
930       
931     // If the RHS is a constant, see if we can simplify it.
932     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
933       return I;
934       
935     // Output known-1 bits are only known if set in both the LHS & RHS.
936     RHSKnownOne &= LHSKnownOne;
937     // Output known-0 are known to be clear if zero in either the LHS | RHS.
938     RHSKnownZero |= LHSKnownZero;
939     break;
940   case Instruction::Or:
941     // If either the LHS or the RHS are One, the result is One.
942     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
943                              RHSKnownZero, RHSKnownOne, Depth+1) ||
944         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
945                              LHSKnownZero, LHSKnownOne, Depth+1))
946       return I;
947     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
948     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
949     
950     // If all of the demanded bits are known zero on one side, return the other.
951     // These bits cannot contribute to the result of the 'or'.
952     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
953         (DemandedMask & ~LHSKnownOne))
954       return I->getOperand(0);
955     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
956         (DemandedMask & ~RHSKnownOne))
957       return I->getOperand(1);
958
959     // If all of the potentially set bits on one side are known to be set on
960     // the other side, just use the 'other' side.
961     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
962         (DemandedMask & (~RHSKnownZero)))
963       return I->getOperand(0);
964     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
965         (DemandedMask & (~LHSKnownZero)))
966       return I->getOperand(1);
967         
968     // If the RHS is a constant, see if we can simplify it.
969     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
970       return I;
971           
972     // Output known-0 bits are only known if clear in both the LHS & RHS.
973     RHSKnownZero &= LHSKnownZero;
974     // Output known-1 are known to be set if set in either the LHS | RHS.
975     RHSKnownOne |= LHSKnownOne;
976     break;
977   case Instruction::Xor: {
978     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
979                              RHSKnownZero, RHSKnownOne, Depth+1) ||
980         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
981                              LHSKnownZero, LHSKnownOne, Depth+1))
982       return I;
983     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
984     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
985     
986     // If all of the demanded bits are known zero on one side, return the other.
987     // These bits cannot contribute to the result of the 'xor'.
988     if ((DemandedMask & RHSKnownZero) == DemandedMask)
989       return I->getOperand(0);
990     if ((DemandedMask & LHSKnownZero) == DemandedMask)
991       return I->getOperand(1);
992     
993     // Output known-0 bits are known if clear or set in both the LHS & RHS.
994     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
995                          (RHSKnownOne & LHSKnownOne);
996     // Output known-1 are known to be set if set in only one of the LHS, RHS.
997     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
998                         (RHSKnownOne & LHSKnownZero);
999     
1000     // If all of the demanded bits are known to be zero on one side or the
1001     // other, turn this into an *inclusive* or.
1002     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1003     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1004       Instruction *Or =
1005         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1006                                  I->getName());
1007       return InsertNewInstBefore(Or, *I);
1008     }
1009     
1010     // If all of the demanded bits on one side are known, and all of the set
1011     // bits on that side are also known to be set on the other side, turn this
1012     // into an AND, as we know the bits will be cleared.
1013     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1014     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1015       // all known
1016       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1017         Constant *AndC = Constant::getIntegerValue(VTy,
1018                                                    ~RHSKnownOne & DemandedMask);
1019         Instruction *And = 
1020           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1021         return InsertNewInstBefore(And, *I);
1022       }
1023     }
1024     
1025     // If the RHS is a constant, see if we can simplify it.
1026     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1027     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1028       return I;
1029     
1030     RHSKnownZero = KnownZeroOut;
1031     RHSKnownOne  = KnownOneOut;
1032     break;
1033   }
1034   case Instruction::Select:
1035     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1036                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1037         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1038                              LHSKnownZero, LHSKnownOne, Depth+1))
1039       return I;
1040     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1041     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1042     
1043     // If the operands are constants, see if we can simplify them.
1044     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1045         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1046       return I;
1047     
1048     // Only known if known in both the LHS and RHS.
1049     RHSKnownOne &= LHSKnownOne;
1050     RHSKnownZero &= LHSKnownZero;
1051     break;
1052   case Instruction::Trunc: {
1053     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1054     DemandedMask.zext(truncBf);
1055     RHSKnownZero.zext(truncBf);
1056     RHSKnownOne.zext(truncBf);
1057     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1058                              RHSKnownZero, RHSKnownOne, Depth+1))
1059       return I;
1060     DemandedMask.trunc(BitWidth);
1061     RHSKnownZero.trunc(BitWidth);
1062     RHSKnownOne.trunc(BitWidth);
1063     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1064     break;
1065   }
1066   case Instruction::BitCast:
1067     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1068       return false;  // vector->int or fp->int?
1069
1070     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1071       if (const VectorType *SrcVTy =
1072             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1073         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1074           // Don't touch a bitcast between vectors of different element counts.
1075           return false;
1076       } else
1077         // Don't touch a scalar-to-vector bitcast.
1078         return false;
1079     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1080       // Don't touch a vector-to-scalar bitcast.
1081       return false;
1082
1083     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1084                              RHSKnownZero, RHSKnownOne, Depth+1))
1085       return I;
1086     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1087     break;
1088   case Instruction::ZExt: {
1089     // Compute the bits in the result that are not present in the input.
1090     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1091     
1092     DemandedMask.trunc(SrcBitWidth);
1093     RHSKnownZero.trunc(SrcBitWidth);
1094     RHSKnownOne.trunc(SrcBitWidth);
1095     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1096                              RHSKnownZero, RHSKnownOne, Depth+1))
1097       return I;
1098     DemandedMask.zext(BitWidth);
1099     RHSKnownZero.zext(BitWidth);
1100     RHSKnownOne.zext(BitWidth);
1101     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1102     // The top bits are known to be zero.
1103     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1104     break;
1105   }
1106   case Instruction::SExt: {
1107     // Compute the bits in the result that are not present in the input.
1108     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1109     
1110     APInt InputDemandedBits = DemandedMask & 
1111                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1112
1113     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1114     // If any of the sign extended bits are demanded, we know that the sign
1115     // bit is demanded.
1116     if ((NewBits & DemandedMask) != 0)
1117       InputDemandedBits.set(SrcBitWidth-1);
1118       
1119     InputDemandedBits.trunc(SrcBitWidth);
1120     RHSKnownZero.trunc(SrcBitWidth);
1121     RHSKnownOne.trunc(SrcBitWidth);
1122     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1123                              RHSKnownZero, RHSKnownOne, Depth+1))
1124       return I;
1125     InputDemandedBits.zext(BitWidth);
1126     RHSKnownZero.zext(BitWidth);
1127     RHSKnownOne.zext(BitWidth);
1128     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1129       
1130     // If the sign bit of the input is known set or clear, then we know the
1131     // top bits of the result.
1132
1133     // If the input sign bit is known zero, or if the NewBits are not demanded
1134     // convert this into a zero extension.
1135     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1136       // Convert to ZExt cast
1137       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1138       return InsertNewInstBefore(NewCast, *I);
1139     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1140       RHSKnownOne |= NewBits;
1141     }
1142     break;
1143   }
1144   case Instruction::Add: {
1145     // Figure out what the input bits are.  If the top bits of the and result
1146     // are not demanded, then the add doesn't demand them from its input
1147     // either.
1148     unsigned NLZ = DemandedMask.countLeadingZeros();
1149       
1150     // If there is a constant on the RHS, there are a variety of xformations
1151     // we can do.
1152     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1153       // If null, this should be simplified elsewhere.  Some of the xforms here
1154       // won't work if the RHS is zero.
1155       if (RHS->isZero())
1156         break;
1157       
1158       // If the top bit of the output is demanded, demand everything from the
1159       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1160       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1161
1162       // Find information about known zero/one bits in the input.
1163       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1164                                LHSKnownZero, LHSKnownOne, Depth+1))
1165         return I;
1166
1167       // If the RHS of the add has bits set that can't affect the input, reduce
1168       // the constant.
1169       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1170         return I;
1171       
1172       // Avoid excess work.
1173       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1174         break;
1175       
1176       // Turn it into OR if input bits are zero.
1177       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1178         Instruction *Or =
1179           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1180                                    I->getName());
1181         return InsertNewInstBefore(Or, *I);
1182       }
1183       
1184       // We can say something about the output known-zero and known-one bits,
1185       // depending on potential carries from the input constant and the
1186       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1187       // bits set and the RHS constant is 0x01001, then we know we have a known
1188       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1189       
1190       // To compute this, we first compute the potential carry bits.  These are
1191       // the bits which may be modified.  I'm not aware of a better way to do
1192       // this scan.
1193       const APInt &RHSVal = RHS->getValue();
1194       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1195       
1196       // Now that we know which bits have carries, compute the known-1/0 sets.
1197       
1198       // Bits are known one if they are known zero in one operand and one in the
1199       // other, and there is no input carry.
1200       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1201                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1202       
1203       // Bits are known zero if they are known zero in both operands and there
1204       // is no input carry.
1205       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1206     } else {
1207       // If the high-bits of this ADD are not demanded, then it does not demand
1208       // the high bits of its LHS or RHS.
1209       if (DemandedMask[BitWidth-1] == 0) {
1210         // Right fill the mask of bits for this ADD to demand the most
1211         // significant bit and all those below it.
1212         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1213         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1214                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1215             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1216                                  LHSKnownZero, LHSKnownOne, Depth+1))
1217           return I;
1218       }
1219     }
1220     break;
1221   }
1222   case Instruction::Sub:
1223     // If the high-bits of this SUB are not demanded, then it does not demand
1224     // the high bits of its LHS or RHS.
1225     if (DemandedMask[BitWidth-1] == 0) {
1226       // Right fill the mask of bits for this SUB to demand the most
1227       // significant bit and all those below it.
1228       uint32_t NLZ = DemandedMask.countLeadingZeros();
1229       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1230       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1231                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1232           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1233                                LHSKnownZero, LHSKnownOne, Depth+1))
1234         return I;
1235     }
1236     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1237     // the known zeros and ones.
1238     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1239     break;
1240   case Instruction::Shl:
1241     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1242       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1243       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1244       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1245                                RHSKnownZero, RHSKnownOne, Depth+1))
1246         return I;
1247       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1248       RHSKnownZero <<= ShiftAmt;
1249       RHSKnownOne  <<= ShiftAmt;
1250       // low bits known zero.
1251       if (ShiftAmt)
1252         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1253     }
1254     break;
1255   case Instruction::LShr:
1256     // For a logical shift right
1257     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1258       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1259       
1260       // Unsigned shift right.
1261       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1262       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1263                                RHSKnownZero, RHSKnownOne, Depth+1))
1264         return I;
1265       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1266       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1267       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1268       if (ShiftAmt) {
1269         // Compute the new bits that are at the top now.
1270         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1271         RHSKnownZero |= HighBits;  // high bits known zero.
1272       }
1273     }
1274     break;
1275   case Instruction::AShr:
1276     // If this is an arithmetic shift right and only the low-bit is set, we can
1277     // always convert this into a logical shr, even if the shift amount is
1278     // variable.  The low bit of the shift cannot be an input sign bit unless
1279     // the shift amount is >= the size of the datatype, which is undefined.
1280     if (DemandedMask == 1) {
1281       // Perform the logical shift right.
1282       Instruction *NewVal = BinaryOperator::CreateLShr(
1283                         I->getOperand(0), I->getOperand(1), I->getName());
1284       return InsertNewInstBefore(NewVal, *I);
1285     }    
1286
1287     // If the sign bit is the only bit demanded by this ashr, then there is no
1288     // need to do it, the shift doesn't change the high bit.
1289     if (DemandedMask.isSignBit())
1290       return I->getOperand(0);
1291     
1292     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1293       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1294       
1295       // Signed shift right.
1296       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1297       // If any of the "high bits" are demanded, we should set the sign bit as
1298       // demanded.
1299       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1300         DemandedMaskIn.set(BitWidth-1);
1301       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1302                                RHSKnownZero, RHSKnownOne, Depth+1))
1303         return I;
1304       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1305       // Compute the new bits that are at the top now.
1306       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1307       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1308       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1309         
1310       // Handle the sign bits.
1311       APInt SignBit(APInt::getSignBit(BitWidth));
1312       // Adjust to where it is now in the mask.
1313       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1314         
1315       // If the input sign bit is known to be zero, or if none of the top bits
1316       // are demanded, turn this into an unsigned shift right.
1317       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1318           (HighBits & ~DemandedMask) == HighBits) {
1319         // Perform the logical shift right.
1320         Instruction *NewVal = BinaryOperator::CreateLShr(
1321                           I->getOperand(0), SA, I->getName());
1322         return InsertNewInstBefore(NewVal, *I);
1323       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1324         RHSKnownOne |= HighBits;
1325       }
1326     }
1327     break;
1328   case Instruction::SRem:
1329     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1330       APInt RA = Rem->getValue().abs();
1331       if (RA.isPowerOf2()) {
1332         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1333           return I->getOperand(0);
1334
1335         APInt LowBits = RA - 1;
1336         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1337         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1338                                  LHSKnownZero, LHSKnownOne, Depth+1))
1339           return I;
1340
1341         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1342           LHSKnownZero |= ~LowBits;
1343
1344         KnownZero |= LHSKnownZero & DemandedMask;
1345
1346         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1347       }
1348     }
1349     break;
1350   case Instruction::URem: {
1351     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1352     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1353     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1354                              KnownZero2, KnownOne2, Depth+1) ||
1355         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1356                              KnownZero2, KnownOne2, Depth+1))
1357       return I;
1358
1359     unsigned Leaders = KnownZero2.countLeadingOnes();
1360     Leaders = std::max(Leaders,
1361                        KnownZero2.countLeadingOnes());
1362     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1363     break;
1364   }
1365   case Instruction::Call:
1366     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1367       switch (II->getIntrinsicID()) {
1368       default: break;
1369       case Intrinsic::bswap: {
1370         // If the only bits demanded come from one byte of the bswap result,
1371         // just shift the input byte into position to eliminate the bswap.
1372         unsigned NLZ = DemandedMask.countLeadingZeros();
1373         unsigned NTZ = DemandedMask.countTrailingZeros();
1374           
1375         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1376         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1377         // have 14 leading zeros, round to 8.
1378         NLZ &= ~7;
1379         NTZ &= ~7;
1380         // If we need exactly one byte, we can do this transformation.
1381         if (BitWidth-NLZ-NTZ == 8) {
1382           unsigned ResultBit = NTZ;
1383           unsigned InputBit = BitWidth-NTZ-8;
1384           
1385           // Replace this with either a left or right shift to get the byte into
1386           // the right place.
1387           Instruction *NewVal;
1388           if (InputBit > ResultBit)
1389             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1390                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1391           else
1392             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1393                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1394           NewVal->takeName(I);
1395           return InsertNewInstBefore(NewVal, *I);
1396         }
1397           
1398         // TODO: Could compute known zero/one bits based on the input.
1399         break;
1400       }
1401       }
1402     }
1403     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1404     break;
1405   }
1406   
1407   // If the client is only demanding bits that we know, return the known
1408   // constant.
1409   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1410     return Constant::getIntegerValue(VTy, RHSKnownOne);
1411   return false;
1412 }
1413
1414
1415 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1416 /// any number of elements. DemandedElts contains the set of elements that are
1417 /// actually used by the caller.  This method analyzes which elements of the
1418 /// operand are undef and returns that information in UndefElts.
1419 ///
1420 /// If the information about demanded elements can be used to simplify the
1421 /// operation, the operation is simplified, then the resultant value is
1422 /// returned.  This returns null if no change was made.
1423 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1424                                                 APInt& UndefElts,
1425                                                 unsigned Depth) {
1426   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1427   APInt EltMask(APInt::getAllOnesValue(VWidth));
1428   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1429
1430   if (isa<UndefValue>(V)) {
1431     // If the entire vector is undefined, just return this info.
1432     UndefElts = EltMask;
1433     return 0;
1434   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1435     UndefElts = EltMask;
1436     return UndefValue::get(V->getType());
1437   }
1438
1439   UndefElts = 0;
1440   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1441     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1442     Constant *Undef = UndefValue::get(EltTy);
1443
1444     std::vector<Constant*> Elts;
1445     for (unsigned i = 0; i != VWidth; ++i)
1446       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1447         Elts.push_back(Undef);
1448         UndefElts.set(i);
1449       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1450         Elts.push_back(Undef);
1451         UndefElts.set(i);
1452       } else {                               // Otherwise, defined.
1453         Elts.push_back(CP->getOperand(i));
1454       }
1455
1456     // If we changed the constant, return it.
1457     Constant *NewCP = ConstantVector::get(Elts);
1458     return NewCP != CP ? NewCP : 0;
1459   } else if (isa<ConstantAggregateZero>(V)) {
1460     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1461     // set to undef.
1462     
1463     // Check if this is identity. If so, return 0 since we are not simplifying
1464     // anything.
1465     if (DemandedElts == ((1ULL << VWidth) -1))
1466       return 0;
1467     
1468     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1469     Constant *Zero = Constant::getNullValue(EltTy);
1470     Constant *Undef = UndefValue::get(EltTy);
1471     std::vector<Constant*> Elts;
1472     for (unsigned i = 0; i != VWidth; ++i) {
1473       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1474       Elts.push_back(Elt);
1475     }
1476     UndefElts = DemandedElts ^ EltMask;
1477     return ConstantVector::get(Elts);
1478   }
1479   
1480   // Limit search depth.
1481   if (Depth == 10)
1482     return 0;
1483
1484   // If multiple users are using the root value, procede with
1485   // simplification conservatively assuming that all elements
1486   // are needed.
1487   if (!V->hasOneUse()) {
1488     // Quit if we find multiple users of a non-root value though.
1489     // They'll be handled when it's their turn to be visited by
1490     // the main instcombine process.
1491     if (Depth != 0)
1492       // TODO: Just compute the UndefElts information recursively.
1493       return 0;
1494
1495     // Conservatively assume that all elements are needed.
1496     DemandedElts = EltMask;
1497   }
1498   
1499   Instruction *I = dyn_cast<Instruction>(V);
1500   if (!I) return 0;        // Only analyze instructions.
1501   
1502   bool MadeChange = false;
1503   APInt UndefElts2(VWidth, 0);
1504   Value *TmpV;
1505   switch (I->getOpcode()) {
1506   default: break;
1507     
1508   case Instruction::InsertElement: {
1509     // If this is a variable index, we don't know which element it overwrites.
1510     // demand exactly the same input as we produce.
1511     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1512     if (Idx == 0) {
1513       // Note that we can't propagate undef elt info, because we don't know
1514       // which elt is getting updated.
1515       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1516                                         UndefElts2, Depth+1);
1517       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1518       break;
1519     }
1520     
1521     // If this is inserting an element that isn't demanded, remove this
1522     // insertelement.
1523     unsigned IdxNo = Idx->getZExtValue();
1524     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1525       return AddSoonDeadInstToWorklist(*I, 0);
1526     
1527     // Otherwise, the element inserted overwrites whatever was there, so the
1528     // input demanded set is simpler than the output set.
1529     APInt DemandedElts2 = DemandedElts;
1530     DemandedElts2.clear(IdxNo);
1531     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1532                                       UndefElts, Depth+1);
1533     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1534
1535     // The inserted element is defined.
1536     UndefElts.clear(IdxNo);
1537     break;
1538   }
1539   case Instruction::ShuffleVector: {
1540     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1541     uint64_t LHSVWidth =
1542       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1543     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1544     for (unsigned i = 0; i < VWidth; i++) {
1545       if (DemandedElts[i]) {
1546         unsigned MaskVal = Shuffle->getMaskValue(i);
1547         if (MaskVal != -1u) {
1548           assert(MaskVal < LHSVWidth * 2 &&
1549                  "shufflevector mask index out of range!");
1550           if (MaskVal < LHSVWidth)
1551             LeftDemanded.set(MaskVal);
1552           else
1553             RightDemanded.set(MaskVal - LHSVWidth);
1554         }
1555       }
1556     }
1557
1558     APInt UndefElts4(LHSVWidth, 0);
1559     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1560                                       UndefElts4, Depth+1);
1561     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1562
1563     APInt UndefElts3(LHSVWidth, 0);
1564     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1565                                       UndefElts3, Depth+1);
1566     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1567
1568     bool NewUndefElts = false;
1569     for (unsigned i = 0; i < VWidth; i++) {
1570       unsigned MaskVal = Shuffle->getMaskValue(i);
1571       if (MaskVal == -1u) {
1572         UndefElts.set(i);
1573       } else if (MaskVal < LHSVWidth) {
1574         if (UndefElts4[MaskVal]) {
1575           NewUndefElts = true;
1576           UndefElts.set(i);
1577         }
1578       } else {
1579         if (UndefElts3[MaskVal - LHSVWidth]) {
1580           NewUndefElts = true;
1581           UndefElts.set(i);
1582         }
1583       }
1584     }
1585
1586     if (NewUndefElts) {
1587       // Add additional discovered undefs.
1588       std::vector<Constant*> Elts;
1589       for (unsigned i = 0; i < VWidth; ++i) {
1590         if (UndefElts[i])
1591           Elts.push_back(UndefValue::get(Type::Int32Ty));
1592         else
1593           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1594                                           Shuffle->getMaskValue(i)));
1595       }
1596       I->setOperand(2, ConstantVector::get(Elts));
1597       MadeChange = true;
1598     }
1599     break;
1600   }
1601   case Instruction::BitCast: {
1602     // Vector->vector casts only.
1603     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1604     if (!VTy) break;
1605     unsigned InVWidth = VTy->getNumElements();
1606     APInt InputDemandedElts(InVWidth, 0);
1607     unsigned Ratio;
1608
1609     if (VWidth == InVWidth) {
1610       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1611       // elements as are demanded of us.
1612       Ratio = 1;
1613       InputDemandedElts = DemandedElts;
1614     } else if (VWidth > InVWidth) {
1615       // Untested so far.
1616       break;
1617       
1618       // If there are more elements in the result than there are in the source,
1619       // then an input element is live if any of the corresponding output
1620       // elements are live.
1621       Ratio = VWidth/InVWidth;
1622       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1623         if (DemandedElts[OutIdx])
1624           InputDemandedElts.set(OutIdx/Ratio);
1625       }
1626     } else {
1627       // Untested so far.
1628       break;
1629       
1630       // If there are more elements in the source than there are in the result,
1631       // then an input element is live if the corresponding output element is
1632       // live.
1633       Ratio = InVWidth/VWidth;
1634       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1635         if (DemandedElts[InIdx/Ratio])
1636           InputDemandedElts.set(InIdx);
1637     }
1638     
1639     // div/rem demand all inputs, because they don't want divide by zero.
1640     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1641                                       UndefElts2, Depth+1);
1642     if (TmpV) {
1643       I->setOperand(0, TmpV);
1644       MadeChange = true;
1645     }
1646     
1647     UndefElts = UndefElts2;
1648     if (VWidth > InVWidth) {
1649       llvm_unreachable("Unimp");
1650       // If there are more elements in the result than there are in the source,
1651       // then an output element is undef if the corresponding input element is
1652       // undef.
1653       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1654         if (UndefElts2[OutIdx/Ratio])
1655           UndefElts.set(OutIdx);
1656     } else if (VWidth < InVWidth) {
1657       llvm_unreachable("Unimp");
1658       // If there are more elements in the source than there are in the result,
1659       // then a result element is undef if all of the corresponding input
1660       // elements are undef.
1661       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1662       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1663         if (!UndefElts2[InIdx])            // Not undef?
1664           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1665     }
1666     break;
1667   }
1668   case Instruction::And:
1669   case Instruction::Or:
1670   case Instruction::Xor:
1671   case Instruction::Add:
1672   case Instruction::Sub:
1673   case Instruction::Mul:
1674     // div/rem demand all inputs, because they don't want divide by zero.
1675     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1676                                       UndefElts, Depth+1);
1677     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1678     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1679                                       UndefElts2, Depth+1);
1680     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1681       
1682     // Output elements are undefined if both are undefined.  Consider things
1683     // like undef&0.  The result is known zero, not undef.
1684     UndefElts &= UndefElts2;
1685     break;
1686     
1687   case Instruction::Call: {
1688     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1689     if (!II) break;
1690     switch (II->getIntrinsicID()) {
1691     default: break;
1692       
1693     // Binary vector operations that work column-wise.  A dest element is a
1694     // function of the corresponding input elements from the two inputs.
1695     case Intrinsic::x86_sse_sub_ss:
1696     case Intrinsic::x86_sse_mul_ss:
1697     case Intrinsic::x86_sse_min_ss:
1698     case Intrinsic::x86_sse_max_ss:
1699     case Intrinsic::x86_sse2_sub_sd:
1700     case Intrinsic::x86_sse2_mul_sd:
1701     case Intrinsic::x86_sse2_min_sd:
1702     case Intrinsic::x86_sse2_max_sd:
1703       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1704                                         UndefElts, Depth+1);
1705       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1706       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1707                                         UndefElts2, Depth+1);
1708       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1709
1710       // If only the low elt is demanded and this is a scalarizable intrinsic,
1711       // scalarize it now.
1712       if (DemandedElts == 1) {
1713         switch (II->getIntrinsicID()) {
1714         default: break;
1715         case Intrinsic::x86_sse_sub_ss:
1716         case Intrinsic::x86_sse_mul_ss:
1717         case Intrinsic::x86_sse2_sub_sd:
1718         case Intrinsic::x86_sse2_mul_sd:
1719           // TODO: Lower MIN/MAX/ABS/etc
1720           Value *LHS = II->getOperand(1);
1721           Value *RHS = II->getOperand(2);
1722           // Extract the element as scalars.
1723           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1724             ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
1725           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1726             ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
1727           
1728           switch (II->getIntrinsicID()) {
1729           default: llvm_unreachable("Case stmts out of sync!");
1730           case Intrinsic::x86_sse_sub_ss:
1731           case Intrinsic::x86_sse2_sub_sd:
1732             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1733                                                         II->getName()), *II);
1734             break;
1735           case Intrinsic::x86_sse_mul_ss:
1736           case Intrinsic::x86_sse2_mul_sd:
1737             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1738                                                          II->getName()), *II);
1739             break;
1740           }
1741           
1742           Instruction *New =
1743             InsertElementInst::Create(
1744               UndefValue::get(II->getType()), TmpV,
1745               ConstantInt::get(Type::Int32Ty, 0U, false), II->getName());
1746           InsertNewInstBefore(New, *II);
1747           AddSoonDeadInstToWorklist(*II, 0);
1748           return New;
1749         }            
1750       }
1751         
1752       // Output elements are undefined if both are undefined.  Consider things
1753       // like undef&0.  The result is known zero, not undef.
1754       UndefElts &= UndefElts2;
1755       break;
1756     }
1757     break;
1758   }
1759   }
1760   return MadeChange ? I : 0;
1761 }
1762
1763
1764 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1765 /// function is designed to check a chain of associative operators for a
1766 /// potential to apply a certain optimization.  Since the optimization may be
1767 /// applicable if the expression was reassociated, this checks the chain, then
1768 /// reassociates the expression as necessary to expose the optimization
1769 /// opportunity.  This makes use of a special Functor, which must define
1770 /// 'shouldApply' and 'apply' methods.
1771 ///
1772 template<typename Functor>
1773 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1774                                    LLVMContext *Context) {
1775   unsigned Opcode = Root.getOpcode();
1776   Value *LHS = Root.getOperand(0);
1777
1778   // Quick check, see if the immediate LHS matches...
1779   if (F.shouldApply(LHS))
1780     return F.apply(Root);
1781
1782   // Otherwise, if the LHS is not of the same opcode as the root, return.
1783   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1784   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1785     // Should we apply this transform to the RHS?
1786     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1787
1788     // If not to the RHS, check to see if we should apply to the LHS...
1789     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1790       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1791       ShouldApply = true;
1792     }
1793
1794     // If the functor wants to apply the optimization to the RHS of LHSI,
1795     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1796     if (ShouldApply) {
1797       // Now all of the instructions are in the current basic block, go ahead
1798       // and perform the reassociation.
1799       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1800
1801       // First move the selected RHS to the LHS of the root...
1802       Root.setOperand(0, LHSI->getOperand(1));
1803
1804       // Make what used to be the LHS of the root be the user of the root...
1805       Value *ExtraOperand = TmpLHSI->getOperand(1);
1806       if (&Root == TmpLHSI) {
1807         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1808         return 0;
1809       }
1810       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1811       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1812       BasicBlock::iterator ARI = &Root; ++ARI;
1813       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1814       ARI = Root;
1815
1816       // Now propagate the ExtraOperand down the chain of instructions until we
1817       // get to LHSI.
1818       while (TmpLHSI != LHSI) {
1819         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1820         // Move the instruction to immediately before the chain we are
1821         // constructing to avoid breaking dominance properties.
1822         NextLHSI->moveBefore(ARI);
1823         ARI = NextLHSI;
1824
1825         Value *NextOp = NextLHSI->getOperand(1);
1826         NextLHSI->setOperand(1, ExtraOperand);
1827         TmpLHSI = NextLHSI;
1828         ExtraOperand = NextOp;
1829       }
1830
1831       // Now that the instructions are reassociated, have the functor perform
1832       // the transformation...
1833       return F.apply(Root);
1834     }
1835
1836     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1837   }
1838   return 0;
1839 }
1840
1841 namespace {
1842
1843 // AddRHS - Implements: X + X --> X << 1
1844 struct AddRHS {
1845   Value *RHS;
1846   LLVMContext *Context;
1847   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1848   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1849   Instruction *apply(BinaryOperator &Add) const {
1850     return BinaryOperator::CreateShl(Add.getOperand(0),
1851                                      ConstantInt::get(Add.getType(), 1));
1852   }
1853 };
1854
1855 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1856 //                 iff C1&C2 == 0
1857 struct AddMaskingAnd {
1858   Constant *C2;
1859   LLVMContext *Context;
1860   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1861   bool shouldApply(Value *LHS) const {
1862     ConstantInt *C1;
1863     return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1864            ConstantExpr::getAnd(C1, C2)->isNullValue();
1865   }
1866   Instruction *apply(BinaryOperator &Add) const {
1867     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1868   }
1869 };
1870
1871 }
1872
1873 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1874                                              InstCombiner *IC) {
1875   LLVMContext *Context = IC->getContext();
1876   
1877   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1878     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1879   }
1880
1881   // Figure out if the constant is the left or the right argument.
1882   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1883   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1884
1885   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1886     if (ConstIsRHS)
1887       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1888     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1889   }
1890
1891   Value *Op0 = SO, *Op1 = ConstOperand;
1892   if (!ConstIsRHS)
1893     std::swap(Op0, Op1);
1894   Instruction *New;
1895   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1896     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1897   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1898     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1899                           Op0, Op1, SO->getName()+".cmp");
1900   else {
1901     llvm_unreachable("Unknown binary instruction type!");
1902   }
1903   return IC->InsertNewInstBefore(New, I);
1904 }
1905
1906 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1907 // constant as the other operand, try to fold the binary operator into the
1908 // select arguments.  This also works for Cast instructions, which obviously do
1909 // not have a second operand.
1910 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1911                                      InstCombiner *IC) {
1912   // Don't modify shared select instructions
1913   if (!SI->hasOneUse()) return 0;
1914   Value *TV = SI->getOperand(1);
1915   Value *FV = SI->getOperand(2);
1916
1917   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1918     // Bool selects with constant operands can be folded to logical ops.
1919     if (SI->getType() == Type::Int1Ty) return 0;
1920
1921     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1922     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1923
1924     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1925                               SelectFalseVal);
1926   }
1927   return 0;
1928 }
1929
1930
1931 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1932 /// node as operand #0, see if we can fold the instruction into the PHI (which
1933 /// is only possible if all operands to the PHI are constants).
1934 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1935   PHINode *PN = cast<PHINode>(I.getOperand(0));
1936   unsigned NumPHIValues = PN->getNumIncomingValues();
1937   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1938
1939   // Check to see if all of the operands of the PHI are constants.  If there is
1940   // one non-constant value, remember the BB it is.  If there is more than one
1941   // or if *it* is a PHI, bail out.
1942   BasicBlock *NonConstBB = 0;
1943   for (unsigned i = 0; i != NumPHIValues; ++i)
1944     if (!isa<Constant>(PN->getIncomingValue(i))) {
1945       if (NonConstBB) return 0;  // More than one non-const value.
1946       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1947       NonConstBB = PN->getIncomingBlock(i);
1948       
1949       // If the incoming non-constant value is in I's block, we have an infinite
1950       // loop.
1951       if (NonConstBB == I.getParent())
1952         return 0;
1953     }
1954   
1955   // If there is exactly one non-constant value, we can insert a copy of the
1956   // operation in that block.  However, if this is a critical edge, we would be
1957   // inserting the computation one some other paths (e.g. inside a loop).  Only
1958   // do this if the pred block is unconditionally branching into the phi block.
1959   if (NonConstBB) {
1960     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1961     if (!BI || !BI->isUnconditional()) return 0;
1962   }
1963
1964   // Okay, we can do the transformation: create the new PHI node.
1965   PHINode *NewPN = PHINode::Create(I.getType(), "");
1966   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1967   InsertNewInstBefore(NewPN, *PN);
1968   NewPN->takeName(PN);
1969
1970   // Next, add all of the operands to the PHI.
1971   if (I.getNumOperands() == 2) {
1972     Constant *C = cast<Constant>(I.getOperand(1));
1973     for (unsigned i = 0; i != NumPHIValues; ++i) {
1974       Value *InV = 0;
1975       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1976         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1977           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1978         else
1979           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1980       } else {
1981         assert(PN->getIncomingBlock(i) == NonConstBB);
1982         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1983           InV = BinaryOperator::Create(BO->getOpcode(),
1984                                        PN->getIncomingValue(i), C, "phitmp",
1985                                        NonConstBB->getTerminator());
1986         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1987           InV = CmpInst::Create(*Context, CI->getOpcode(), 
1988                                 CI->getPredicate(),
1989                                 PN->getIncomingValue(i), C, "phitmp",
1990                                 NonConstBB->getTerminator());
1991         else
1992           llvm_unreachable("Unknown binop!");
1993         
1994         AddToWorkList(cast<Instruction>(InV));
1995       }
1996       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1997     }
1998   } else { 
1999     CastInst *CI = cast<CastInst>(&I);
2000     const Type *RetTy = CI->getType();
2001     for (unsigned i = 0; i != NumPHIValues; ++i) {
2002       Value *InV;
2003       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2004         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2005       } else {
2006         assert(PN->getIncomingBlock(i) == NonConstBB);
2007         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2008                                I.getType(), "phitmp", 
2009                                NonConstBB->getTerminator());
2010         AddToWorkList(cast<Instruction>(InV));
2011       }
2012       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2013     }
2014   }
2015   return ReplaceInstUsesWith(I, NewPN);
2016 }
2017
2018
2019 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2020 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2021 /// This basically requires proving that the add in the original type would not
2022 /// overflow to change the sign bit or have a carry out.
2023 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2024   // There are different heuristics we can use for this.  Here are some simple
2025   // ones.
2026   
2027   // Add has the property that adding any two 2's complement numbers can only 
2028   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2029   // have at least two sign bits, we know that the addition of the two values will
2030   // sign extend fine.
2031   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2032     return true;
2033   
2034   
2035   // If one of the operands only has one non-zero bit, and if the other operand
2036   // has a known-zero bit in a more significant place than it (not including the
2037   // sign bit) the ripple may go up to and fill the zero, but won't change the
2038   // sign.  For example, (X & ~4) + 1.
2039   
2040   // TODO: Implement.
2041   
2042   return false;
2043 }
2044
2045
2046 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2047   bool Changed = SimplifyCommutative(I);
2048   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2049
2050   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2051     // X + undef -> undef
2052     if (isa<UndefValue>(RHS))
2053       return ReplaceInstUsesWith(I, RHS);
2054
2055     // X + 0 --> X
2056     if (RHSC->isNullValue())
2057       return ReplaceInstUsesWith(I, LHS);
2058
2059     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2060       // X + (signbit) --> X ^ signbit
2061       const APInt& Val = CI->getValue();
2062       uint32_t BitWidth = Val.getBitWidth();
2063       if (Val == APInt::getSignBit(BitWidth))
2064         return BinaryOperator::CreateXor(LHS, RHS);
2065       
2066       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2067       // (X & 254)+1 -> (X&254)|1
2068       if (SimplifyDemandedInstructionBits(I))
2069         return &I;
2070
2071       // zext(bool) + C -> bool ? C + 1 : C
2072       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2073         if (ZI->getSrcTy() == Type::Int1Ty)
2074           return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2075     }
2076
2077     if (isa<PHINode>(LHS))
2078       if (Instruction *NV = FoldOpIntoPhi(I))
2079         return NV;
2080     
2081     ConstantInt *XorRHS = 0;
2082     Value *XorLHS = 0;
2083     if (isa<ConstantInt>(RHSC) &&
2084         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2085       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2086       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2087       
2088       uint32_t Size = TySizeBits / 2;
2089       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2090       APInt CFF80Val(-C0080Val);
2091       do {
2092         if (TySizeBits > Size) {
2093           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2094           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2095           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2096               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2097             // This is a sign extend if the top bits are known zero.
2098             if (!MaskedValueIsZero(XorLHS, 
2099                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2100               Size = 0;  // Not a sign ext, but can't be any others either.
2101             break;
2102           }
2103         }
2104         Size >>= 1;
2105         C0080Val = APIntOps::lshr(C0080Val, Size);
2106         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2107       } while (Size >= 1);
2108       
2109       // FIXME: This shouldn't be necessary. When the backends can handle types
2110       // with funny bit widths then this switch statement should be removed. It
2111       // is just here to get the size of the "middle" type back up to something
2112       // that the back ends can handle.
2113       const Type *MiddleType = 0;
2114       switch (Size) {
2115         default: break;
2116         case 32: MiddleType = Type::Int32Ty; break;
2117         case 16: MiddleType = Type::Int16Ty; break;
2118         case  8: MiddleType = Type::Int8Ty; break;
2119       }
2120       if (MiddleType) {
2121         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2122         InsertNewInstBefore(NewTrunc, I);
2123         return new SExtInst(NewTrunc, I.getType(), I.getName());
2124       }
2125     }
2126   }
2127
2128   if (I.getType() == Type::Int1Ty)
2129     return BinaryOperator::CreateXor(LHS, RHS);
2130
2131   // X + X --> X << 1
2132   if (I.getType()->isInteger()) {
2133     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2134       return Result;
2135
2136     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2137       if (RHSI->getOpcode() == Instruction::Sub)
2138         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2139           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2140     }
2141     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2142       if (LHSI->getOpcode() == Instruction::Sub)
2143         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2144           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2145     }
2146   }
2147
2148   // -A + B  -->  B - A
2149   // -A + -B  -->  -(A + B)
2150   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2151     if (LHS->getType()->isIntOrIntVector()) {
2152       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2153         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2154         InsertNewInstBefore(NewAdd, I);
2155         return BinaryOperator::CreateNeg(*Context, NewAdd);
2156       }
2157     }
2158     
2159     return BinaryOperator::CreateSub(RHS, LHSV);
2160   }
2161
2162   // A + -B  -->  A - B
2163   if (!isa<Constant>(RHS))
2164     if (Value *V = dyn_castNegVal(RHS, Context))
2165       return BinaryOperator::CreateSub(LHS, V);
2166
2167
2168   ConstantInt *C2;
2169   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2170     if (X == RHS)   // X*C + X --> X * (C+1)
2171       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2172
2173     // X*C1 + X*C2 --> X * (C1+C2)
2174     ConstantInt *C1;
2175     if (X == dyn_castFoldableMul(RHS, C1, Context))
2176       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2177   }
2178
2179   // X + X*C --> X * (C+1)
2180   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2181     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2182
2183   // X + ~X --> -1   since   ~X = -X-1
2184   if (dyn_castNotVal(LHS, Context) == RHS ||
2185       dyn_castNotVal(RHS, Context) == LHS)
2186     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2187   
2188
2189   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2190   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2191     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2192       return R;
2193   
2194   // A+B --> A|B iff A and B have no bits set in common.
2195   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2196     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2197     APInt LHSKnownOne(IT->getBitWidth(), 0);
2198     APInt LHSKnownZero(IT->getBitWidth(), 0);
2199     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2200     if (LHSKnownZero != 0) {
2201       APInt RHSKnownOne(IT->getBitWidth(), 0);
2202       APInt RHSKnownZero(IT->getBitWidth(), 0);
2203       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2204       
2205       // No bits in common -> bitwise or.
2206       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2207         return BinaryOperator::CreateOr(LHS, RHS);
2208     }
2209   }
2210
2211   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2212   if (I.getType()->isIntOrIntVector()) {
2213     Value *W, *X, *Y, *Z;
2214     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2215         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2216       if (W != Y) {
2217         if (W == Z) {
2218           std::swap(Y, Z);
2219         } else if (Y == X) {
2220           std::swap(W, X);
2221         } else if (X == Z) {
2222           std::swap(Y, Z);
2223           std::swap(W, X);
2224         }
2225       }
2226
2227       if (W == Y) {
2228         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2229                                                             LHS->getName()), I);
2230         return BinaryOperator::CreateMul(W, NewAdd);
2231       }
2232     }
2233   }
2234
2235   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2236     Value *X = 0;
2237     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2238       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2239
2240     // (X & FF00) + xx00  -> (X+xx00) & FF00
2241     if (LHS->hasOneUse() &&
2242         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2243       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2244       if (Anded == CRHS) {
2245         // See if all bits from the first bit set in the Add RHS up are included
2246         // in the mask.  First, get the rightmost bit.
2247         const APInt& AddRHSV = CRHS->getValue();
2248
2249         // Form a mask of all bits from the lowest bit added through the top.
2250         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2251
2252         // See if the and mask includes all of these bits.
2253         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2254
2255         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2256           // Okay, the xform is safe.  Insert the new add pronto.
2257           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2258                                                             LHS->getName()), I);
2259           return BinaryOperator::CreateAnd(NewAdd, C2);
2260         }
2261       }
2262     }
2263
2264     // Try to fold constant add into select arguments.
2265     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2266       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2267         return R;
2268   }
2269
2270   // add (select X 0 (sub n A)) A  -->  select X A n
2271   {
2272     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2273     Value *A = RHS;
2274     if (!SI) {
2275       SI = dyn_cast<SelectInst>(RHS);
2276       A = LHS;
2277     }
2278     if (SI && SI->hasOneUse()) {
2279       Value *TV = SI->getTrueValue();
2280       Value *FV = SI->getFalseValue();
2281       Value *N;
2282
2283       // Can we fold the add into the argument of the select?
2284       // We check both true and false select arguments for a matching subtract.
2285       if (match(FV, m_Zero(), *Context) &&
2286           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2287         // Fold the add into the true select value.
2288         return SelectInst::Create(SI->getCondition(), N, A);
2289       if (match(TV, m_Zero(), *Context) &&
2290           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2291         // Fold the add into the false select value.
2292         return SelectInst::Create(SI->getCondition(), A, N);
2293     }
2294   }
2295
2296   // Check for (add (sext x), y), see if we can merge this into an
2297   // integer add followed by a sext.
2298   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2299     // (add (sext x), cst) --> (sext (add x, cst'))
2300     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2301       Constant *CI = 
2302         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2303       if (LHSConv->hasOneUse() &&
2304           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2305           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2306         // Insert the new, smaller add.
2307         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2308                                                         CI, "addconv");
2309         InsertNewInstBefore(NewAdd, I);
2310         return new SExtInst(NewAdd, I.getType());
2311       }
2312     }
2313     
2314     // (add (sext x), (sext y)) --> (sext (add int x, y))
2315     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2316       // Only do this if x/y have the same type, if at last one of them has a
2317       // single use (so we don't increase the number of sexts), and if the
2318       // integer add will not overflow.
2319       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2320           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2321           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2322                                    RHSConv->getOperand(0))) {
2323         // Insert the new integer add.
2324         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2325                                                         RHSConv->getOperand(0),
2326                                                         "addconv");
2327         InsertNewInstBefore(NewAdd, I);
2328         return new SExtInst(NewAdd, I.getType());
2329       }
2330     }
2331   }
2332
2333   return Changed ? &I : 0;
2334 }
2335
2336 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2337   bool Changed = SimplifyCommutative(I);
2338   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2339
2340   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2341     // X + 0 --> X
2342     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2343       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2344                               (I.getType())->getValueAPF()))
2345         return ReplaceInstUsesWith(I, LHS);
2346     }
2347
2348     if (isa<PHINode>(LHS))
2349       if (Instruction *NV = FoldOpIntoPhi(I))
2350         return NV;
2351   }
2352
2353   // -A + B  -->  B - A
2354   // -A + -B  -->  -(A + B)
2355   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2356     return BinaryOperator::CreateFSub(RHS, LHSV);
2357
2358   // A + -B  -->  A - B
2359   if (!isa<Constant>(RHS))
2360     if (Value *V = dyn_castFNegVal(RHS, Context))
2361       return BinaryOperator::CreateFSub(LHS, V);
2362
2363   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2364   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2365     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2366       return ReplaceInstUsesWith(I, LHS);
2367
2368   // Check for (add double (sitofp x), y), see if we can merge this into an
2369   // integer add followed by a promotion.
2370   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2371     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2372     // ... if the constant fits in the integer value.  This is useful for things
2373     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2374     // requires a constant pool load, and generally allows the add to be better
2375     // instcombined.
2376     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2377       Constant *CI = 
2378       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2379       if (LHSConv->hasOneUse() &&
2380           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2381           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2382         // Insert the new integer add.
2383         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2384                                                         CI, "addconv");
2385         InsertNewInstBefore(NewAdd, I);
2386         return new SIToFPInst(NewAdd, I.getType());
2387       }
2388     }
2389     
2390     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2391     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2392       // Only do this if x/y have the same type, if at last one of them has a
2393       // single use (so we don't increase the number of int->fp conversions),
2394       // and if the integer add will not overflow.
2395       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2396           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2397           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2398                                    RHSConv->getOperand(0))) {
2399         // Insert the new integer add.
2400         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2401                                                         RHSConv->getOperand(0),
2402                                                         "addconv");
2403         InsertNewInstBefore(NewAdd, I);
2404         return new SIToFPInst(NewAdd, I.getType());
2405       }
2406     }
2407   }
2408   
2409   return Changed ? &I : 0;
2410 }
2411
2412 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2413   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2414
2415   if (Op0 == Op1)                        // sub X, X  -> 0
2416     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2417
2418   // If this is a 'B = x-(-A)', change to B = x+A...
2419   if (Value *V = dyn_castNegVal(Op1, Context))
2420     return BinaryOperator::CreateAdd(Op0, V);
2421
2422   if (isa<UndefValue>(Op0))
2423     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2424   if (isa<UndefValue>(Op1))
2425     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2426
2427   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2428     // Replace (-1 - A) with (~A)...
2429     if (C->isAllOnesValue())
2430       return BinaryOperator::CreateNot(*Context, Op1);
2431
2432     // C - ~X == X + (1+C)
2433     Value *X = 0;
2434     if (match(Op1, m_Not(m_Value(X)), *Context))
2435       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2436
2437     // -(X >>u 31) -> (X >>s 31)
2438     // -(X >>s 31) -> (X >>u 31)
2439     if (C->isZero()) {
2440       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2441         if (SI->getOpcode() == Instruction::LShr) {
2442           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2443             // Check to see if we are shifting out everything but the sign bit.
2444             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2445                 SI->getType()->getPrimitiveSizeInBits()-1) {
2446               // Ok, the transformation is safe.  Insert AShr.
2447               return BinaryOperator::Create(Instruction::AShr, 
2448                                           SI->getOperand(0), CU, SI->getName());
2449             }
2450           }
2451         }
2452         else if (SI->getOpcode() == Instruction::AShr) {
2453           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2454             // Check to see if we are shifting out everything but the sign bit.
2455             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2456                 SI->getType()->getPrimitiveSizeInBits()-1) {
2457               // Ok, the transformation is safe.  Insert LShr. 
2458               return BinaryOperator::CreateLShr(
2459                                           SI->getOperand(0), CU, SI->getName());
2460             }
2461           }
2462         }
2463       }
2464     }
2465
2466     // Try to fold constant sub into select arguments.
2467     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2468       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2469         return R;
2470
2471     // C - zext(bool) -> bool ? C - 1 : C
2472     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2473       if (ZI->getSrcTy() == Type::Int1Ty)
2474         return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2475   }
2476
2477   if (I.getType() == Type::Int1Ty)
2478     return BinaryOperator::CreateXor(Op0, Op1);
2479
2480   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2481     if (Op1I->getOpcode() == Instruction::Add) {
2482       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2483         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2484                                          I.getName());
2485       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2486         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2487                                          I.getName());
2488       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2489         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2490           // C1-(X+C2) --> (C1-C2)-X
2491           return BinaryOperator::CreateSub(
2492             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2493       }
2494     }
2495
2496     if (Op1I->hasOneUse()) {
2497       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2498       // is not used by anyone else...
2499       //
2500       if (Op1I->getOpcode() == Instruction::Sub) {
2501         // Swap the two operands of the subexpr...
2502         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2503         Op1I->setOperand(0, IIOp1);
2504         Op1I->setOperand(1, IIOp0);
2505
2506         // Create the new top level add instruction...
2507         return BinaryOperator::CreateAdd(Op0, Op1);
2508       }
2509
2510       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2511       //
2512       if (Op1I->getOpcode() == Instruction::And &&
2513           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2514         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2515
2516         Value *NewNot =
2517           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2518                                                         OtherOp, "B.not"), I);
2519         return BinaryOperator::CreateAnd(Op0, NewNot);
2520       }
2521
2522       // 0 - (X sdiv C)  -> (X sdiv -C)
2523       if (Op1I->getOpcode() == Instruction::SDiv)
2524         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2525           if (CSI->isZero())
2526             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2527               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2528                                           ConstantExpr::getNeg(DivRHS));
2529
2530       // X - X*C --> X * (1-C)
2531       ConstantInt *C2 = 0;
2532       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2533         Constant *CP1 = 
2534           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2535                                              C2);
2536         return BinaryOperator::CreateMul(Op0, CP1);
2537       }
2538     }
2539   }
2540
2541   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2542     if (Op0I->getOpcode() == Instruction::Add) {
2543       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2544         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2545       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2546         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2547     } else if (Op0I->getOpcode() == Instruction::Sub) {
2548       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2549         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2550                                          I.getName());
2551     }
2552   }
2553
2554   ConstantInt *C1;
2555   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2556     if (X == Op1)  // X*C - X --> X * (C-1)
2557       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2558
2559     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2560     if (X == dyn_castFoldableMul(Op1, C2, Context))
2561       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2562   }
2563   return 0;
2564 }
2565
2566 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2567   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2568
2569   // If this is a 'B = x-(-A)', change to B = x+A...
2570   if (Value *V = dyn_castFNegVal(Op1, Context))
2571     return BinaryOperator::CreateFAdd(Op0, V);
2572
2573   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2574     if (Op1I->getOpcode() == Instruction::FAdd) {
2575       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2576         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2577                                           I.getName());
2578       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2579         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2580                                           I.getName());
2581     }
2582   }
2583
2584   return 0;
2585 }
2586
2587 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2588 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2589 /// TrueIfSigned if the result of the comparison is true when the input value is
2590 /// signed.
2591 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2592                            bool &TrueIfSigned) {
2593   switch (pred) {
2594   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2595     TrueIfSigned = true;
2596     return RHS->isZero();
2597   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2598     TrueIfSigned = true;
2599     return RHS->isAllOnesValue();
2600   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2601     TrueIfSigned = false;
2602     return RHS->isAllOnesValue();
2603   case ICmpInst::ICMP_UGT:
2604     // True if LHS u> RHS and RHS == high-bit-mask - 1
2605     TrueIfSigned = true;
2606     return RHS->getValue() ==
2607       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2608   case ICmpInst::ICMP_UGE: 
2609     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2610     TrueIfSigned = true;
2611     return RHS->getValue().isSignBit();
2612   default:
2613     return false;
2614   }
2615 }
2616
2617 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2618   bool Changed = SimplifyCommutative(I);
2619   Value *Op0 = I.getOperand(0);
2620
2621   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2622     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2623
2624   // Simplify mul instructions with a constant RHS...
2625   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2626     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2627
2628       // ((X << C1)*C2) == (X * (C2 << C1))
2629       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2630         if (SI->getOpcode() == Instruction::Shl)
2631           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2632             return BinaryOperator::CreateMul(SI->getOperand(0),
2633                                         ConstantExpr::getShl(CI, ShOp));
2634
2635       if (CI->isZero())
2636         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2637       if (CI->equalsInt(1))                  // X * 1  == X
2638         return ReplaceInstUsesWith(I, Op0);
2639       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2640         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2641
2642       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2643       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2644         return BinaryOperator::CreateShl(Op0,
2645                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2646       }
2647     } else if (isa<VectorType>(Op1->getType())) {
2648       if (Op1->isNullValue())
2649         return ReplaceInstUsesWith(I, Op1);
2650
2651       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2652         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2653           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2654
2655         // As above, vector X*splat(1.0) -> X in all defined cases.
2656         if (Constant *Splat = Op1V->getSplatValue()) {
2657           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2658             if (CI->equalsInt(1))
2659               return ReplaceInstUsesWith(I, Op0);
2660         }
2661       }
2662     }
2663     
2664     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2665       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2666           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2667         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2668         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2669                                                      Op1, "tmp");
2670         InsertNewInstBefore(Add, I);
2671         Value *C1C2 = ConstantExpr::getMul(Op1, 
2672                                            cast<Constant>(Op0I->getOperand(1)));
2673         return BinaryOperator::CreateAdd(Add, C1C2);
2674         
2675       }
2676
2677     // Try to fold constant mul into select arguments.
2678     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2679       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2680         return R;
2681
2682     if (isa<PHINode>(Op0))
2683       if (Instruction *NV = FoldOpIntoPhi(I))
2684         return NV;
2685   }
2686
2687   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2688     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2689       return BinaryOperator::CreateMul(Op0v, Op1v);
2690
2691   // (X / Y) *  Y = X - (X % Y)
2692   // (X / Y) * -Y = (X % Y) - X
2693   {
2694     Value *Op1 = I.getOperand(1);
2695     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2696     if (!BO ||
2697         (BO->getOpcode() != Instruction::UDiv && 
2698          BO->getOpcode() != Instruction::SDiv)) {
2699       Op1 = Op0;
2700       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2701     }
2702     Value *Neg = dyn_castNegVal(Op1, Context);
2703     if (BO && BO->hasOneUse() &&
2704         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2705         (BO->getOpcode() == Instruction::UDiv ||
2706          BO->getOpcode() == Instruction::SDiv)) {
2707       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2708
2709       Instruction *Rem;
2710       if (BO->getOpcode() == Instruction::UDiv)
2711         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2712       else
2713         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2714
2715       InsertNewInstBefore(Rem, I);
2716       Rem->takeName(BO);
2717
2718       if (Op1BO == Op1)
2719         return BinaryOperator::CreateSub(Op0BO, Rem);
2720       else
2721         return BinaryOperator::CreateSub(Rem, Op0BO);
2722     }
2723   }
2724
2725   if (I.getType() == Type::Int1Ty)
2726     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2727
2728   // If one of the operands of the multiply is a cast from a boolean value, then
2729   // we know the bool is either zero or one, so this is a 'masking' multiply.
2730   // See if we can simplify things based on how the boolean was originally
2731   // formed.
2732   CastInst *BoolCast = 0;
2733   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2734     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2735       BoolCast = CI;
2736   if (!BoolCast)
2737     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2738       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2739         BoolCast = CI;
2740   if (BoolCast) {
2741     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2742       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2743       const Type *SCOpTy = SCIOp0->getType();
2744       bool TIS = false;
2745       
2746       // If the icmp is true iff the sign bit of X is set, then convert this
2747       // multiply into a shift/and combination.
2748       if (isa<ConstantInt>(SCIOp1) &&
2749           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2750           TIS) {
2751         // Shift the X value right to turn it into "all signbits".
2752         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2753                                           SCOpTy->getPrimitiveSizeInBits()-1);
2754         Value *V =
2755           InsertNewInstBefore(
2756             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2757                                             BoolCast->getOperand(0)->getName()+
2758                                             ".mask"), I);
2759
2760         // If the multiply type is not the same as the source type, sign extend
2761         // or truncate to the multiply type.
2762         if (I.getType() != V->getType()) {
2763           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2764           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2765           Instruction::CastOps opcode = 
2766             (SrcBits == DstBits ? Instruction::BitCast : 
2767              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2768           V = InsertCastBefore(opcode, V, I.getType(), I);
2769         }
2770
2771         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2772         return BinaryOperator::CreateAnd(V, OtherOp);
2773       }
2774     }
2775   }
2776
2777   return Changed ? &I : 0;
2778 }
2779
2780 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2781   bool Changed = SimplifyCommutative(I);
2782   Value *Op0 = I.getOperand(0);
2783
2784   // Simplify mul instructions with a constant RHS...
2785   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2786     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2787       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2788       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2789       if (Op1F->isExactlyValue(1.0))
2790         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2791     } else if (isa<VectorType>(Op1->getType())) {
2792       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2793         // As above, vector X*splat(1.0) -> X in all defined cases.
2794         if (Constant *Splat = Op1V->getSplatValue()) {
2795           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2796             if (F->isExactlyValue(1.0))
2797               return ReplaceInstUsesWith(I, Op0);
2798         }
2799       }
2800     }
2801
2802     // Try to fold constant mul into select arguments.
2803     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2804       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2805         return R;
2806
2807     if (isa<PHINode>(Op0))
2808       if (Instruction *NV = FoldOpIntoPhi(I))
2809         return NV;
2810   }
2811
2812   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2813     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2814       return BinaryOperator::CreateFMul(Op0v, Op1v);
2815
2816   return Changed ? &I : 0;
2817 }
2818
2819 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2820 /// instruction.
2821 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2822   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2823   
2824   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2825   int NonNullOperand = -1;
2826   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2827     if (ST->isNullValue())
2828       NonNullOperand = 2;
2829   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2830   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2831     if (ST->isNullValue())
2832       NonNullOperand = 1;
2833   
2834   if (NonNullOperand == -1)
2835     return false;
2836   
2837   Value *SelectCond = SI->getOperand(0);
2838   
2839   // Change the div/rem to use 'Y' instead of the select.
2840   I.setOperand(1, SI->getOperand(NonNullOperand));
2841   
2842   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2843   // problem.  However, the select, or the condition of the select may have
2844   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2845   // propagate the known value for the select into other uses of it, and
2846   // propagate a known value of the condition into its other users.
2847   
2848   // If the select and condition only have a single use, don't bother with this,
2849   // early exit.
2850   if (SI->use_empty() && SelectCond->hasOneUse())
2851     return true;
2852   
2853   // Scan the current block backward, looking for other uses of SI.
2854   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2855   
2856   while (BBI != BBFront) {
2857     --BBI;
2858     // If we found a call to a function, we can't assume it will return, so
2859     // information from below it cannot be propagated above it.
2860     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2861       break;
2862     
2863     // Replace uses of the select or its condition with the known values.
2864     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2865          I != E; ++I) {
2866       if (*I == SI) {
2867         *I = SI->getOperand(NonNullOperand);
2868         AddToWorkList(BBI);
2869       } else if (*I == SelectCond) {
2870         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2871                                    ConstantInt::getFalse(*Context);
2872         AddToWorkList(BBI);
2873       }
2874     }
2875     
2876     // If we past the instruction, quit looking for it.
2877     if (&*BBI == SI)
2878       SI = 0;
2879     if (&*BBI == SelectCond)
2880       SelectCond = 0;
2881     
2882     // If we ran out of things to eliminate, break out of the loop.
2883     if (SelectCond == 0 && SI == 0)
2884       break;
2885     
2886   }
2887   return true;
2888 }
2889
2890
2891 /// This function implements the transforms on div instructions that work
2892 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2893 /// used by the visitors to those instructions.
2894 /// @brief Transforms common to all three div instructions
2895 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2896   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2897
2898   // undef / X -> 0        for integer.
2899   // undef / X -> undef    for FP (the undef could be a snan).
2900   if (isa<UndefValue>(Op0)) {
2901     if (Op0->getType()->isFPOrFPVector())
2902       return ReplaceInstUsesWith(I, Op0);
2903     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2904   }
2905
2906   // X / undef -> undef
2907   if (isa<UndefValue>(Op1))
2908     return ReplaceInstUsesWith(I, Op1);
2909
2910   return 0;
2911 }
2912
2913 /// This function implements the transforms common to both integer division
2914 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2915 /// division instructions.
2916 /// @brief Common integer divide transforms
2917 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2918   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2919
2920   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2921   if (Op0 == Op1) {
2922     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2923       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2924       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2925       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2926     }
2927
2928     Constant *CI = ConstantInt::get(I.getType(), 1);
2929     return ReplaceInstUsesWith(I, CI);
2930   }
2931   
2932   if (Instruction *Common = commonDivTransforms(I))
2933     return Common;
2934   
2935   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2936   // This does not apply for fdiv.
2937   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2938     return &I;
2939
2940   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2941     // div X, 1 == X
2942     if (RHS->equalsInt(1))
2943       return ReplaceInstUsesWith(I, Op0);
2944
2945     // (X / C1) / C2  -> X / (C1*C2)
2946     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2947       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2948         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2949           if (MultiplyOverflows(RHS, LHSRHS,
2950                                 I.getOpcode()==Instruction::SDiv, Context))
2951             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2952           else 
2953             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2954                                       ConstantExpr::getMul(RHS, LHSRHS));
2955         }
2956
2957     if (!RHS->isZero()) { // avoid X udiv 0
2958       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2959         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2960           return R;
2961       if (isa<PHINode>(Op0))
2962         if (Instruction *NV = FoldOpIntoPhi(I))
2963           return NV;
2964     }
2965   }
2966
2967   // 0 / X == 0, we don't need to preserve faults!
2968   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2969     if (LHS->equalsInt(0))
2970       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2971
2972   // It can't be division by zero, hence it must be division by one.
2973   if (I.getType() == Type::Int1Ty)
2974     return ReplaceInstUsesWith(I, Op0);
2975
2976   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2977     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2978       // div X, 1 == X
2979       if (X->isOne())
2980         return ReplaceInstUsesWith(I, Op0);
2981   }
2982
2983   return 0;
2984 }
2985
2986 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2987   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2988
2989   // Handle the integer div common cases
2990   if (Instruction *Common = commonIDivTransforms(I))
2991     return Common;
2992
2993   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2994     // X udiv C^2 -> X >> C
2995     // Check to see if this is an unsigned division with an exact power of 2,
2996     // if so, convert to a right shift.
2997     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2998       return BinaryOperator::CreateLShr(Op0, 
2999             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3000
3001     // X udiv C, where C >= signbit
3002     if (C->getValue().isNegative()) {
3003       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3004                                                     ICmpInst::ICMP_ULT, Op0, C),
3005                                       I);
3006       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3007                                 ConstantInt::get(I.getType(), 1));
3008     }
3009   }
3010
3011   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3012   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3013     if (RHSI->getOpcode() == Instruction::Shl &&
3014         isa<ConstantInt>(RHSI->getOperand(0))) {
3015       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3016       if (C1.isPowerOf2()) {
3017         Value *N = RHSI->getOperand(1);
3018         const Type *NTy = N->getType();
3019         if (uint32_t C2 = C1.logBase2()) {
3020           Constant *C2V = ConstantInt::get(NTy, C2);
3021           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3022         }
3023         return BinaryOperator::CreateLShr(Op0, N);
3024       }
3025     }
3026   }
3027   
3028   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3029   // where C1&C2 are powers of two.
3030   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3031     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3032       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3033         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3034         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3035           // Compute the shift amounts
3036           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3037           // Construct the "on true" case of the select
3038           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3039           Instruction *TSI = BinaryOperator::CreateLShr(
3040                                                  Op0, TC, SI->getName()+".t");
3041           TSI = InsertNewInstBefore(TSI, I);
3042   
3043           // Construct the "on false" case of the select
3044           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3045           Instruction *FSI = BinaryOperator::CreateLShr(
3046                                                  Op0, FC, SI->getName()+".f");
3047           FSI = InsertNewInstBefore(FSI, I);
3048
3049           // construct the select instruction and return it.
3050           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3051         }
3052       }
3053   return 0;
3054 }
3055
3056 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3057   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3058
3059   // Handle the integer div common cases
3060   if (Instruction *Common = commonIDivTransforms(I))
3061     return Common;
3062
3063   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3064     // sdiv X, -1 == -X
3065     if (RHS->isAllOnesValue())
3066       return BinaryOperator::CreateNeg(*Context, Op0);
3067
3068     // sdiv X, C  --> ashr X, log2(C)
3069     if (cast<SDivOperator>(&I)->isExact() &&
3070         RHS->getValue().isNonNegative() &&
3071         RHS->getValue().isPowerOf2()) {
3072       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3073                                             RHS->getValue().exactLogBase2());
3074       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3075     }
3076   }
3077
3078   // If the sign bits of both operands are zero (i.e. we can prove they are
3079   // unsigned inputs), turn this into a udiv.
3080   if (I.getType()->isInteger()) {
3081     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3082     if (MaskedValueIsZero(Op0, Mask)) {
3083       if (MaskedValueIsZero(Op1, Mask)) {
3084         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3085         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3086       }
3087       ConstantInt *ShiftedInt;
3088       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3089           ShiftedInt->getValue().isPowerOf2()) {
3090         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3091         // Safe because the only negative value (1 << Y) can take on is
3092         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3093         // the sign bit set.
3094         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3095       }
3096     }
3097   }
3098   
3099   return 0;
3100 }
3101
3102 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3103   return commonDivTransforms(I);
3104 }
3105
3106 /// This function implements the transforms on rem instructions that work
3107 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3108 /// is used by the visitors to those instructions.
3109 /// @brief Transforms common to all three rem instructions
3110 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3111   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3112
3113   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3114     if (I.getType()->isFPOrFPVector())
3115       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3116     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3117   }
3118   if (isa<UndefValue>(Op1))
3119     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3120
3121   // Handle cases involving: rem X, (select Cond, Y, Z)
3122   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3123     return &I;
3124
3125   return 0;
3126 }
3127
3128 /// This function implements the transforms common to both integer remainder
3129 /// instructions (urem and srem). It is called by the visitors to those integer
3130 /// remainder instructions.
3131 /// @brief Common integer remainder transforms
3132 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3133   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3134
3135   if (Instruction *common = commonRemTransforms(I))
3136     return common;
3137
3138   // 0 % X == 0 for integer, we don't need to preserve faults!
3139   if (Constant *LHS = dyn_cast<Constant>(Op0))
3140     if (LHS->isNullValue())
3141       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3142
3143   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3144     // X % 0 == undef, we don't need to preserve faults!
3145     if (RHS->equalsInt(0))
3146       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3147     
3148     if (RHS->equalsInt(1))  // X % 1 == 0
3149       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3150
3151     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3152       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3153         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3154           return R;
3155       } else if (isa<PHINode>(Op0I)) {
3156         if (Instruction *NV = FoldOpIntoPhi(I))
3157           return NV;
3158       }
3159
3160       // See if we can fold away this rem instruction.
3161       if (SimplifyDemandedInstructionBits(I))
3162         return &I;
3163     }
3164   }
3165
3166   return 0;
3167 }
3168
3169 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3170   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3171
3172   if (Instruction *common = commonIRemTransforms(I))
3173     return common;
3174   
3175   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3176     // X urem C^2 -> X and C
3177     // Check to see if this is an unsigned remainder with an exact power of 2,
3178     // if so, convert to a bitwise and.
3179     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3180       if (C->getValue().isPowerOf2())
3181         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3182   }
3183
3184   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3185     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3186     if (RHSI->getOpcode() == Instruction::Shl &&
3187         isa<ConstantInt>(RHSI->getOperand(0))) {
3188       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3189         Constant *N1 = Constant::getAllOnesValue(I.getType());
3190         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3191                                                                    "tmp"), I);
3192         return BinaryOperator::CreateAnd(Op0, Add);
3193       }
3194     }
3195   }
3196
3197   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3198   // where C1&C2 are powers of two.
3199   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3200     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3201       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3202         // STO == 0 and SFO == 0 handled above.
3203         if ((STO->getValue().isPowerOf2()) && 
3204             (SFO->getValue().isPowerOf2())) {
3205           Value *TrueAnd = InsertNewInstBefore(
3206             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3207                                       SI->getName()+".t"), I);
3208           Value *FalseAnd = InsertNewInstBefore(
3209             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3210                                       SI->getName()+".f"), I);
3211           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3212         }
3213       }
3214   }
3215   
3216   return 0;
3217 }
3218
3219 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3220   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3221
3222   // Handle the integer rem common cases
3223   if (Instruction *common = commonIRemTransforms(I))
3224     return common;
3225   
3226   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3227     if (!isa<Constant>(RHSNeg) ||
3228         (isa<ConstantInt>(RHSNeg) &&
3229          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3230       // X % -Y -> X % Y
3231       AddUsesToWorkList(I);
3232       I.setOperand(1, RHSNeg);
3233       return &I;
3234     }
3235
3236   // If the sign bits of both operands are zero (i.e. we can prove they are
3237   // unsigned inputs), turn this into a urem.
3238   if (I.getType()->isInteger()) {
3239     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3240     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3241       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3242       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3243     }
3244   }
3245
3246   // If it's a constant vector, flip any negative values positive.
3247   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3248     unsigned VWidth = RHSV->getNumOperands();
3249
3250     bool hasNegative = false;
3251     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3252       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3253         if (RHS->getValue().isNegative())
3254           hasNegative = true;
3255
3256     if (hasNegative) {
3257       std::vector<Constant *> Elts(VWidth);
3258       for (unsigned i = 0; i != VWidth; ++i) {
3259         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3260           if (RHS->getValue().isNegative())
3261             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3262           else
3263             Elts[i] = RHS;
3264         }
3265       }
3266
3267       Constant *NewRHSV = ConstantVector::get(Elts);
3268       if (NewRHSV != RHSV) {
3269         AddUsesToWorkList(I);
3270         I.setOperand(1, NewRHSV);
3271         return &I;
3272       }
3273     }
3274   }
3275
3276   return 0;
3277 }
3278
3279 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3280   return commonRemTransforms(I);
3281 }
3282
3283 // isOneBitSet - Return true if there is exactly one bit set in the specified
3284 // constant.
3285 static bool isOneBitSet(const ConstantInt *CI) {
3286   return CI->getValue().isPowerOf2();
3287 }
3288
3289 // isHighOnes - Return true if the constant is of the form 1+0+.
3290 // This is the same as lowones(~X).
3291 static bool isHighOnes(const ConstantInt *CI) {
3292   return (~CI->getValue() + 1).isPowerOf2();
3293 }
3294
3295 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3296 /// are carefully arranged to allow folding of expressions such as:
3297 ///
3298 ///      (A < B) | (A > B) --> (A != B)
3299 ///
3300 /// Note that this is only valid if the first and second predicates have the
3301 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3302 ///
3303 /// Three bits are used to represent the condition, as follows:
3304 ///   0  A > B
3305 ///   1  A == B
3306 ///   2  A < B
3307 ///
3308 /// <=>  Value  Definition
3309 /// 000     0   Always false
3310 /// 001     1   A >  B
3311 /// 010     2   A == B
3312 /// 011     3   A >= B
3313 /// 100     4   A <  B
3314 /// 101     5   A != B
3315 /// 110     6   A <= B
3316 /// 111     7   Always true
3317 ///  
3318 static unsigned getICmpCode(const ICmpInst *ICI) {
3319   switch (ICI->getPredicate()) {
3320     // False -> 0
3321   case ICmpInst::ICMP_UGT: return 1;  // 001
3322   case ICmpInst::ICMP_SGT: return 1;  // 001
3323   case ICmpInst::ICMP_EQ:  return 2;  // 010
3324   case ICmpInst::ICMP_UGE: return 3;  // 011
3325   case ICmpInst::ICMP_SGE: return 3;  // 011
3326   case ICmpInst::ICMP_ULT: return 4;  // 100
3327   case ICmpInst::ICMP_SLT: return 4;  // 100
3328   case ICmpInst::ICMP_NE:  return 5;  // 101
3329   case ICmpInst::ICMP_ULE: return 6;  // 110
3330   case ICmpInst::ICMP_SLE: return 6;  // 110
3331     // True -> 7
3332   default:
3333     llvm_unreachable("Invalid ICmp predicate!");
3334     return 0;
3335   }
3336 }
3337
3338 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3339 /// predicate into a three bit mask. It also returns whether it is an ordered
3340 /// predicate by reference.
3341 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3342   isOrdered = false;
3343   switch (CC) {
3344   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3345   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3346   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3347   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3348   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3349   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3350   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3351   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3352   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3353   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3354   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3355   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3356   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3357   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3358     // True -> 7
3359   default:
3360     // Not expecting FCMP_FALSE and FCMP_TRUE;
3361     llvm_unreachable("Unexpected FCmp predicate!");
3362     return 0;
3363   }
3364 }
3365
3366 /// getICmpValue - This is the complement of getICmpCode, which turns an
3367 /// opcode and two operands into either a constant true or false, or a brand 
3368 /// new ICmp instruction. The sign is passed in to determine which kind
3369 /// of predicate to use in the new icmp instruction.
3370 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3371                            LLVMContext *Context) {
3372   switch (code) {
3373   default: llvm_unreachable("Illegal ICmp code!");
3374   case  0: return ConstantInt::getFalse(*Context);
3375   case  1: 
3376     if (sign)
3377       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3378     else
3379       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3380   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3381   case  3: 
3382     if (sign)
3383       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3384     else
3385       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3386   case  4: 
3387     if (sign)
3388       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3389     else
3390       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3391   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3392   case  6: 
3393     if (sign)
3394       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3395     else
3396       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3397   case  7: return ConstantInt::getTrue(*Context);
3398   }
3399 }
3400
3401 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3402 /// opcode and two operands into either a FCmp instruction. isordered is passed
3403 /// in to determine which kind of predicate to use in the new fcmp instruction.
3404 static Value *getFCmpValue(bool isordered, unsigned code,
3405                            Value *LHS, Value *RHS, LLVMContext *Context) {
3406   switch (code) {
3407   default: llvm_unreachable("Illegal FCmp code!");
3408   case  0:
3409     if (isordered)
3410       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3411     else
3412       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3413   case  1: 
3414     if (isordered)
3415       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3416     else
3417       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3418   case  2: 
3419     if (isordered)
3420       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3421     else
3422       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3423   case  3: 
3424     if (isordered)
3425       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3426     else
3427       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3428   case  4: 
3429     if (isordered)
3430       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3431     else
3432       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3433   case  5: 
3434     if (isordered)
3435       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3436     else
3437       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3438   case  6: 
3439     if (isordered)
3440       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3441     else
3442       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3443   case  7: return ConstantInt::getTrue(*Context);
3444   }
3445 }
3446
3447 /// PredicatesFoldable - Return true if both predicates match sign or if at
3448 /// least one of them is an equality comparison (which is signless).
3449 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3450   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3451          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3452          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3453 }
3454
3455 namespace { 
3456 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3457 struct FoldICmpLogical {
3458   InstCombiner &IC;
3459   Value *LHS, *RHS;
3460   ICmpInst::Predicate pred;
3461   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3462     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3463       pred(ICI->getPredicate()) {}
3464   bool shouldApply(Value *V) const {
3465     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3466       if (PredicatesFoldable(pred, ICI->getPredicate()))
3467         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3468                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3469     return false;
3470   }
3471   Instruction *apply(Instruction &Log) const {
3472     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3473     if (ICI->getOperand(0) != LHS) {
3474       assert(ICI->getOperand(1) == LHS);
3475       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3476     }
3477
3478     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3479     unsigned LHSCode = getICmpCode(ICI);
3480     unsigned RHSCode = getICmpCode(RHSICI);
3481     unsigned Code;
3482     switch (Log.getOpcode()) {
3483     case Instruction::And: Code = LHSCode & RHSCode; break;
3484     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3485     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3486     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3487     }
3488
3489     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3490                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3491       
3492     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3493     if (Instruction *I = dyn_cast<Instruction>(RV))
3494       return I;
3495     // Otherwise, it's a constant boolean value...
3496     return IC.ReplaceInstUsesWith(Log, RV);
3497   }
3498 };
3499 } // end anonymous namespace
3500
3501 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3502 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3503 // guaranteed to be a binary operator.
3504 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3505                                     ConstantInt *OpRHS,
3506                                     ConstantInt *AndRHS,
3507                                     BinaryOperator &TheAnd) {
3508   Value *X = Op->getOperand(0);
3509   Constant *Together = 0;
3510   if (!Op->isShift())
3511     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3512
3513   switch (Op->getOpcode()) {
3514   case Instruction::Xor:
3515     if (Op->hasOneUse()) {
3516       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3517       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3518       InsertNewInstBefore(And, TheAnd);
3519       And->takeName(Op);
3520       return BinaryOperator::CreateXor(And, Together);
3521     }
3522     break;
3523   case Instruction::Or:
3524     if (Together == AndRHS) // (X | C) & C --> C
3525       return ReplaceInstUsesWith(TheAnd, AndRHS);
3526
3527     if (Op->hasOneUse() && Together != OpRHS) {
3528       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3529       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3530       InsertNewInstBefore(Or, TheAnd);
3531       Or->takeName(Op);
3532       return BinaryOperator::CreateAnd(Or, AndRHS);
3533     }
3534     break;
3535   case Instruction::Add:
3536     if (Op->hasOneUse()) {
3537       // Adding a one to a single bit bit-field should be turned into an XOR
3538       // of the bit.  First thing to check is to see if this AND is with a
3539       // single bit constant.
3540       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3541
3542       // If there is only one bit set...
3543       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3544         // Ok, at this point, we know that we are masking the result of the
3545         // ADD down to exactly one bit.  If the constant we are adding has
3546         // no bits set below this bit, then we can eliminate the ADD.
3547         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3548
3549         // Check to see if any bits below the one bit set in AndRHSV are set.
3550         if ((AddRHS & (AndRHSV-1)) == 0) {
3551           // If not, the only thing that can effect the output of the AND is
3552           // the bit specified by AndRHSV.  If that bit is set, the effect of
3553           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3554           // no effect.
3555           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3556             TheAnd.setOperand(0, X);
3557             return &TheAnd;
3558           } else {
3559             // Pull the XOR out of the AND.
3560             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3561             InsertNewInstBefore(NewAnd, TheAnd);
3562             NewAnd->takeName(Op);
3563             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3564           }
3565         }
3566       }
3567     }
3568     break;
3569
3570   case Instruction::Shl: {
3571     // We know that the AND will not produce any of the bits shifted in, so if
3572     // the anded constant includes them, clear them now!
3573     //
3574     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3575     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3576     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3577     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3578
3579     if (CI->getValue() == ShlMask) { 
3580     // Masking out bits that the shift already masks
3581       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3582     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3583       TheAnd.setOperand(1, CI);
3584       return &TheAnd;
3585     }
3586     break;
3587   }
3588   case Instruction::LShr:
3589   {
3590     // We know that the AND will not produce any of the bits shifted in, so if
3591     // the anded constant includes them, clear them now!  This only applies to
3592     // unsigned shifts, because a signed shr may bring in set bits!
3593     //
3594     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3595     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3596     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3597     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3598
3599     if (CI->getValue() == ShrMask) {   
3600     // Masking out bits that the shift already masks.
3601       return ReplaceInstUsesWith(TheAnd, Op);
3602     } else if (CI != AndRHS) {
3603       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3604       return &TheAnd;
3605     }
3606     break;
3607   }
3608   case Instruction::AShr:
3609     // Signed shr.
3610     // See if this is shifting in some sign extension, then masking it out
3611     // with an and.
3612     if (Op->hasOneUse()) {
3613       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3614       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3615       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3616       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3617       if (C == AndRHS) {          // Masking out bits shifted in.
3618         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3619         // Make the argument unsigned.
3620         Value *ShVal = Op->getOperand(0);
3621         ShVal = InsertNewInstBefore(
3622             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3623                                    Op->getName()), TheAnd);
3624         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3625       }
3626     }
3627     break;
3628   }
3629   return 0;
3630 }
3631
3632
3633 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3634 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3635 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3636 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3637 /// insert new instructions.
3638 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3639                                            bool isSigned, bool Inside, 
3640                                            Instruction &IB) {
3641   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3642             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3643          "Lo is not <= Hi in range emission code!");
3644     
3645   if (Inside) {
3646     if (Lo == Hi)  // Trivially false.
3647       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3648
3649     // V >= Min && V < Hi --> V < Hi
3650     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3651       ICmpInst::Predicate pred = (isSigned ? 
3652         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3653       return new ICmpInst(*Context, pred, V, Hi);
3654     }
3655
3656     // Emit V-Lo <u Hi-Lo
3657     Constant *NegLo = ConstantExpr::getNeg(Lo);
3658     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3659     InsertNewInstBefore(Add, IB);
3660     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3661     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3662   }
3663
3664   if (Lo == Hi)  // Trivially true.
3665     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3666
3667   // V < Min || V >= Hi -> V > Hi-1
3668   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3669   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3670     ICmpInst::Predicate pred = (isSigned ? 
3671         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3672     return new ICmpInst(*Context, pred, V, Hi);
3673   }
3674
3675   // Emit V-Lo >u Hi-1-Lo
3676   // Note that Hi has already had one subtracted from it, above.
3677   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3678   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3679   InsertNewInstBefore(Add, IB);
3680   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3681   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3682 }
3683
3684 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3685 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3686 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3687 // not, since all 1s are not contiguous.
3688 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3689   const APInt& V = Val->getValue();
3690   uint32_t BitWidth = Val->getType()->getBitWidth();
3691   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3692
3693   // look for the first zero bit after the run of ones
3694   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3695   // look for the first non-zero bit
3696   ME = V.getActiveBits(); 
3697   return true;
3698 }
3699
3700 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3701 /// where isSub determines whether the operator is a sub.  If we can fold one of
3702 /// the following xforms:
3703 /// 
3704 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3705 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3706 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3707 ///
3708 /// return (A +/- B).
3709 ///
3710 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3711                                         ConstantInt *Mask, bool isSub,
3712                                         Instruction &I) {
3713   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3714   if (!LHSI || LHSI->getNumOperands() != 2 ||
3715       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3716
3717   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3718
3719   switch (LHSI->getOpcode()) {
3720   default: return 0;
3721   case Instruction::And:
3722     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3723       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3724       if ((Mask->getValue().countLeadingZeros() + 
3725            Mask->getValue().countPopulation()) == 
3726           Mask->getValue().getBitWidth())
3727         break;
3728
3729       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3730       // part, we don't need any explicit masks to take them out of A.  If that
3731       // is all N is, ignore it.
3732       uint32_t MB = 0, ME = 0;
3733       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3734         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3735         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3736         if (MaskedValueIsZero(RHS, Mask))
3737           break;
3738       }
3739     }
3740     return 0;
3741   case Instruction::Or:
3742   case Instruction::Xor:
3743     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3744     if ((Mask->getValue().countLeadingZeros() + 
3745          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3746         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3747       break;
3748     return 0;
3749   }
3750   
3751   Instruction *New;
3752   if (isSub)
3753     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3754   else
3755     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3756   return InsertNewInstBefore(New, I);
3757 }
3758
3759 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3760 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3761                                           ICmpInst *LHS, ICmpInst *RHS) {
3762   Value *Val, *Val2;
3763   ConstantInt *LHSCst, *RHSCst;
3764   ICmpInst::Predicate LHSCC, RHSCC;
3765   
3766   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3767   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3768                          m_ConstantInt(LHSCst)), *Context) ||
3769       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3770                          m_ConstantInt(RHSCst)), *Context))
3771     return 0;
3772   
3773   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3774   // where C is a power of 2
3775   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3776       LHSCst->getValue().isPowerOf2()) {
3777     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3778     InsertNewInstBefore(NewOr, I);
3779     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3780   }
3781   
3782   // From here on, we only handle:
3783   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3784   if (Val != Val2) return 0;
3785   
3786   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3787   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3788       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3789       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3790       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3791     return 0;
3792   
3793   // We can't fold (ugt x, C) & (sgt x, C2).
3794   if (!PredicatesFoldable(LHSCC, RHSCC))
3795     return 0;
3796     
3797   // Ensure that the larger constant is on the RHS.
3798   bool ShouldSwap;
3799   if (ICmpInst::isSignedPredicate(LHSCC) ||
3800       (ICmpInst::isEquality(LHSCC) && 
3801        ICmpInst::isSignedPredicate(RHSCC)))
3802     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3803   else
3804     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3805     
3806   if (ShouldSwap) {
3807     std::swap(LHS, RHS);
3808     std::swap(LHSCst, RHSCst);
3809     std::swap(LHSCC, RHSCC);
3810   }
3811
3812   // At this point, we know we have have two icmp instructions
3813   // comparing a value against two constants and and'ing the result
3814   // together.  Because of the above check, we know that we only have
3815   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3816   // (from the FoldICmpLogical check above), that the two constants 
3817   // are not equal and that the larger constant is on the RHS
3818   assert(LHSCst != RHSCst && "Compares not folded above?");
3819
3820   switch (LHSCC) {
3821   default: llvm_unreachable("Unknown integer condition code!");
3822   case ICmpInst::ICMP_EQ:
3823     switch (RHSCC) {
3824     default: llvm_unreachable("Unknown integer condition code!");
3825     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3826     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3827     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3828       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3829     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3830     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3831     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3832       return ReplaceInstUsesWith(I, LHS);
3833     }
3834   case ICmpInst::ICMP_NE:
3835     switch (RHSCC) {
3836     default: llvm_unreachable("Unknown integer condition code!");
3837     case ICmpInst::ICMP_ULT:
3838       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3839         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3840       break;                        // (X != 13 & X u< 15) -> no change
3841     case ICmpInst::ICMP_SLT:
3842       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3843         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3844       break;                        // (X != 13 & X s< 15) -> no change
3845     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3846     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3847     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3848       return ReplaceInstUsesWith(I, RHS);
3849     case ICmpInst::ICMP_NE:
3850       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3851         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3852         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3853                                                      Val->getName()+".off");
3854         InsertNewInstBefore(Add, I);
3855         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3856                             ConstantInt::get(Add->getType(), 1));
3857       }
3858       break;                        // (X != 13 & X != 15) -> no change
3859     }
3860     break;
3861   case ICmpInst::ICMP_ULT:
3862     switch (RHSCC) {
3863     default: llvm_unreachable("Unknown integer condition code!");
3864     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3865     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3866       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3867     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3868       break;
3869     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3870     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3871       return ReplaceInstUsesWith(I, LHS);
3872     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3873       break;
3874     }
3875     break;
3876   case ICmpInst::ICMP_SLT:
3877     switch (RHSCC) {
3878     default: llvm_unreachable("Unknown integer condition code!");
3879     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3880     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3881       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3882     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3883       break;
3884     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3885     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3886       return ReplaceInstUsesWith(I, LHS);
3887     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3888       break;
3889     }
3890     break;
3891   case ICmpInst::ICMP_UGT:
3892     switch (RHSCC) {
3893     default: llvm_unreachable("Unknown integer condition code!");
3894     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3895     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3896       return ReplaceInstUsesWith(I, RHS);
3897     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3898       break;
3899     case ICmpInst::ICMP_NE:
3900       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3901         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3902       break;                        // (X u> 13 & X != 15) -> no change
3903     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3904       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3905                              RHSCst, false, true, I);
3906     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3907       break;
3908     }
3909     break;
3910   case ICmpInst::ICMP_SGT:
3911     switch (RHSCC) {
3912     default: llvm_unreachable("Unknown integer condition code!");
3913     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3914     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3915       return ReplaceInstUsesWith(I, RHS);
3916     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3917       break;
3918     case ICmpInst::ICMP_NE:
3919       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3920         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3921       break;                        // (X s> 13 & X != 15) -> no change
3922     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3923       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3924                              RHSCst, true, true, I);
3925     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3926       break;
3927     }
3928     break;
3929   }
3930  
3931   return 0;
3932 }
3933
3934 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3935                                           FCmpInst *RHS) {
3936   
3937   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3938       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3939     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3940     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3941       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3942         // If either of the constants are nans, then the whole thing returns
3943         // false.
3944         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3945           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3946         return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
3947                             LHS->getOperand(0), RHS->getOperand(0));
3948       }
3949     
3950     // Handle vector zeros.  This occurs because the canonical form of
3951     // "fcmp ord x,x" is "fcmp ord x, 0".
3952     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3953         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3954       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
3955                           LHS->getOperand(0), RHS->getOperand(0));
3956     return 0;
3957   }
3958   
3959   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3960   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3961   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3962   
3963   
3964   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3965     // Swap RHS operands to match LHS.
3966     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3967     std::swap(Op1LHS, Op1RHS);
3968   }
3969   
3970   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3971     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3972     if (Op0CC == Op1CC)
3973       return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3974     
3975     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3976       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3977     if (Op0CC == FCmpInst::FCMP_TRUE)
3978       return ReplaceInstUsesWith(I, RHS);
3979     if (Op1CC == FCmpInst::FCMP_TRUE)
3980       return ReplaceInstUsesWith(I, LHS);
3981     
3982     bool Op0Ordered;
3983     bool Op1Ordered;
3984     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3985     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3986     if (Op1Pred == 0) {
3987       std::swap(LHS, RHS);
3988       std::swap(Op0Pred, Op1Pred);
3989       std::swap(Op0Ordered, Op1Ordered);
3990     }
3991     if (Op0Pred == 0) {
3992       // uno && ueq -> uno && (uno || eq) -> ueq
3993       // ord && olt -> ord && (ord && lt) -> olt
3994       if (Op0Ordered == Op1Ordered)
3995         return ReplaceInstUsesWith(I, RHS);
3996       
3997       // uno && oeq -> uno && (ord && eq) -> false
3998       // uno && ord -> false
3999       if (!Op0Ordered)
4000         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4001       // ord && ueq -> ord && (uno || eq) -> oeq
4002       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4003                                             Op0LHS, Op0RHS, Context));
4004     }
4005   }
4006
4007   return 0;
4008 }
4009
4010
4011 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4012   bool Changed = SimplifyCommutative(I);
4013   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4014
4015   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4016     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4017
4018   // and X, X = X
4019   if (Op0 == Op1)
4020     return ReplaceInstUsesWith(I, Op1);
4021
4022   // See if we can simplify any instructions used by the instruction whose sole 
4023   // purpose is to compute bits we don't care about.
4024   if (SimplifyDemandedInstructionBits(I))
4025     return &I;
4026   if (isa<VectorType>(I.getType())) {
4027     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4028       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4029         return ReplaceInstUsesWith(I, I.getOperand(0));
4030     } else if (isa<ConstantAggregateZero>(Op1)) {
4031       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4032     }
4033   }
4034
4035   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4036     const APInt& AndRHSMask = AndRHS->getValue();
4037     APInt NotAndRHS(~AndRHSMask);
4038
4039     // Optimize a variety of ((val OP C1) & C2) combinations...
4040     if (isa<BinaryOperator>(Op0)) {
4041       Instruction *Op0I = cast<Instruction>(Op0);
4042       Value *Op0LHS = Op0I->getOperand(0);
4043       Value *Op0RHS = Op0I->getOperand(1);
4044       switch (Op0I->getOpcode()) {
4045       case Instruction::Xor:
4046       case Instruction::Or:
4047         // If the mask is only needed on one incoming arm, push it up.
4048         if (Op0I->hasOneUse()) {
4049           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4050             // Not masking anything out for the LHS, move to RHS.
4051             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4052                                                    Op0RHS->getName()+".masked");
4053             InsertNewInstBefore(NewRHS, I);
4054             return BinaryOperator::Create(
4055                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4056           }
4057           if (!isa<Constant>(Op0RHS) &&
4058               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4059             // Not masking anything out for the RHS, move to LHS.
4060             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4061                                                    Op0LHS->getName()+".masked");
4062             InsertNewInstBefore(NewLHS, I);
4063             return BinaryOperator::Create(
4064                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4065           }
4066         }
4067
4068         break;
4069       case Instruction::Add:
4070         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4071         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4072         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4073         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4074           return BinaryOperator::CreateAnd(V, AndRHS);
4075         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4076           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4077         break;
4078
4079       case Instruction::Sub:
4080         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4081         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4082         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4083         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4084           return BinaryOperator::CreateAnd(V, AndRHS);
4085
4086         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4087         // has 1's for all bits that the subtraction with A might affect.
4088         if (Op0I->hasOneUse()) {
4089           uint32_t BitWidth = AndRHSMask.getBitWidth();
4090           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4091           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4092
4093           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4094           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4095               MaskedValueIsZero(Op0LHS, Mask)) {
4096             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4097             InsertNewInstBefore(NewNeg, I);
4098             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4099           }
4100         }
4101         break;
4102
4103       case Instruction::Shl:
4104       case Instruction::LShr:
4105         // (1 << x) & 1 --> zext(x == 0)
4106         // (1 >> x) & 1 --> zext(x == 0)
4107         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4108           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4109                                     Op0RHS, Constant::getNullValue(I.getType()));
4110           InsertNewInstBefore(NewICmp, I);
4111           return new ZExtInst(NewICmp, I.getType());
4112         }
4113         break;
4114       }
4115
4116       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4117         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4118           return Res;
4119     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4120       // If this is an integer truncation or change from signed-to-unsigned, and
4121       // if the source is an and/or with immediate, transform it.  This
4122       // frequently occurs for bitfield accesses.
4123       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4124         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4125             CastOp->getNumOperands() == 2)
4126           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4127             if (CastOp->getOpcode() == Instruction::And) {
4128               // Change: and (cast (and X, C1) to T), C2
4129               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4130               // This will fold the two constants together, which may allow 
4131               // other simplifications.
4132               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4133                 CastOp->getOperand(0), I.getType(), 
4134                 CastOp->getName()+".shrunk");
4135               NewCast = InsertNewInstBefore(NewCast, I);
4136               // trunc_or_bitcast(C1)&C2
4137               Constant *C3 =
4138                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4139               C3 = ConstantExpr::getAnd(C3, AndRHS);
4140               return BinaryOperator::CreateAnd(NewCast, C3);
4141             } else if (CastOp->getOpcode() == Instruction::Or) {
4142               // Change: and (cast (or X, C1) to T), C2
4143               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4144               Constant *C3 =
4145                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4146               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4147                 // trunc(C1)&C2
4148                 return ReplaceInstUsesWith(I, AndRHS);
4149             }
4150           }
4151       }
4152     }
4153
4154     // Try to fold constant and into select arguments.
4155     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4156       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4157         return R;
4158     if (isa<PHINode>(Op0))
4159       if (Instruction *NV = FoldOpIntoPhi(I))
4160         return NV;
4161   }
4162
4163   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4164   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4165
4166   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4167     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4168
4169   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4170   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4171     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4172                                                I.getName()+".demorgan");
4173     InsertNewInstBefore(Or, I);
4174     return BinaryOperator::CreateNot(*Context, Or);
4175   }
4176   
4177   {
4178     Value *A = 0, *B = 0, *C = 0, *D = 0;
4179     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4180       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4181         return ReplaceInstUsesWith(I, Op1);
4182     
4183       // (A|B) & ~(A&B) -> A^B
4184       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4185         if ((A == C && B == D) || (A == D && B == C))
4186           return BinaryOperator::CreateXor(A, B);
4187       }
4188     }
4189     
4190     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4191       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4192         return ReplaceInstUsesWith(I, Op0);
4193
4194       // ~(A&B) & (A|B) -> A^B
4195       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4196         if ((A == C && B == D) || (A == D && B == C))
4197           return BinaryOperator::CreateXor(A, B);
4198       }
4199     }
4200     
4201     if (Op0->hasOneUse() &&
4202         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4203       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4204         I.swapOperands();     // Simplify below
4205         std::swap(Op0, Op1);
4206       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4207         cast<BinaryOperator>(Op0)->swapOperands();
4208         I.swapOperands();     // Simplify below
4209         std::swap(Op0, Op1);
4210       }
4211     }
4212
4213     if (Op1->hasOneUse() &&
4214         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4215       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4216         cast<BinaryOperator>(Op1)->swapOperands();
4217         std::swap(A, B);
4218       }
4219       if (A == Op0) {                                // A&(A^B) -> A & ~B
4220         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4221         InsertNewInstBefore(NotB, I);
4222         return BinaryOperator::CreateAnd(A, NotB);
4223       }
4224     }
4225
4226     // (A&((~A)|B)) -> A&B
4227     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4228         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4229       return BinaryOperator::CreateAnd(A, Op1);
4230     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4231         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4232       return BinaryOperator::CreateAnd(A, Op0);
4233   }
4234   
4235   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4236     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4237     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4238       return R;
4239
4240     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4241       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4242         return Res;
4243   }
4244
4245   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4246   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4247     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4248       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4249         const Type *SrcTy = Op0C->getOperand(0)->getType();
4250         if (SrcTy == Op1C->getOperand(0)->getType() &&
4251             SrcTy->isIntOrIntVector() &&
4252             // Only do this if the casts both really cause code to be generated.
4253             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4254                               I.getType(), TD) &&
4255             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4256                               I.getType(), TD)) {
4257           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4258                                                          Op1C->getOperand(0),
4259                                                          I.getName());
4260           InsertNewInstBefore(NewOp, I);
4261           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4262         }
4263       }
4264     
4265   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4266   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4267     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4268       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4269           SI0->getOperand(1) == SI1->getOperand(1) &&
4270           (SI0->hasOneUse() || SI1->hasOneUse())) {
4271         Instruction *NewOp =
4272           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4273                                                         SI1->getOperand(0),
4274                                                         SI0->getName()), I);
4275         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4276                                       SI1->getOperand(1));
4277       }
4278   }
4279
4280   // If and'ing two fcmp, try combine them into one.
4281   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4282     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4283       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4284         return Res;
4285   }
4286
4287   return Changed ? &I : 0;
4288 }
4289
4290 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4291 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4292 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4293 /// the expression came from the corresponding "byte swapped" byte in some other
4294 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4295 /// we know that the expression deposits the low byte of %X into the high byte
4296 /// of the bswap result and that all other bytes are zero.  This expression is
4297 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4298 /// match.
4299 ///
4300 /// This function returns true if the match was unsuccessful and false if so.
4301 /// On entry to the function the "OverallLeftShift" is a signed integer value
4302 /// indicating the number of bytes that the subexpression is later shifted.  For
4303 /// example, if the expression is later right shifted by 16 bits, the
4304 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4305 /// byte of ByteValues is actually being set.
4306 ///
4307 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4308 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4309 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4310 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4311 /// always in the local (OverallLeftShift) coordinate space.
4312 ///
4313 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4314                               SmallVector<Value*, 8> &ByteValues) {
4315   if (Instruction *I = dyn_cast<Instruction>(V)) {
4316     // If this is an or instruction, it may be an inner node of the bswap.
4317     if (I->getOpcode() == Instruction::Or) {
4318       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4319                                ByteValues) ||
4320              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4321                                ByteValues);
4322     }
4323   
4324     // If this is a logical shift by a constant multiple of 8, recurse with
4325     // OverallLeftShift and ByteMask adjusted.
4326     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4327       unsigned ShAmt = 
4328         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4329       // Ensure the shift amount is defined and of a byte value.
4330       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4331         return true;
4332
4333       unsigned ByteShift = ShAmt >> 3;
4334       if (I->getOpcode() == Instruction::Shl) {
4335         // X << 2 -> collect(X, +2)
4336         OverallLeftShift += ByteShift;
4337         ByteMask >>= ByteShift;
4338       } else {
4339         // X >>u 2 -> collect(X, -2)
4340         OverallLeftShift -= ByteShift;
4341         ByteMask <<= ByteShift;
4342         ByteMask &= (~0U >> (32-ByteValues.size()));
4343       }
4344
4345       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4346       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4347
4348       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4349                                ByteValues);
4350     }
4351
4352     // If this is a logical 'and' with a mask that clears bytes, clear the
4353     // corresponding bytes in ByteMask.
4354     if (I->getOpcode() == Instruction::And &&
4355         isa<ConstantInt>(I->getOperand(1))) {
4356       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4357       unsigned NumBytes = ByteValues.size();
4358       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4359       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4360       
4361       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4362         // If this byte is masked out by a later operation, we don't care what
4363         // the and mask is.
4364         if ((ByteMask & (1 << i)) == 0)
4365           continue;
4366         
4367         // If the AndMask is all zeros for this byte, clear the bit.
4368         APInt MaskB = AndMask & Byte;
4369         if (MaskB == 0) {
4370           ByteMask &= ~(1U << i);
4371           continue;
4372         }
4373         
4374         // If the AndMask is not all ones for this byte, it's not a bytezap.
4375         if (MaskB != Byte)
4376           return true;
4377
4378         // Otherwise, this byte is kept.
4379       }
4380
4381       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4382                                ByteValues);
4383     }
4384   }
4385   
4386   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4387   // the input value to the bswap.  Some observations: 1) if more than one byte
4388   // is demanded from this input, then it could not be successfully assembled
4389   // into a byteswap.  At least one of the two bytes would not be aligned with
4390   // their ultimate destination.
4391   if (!isPowerOf2_32(ByteMask)) return true;
4392   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4393   
4394   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4395   // is demanded, it needs to go into byte 0 of the result.  This means that the
4396   // byte needs to be shifted until it lands in the right byte bucket.  The
4397   // shift amount depends on the position: if the byte is coming from the high
4398   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4399   // low part, it must be shifted left.
4400   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4401   if (InputByteNo < ByteValues.size()/2) {
4402     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4403       return true;
4404   } else {
4405     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4406       return true;
4407   }
4408   
4409   // If the destination byte value is already defined, the values are or'd
4410   // together, which isn't a bswap (unless it's an or of the same bits).
4411   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4412     return true;
4413   ByteValues[DestByteNo] = V;
4414   return false;
4415 }
4416
4417 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4418 /// If so, insert the new bswap intrinsic and return it.
4419 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4420   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4421   if (!ITy || ITy->getBitWidth() % 16 || 
4422       // ByteMask only allows up to 32-byte values.
4423       ITy->getBitWidth() > 32*8) 
4424     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4425   
4426   /// ByteValues - For each byte of the result, we keep track of which value
4427   /// defines each byte.
4428   SmallVector<Value*, 8> ByteValues;
4429   ByteValues.resize(ITy->getBitWidth()/8);
4430     
4431   // Try to find all the pieces corresponding to the bswap.
4432   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4433   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4434     return 0;
4435   
4436   // Check to see if all of the bytes come from the same value.
4437   Value *V = ByteValues[0];
4438   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4439   
4440   // Check to make sure that all of the bytes come from the same value.
4441   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4442     if (ByteValues[i] != V)
4443       return 0;
4444   const Type *Tys[] = { ITy };
4445   Module *M = I.getParent()->getParent()->getParent();
4446   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4447   return CallInst::Create(F, V);
4448 }
4449
4450 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4451 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4452 /// we can simplify this expression to "cond ? C : D or B".
4453 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4454                                          Value *C, Value *D,
4455                                          LLVMContext *Context) {
4456   // If A is not a select of -1/0, this cannot match.
4457   Value *Cond = 0;
4458   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4459     return 0;
4460
4461   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4462   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4463     return SelectInst::Create(Cond, C, B);
4464   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4465     return SelectInst::Create(Cond, C, B);
4466   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4467   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4468     return SelectInst::Create(Cond, C, D);
4469   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4470     return SelectInst::Create(Cond, C, D);
4471   return 0;
4472 }
4473
4474 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4475 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4476                                          ICmpInst *LHS, ICmpInst *RHS) {
4477   Value *Val, *Val2;
4478   ConstantInt *LHSCst, *RHSCst;
4479   ICmpInst::Predicate LHSCC, RHSCC;
4480   
4481   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4482   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4483              m_ConstantInt(LHSCst)), *Context) ||
4484       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4485              m_ConstantInt(RHSCst)), *Context))
4486     return 0;
4487   
4488   // From here on, we only handle:
4489   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4490   if (Val != Val2) return 0;
4491   
4492   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4493   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4494       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4495       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4496       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4497     return 0;
4498   
4499   // We can't fold (ugt x, C) | (sgt x, C2).
4500   if (!PredicatesFoldable(LHSCC, RHSCC))
4501     return 0;
4502   
4503   // Ensure that the larger constant is on the RHS.
4504   bool ShouldSwap;
4505   if (ICmpInst::isSignedPredicate(LHSCC) ||
4506       (ICmpInst::isEquality(LHSCC) && 
4507        ICmpInst::isSignedPredicate(RHSCC)))
4508     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4509   else
4510     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4511   
4512   if (ShouldSwap) {
4513     std::swap(LHS, RHS);
4514     std::swap(LHSCst, RHSCst);
4515     std::swap(LHSCC, RHSCC);
4516   }
4517   
4518   // At this point, we know we have have two icmp instructions
4519   // comparing a value against two constants and or'ing the result
4520   // together.  Because of the above check, we know that we only have
4521   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4522   // FoldICmpLogical check above), that the two constants are not
4523   // equal.
4524   assert(LHSCst != RHSCst && "Compares not folded above?");
4525
4526   switch (LHSCC) {
4527   default: llvm_unreachable("Unknown integer condition code!");
4528   case ICmpInst::ICMP_EQ:
4529     switch (RHSCC) {
4530     default: llvm_unreachable("Unknown integer condition code!");
4531     case ICmpInst::ICMP_EQ:
4532       if (LHSCst == SubOne(RHSCst, Context)) {
4533         // (X == 13 | X == 14) -> X-13 <u 2
4534         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4535         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4536                                                      Val->getName()+".off");
4537         InsertNewInstBefore(Add, I);
4538         AddCST = ConstantExpr::getSub(AddOne(RHSCst, Context), LHSCst);
4539         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4540       }
4541       break;                         // (X == 13 | X == 15) -> no change
4542     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4543     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4544       break;
4545     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4546     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4547     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4548       return ReplaceInstUsesWith(I, RHS);
4549     }
4550     break;
4551   case ICmpInst::ICMP_NE:
4552     switch (RHSCC) {
4553     default: llvm_unreachable("Unknown integer condition code!");
4554     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4555     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4556     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4557       return ReplaceInstUsesWith(I, LHS);
4558     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4559     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4560     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4561       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4562     }
4563     break;
4564   case ICmpInst::ICMP_ULT:
4565     switch (RHSCC) {
4566     default: llvm_unreachable("Unknown integer condition code!");
4567     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4568       break;
4569     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4570       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4571       // this can cause overflow.
4572       if (RHSCst->isMaxValue(false))
4573         return ReplaceInstUsesWith(I, LHS);
4574       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4575                              false, false, I);
4576     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4577       break;
4578     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4579     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4580       return ReplaceInstUsesWith(I, RHS);
4581     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4582       break;
4583     }
4584     break;
4585   case ICmpInst::ICMP_SLT:
4586     switch (RHSCC) {
4587     default: llvm_unreachable("Unknown integer condition code!");
4588     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4589       break;
4590     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4591       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4592       // this can cause overflow.
4593       if (RHSCst->isMaxValue(true))
4594         return ReplaceInstUsesWith(I, LHS);
4595       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4596                              true, false, I);
4597     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4598       break;
4599     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4600     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4601       return ReplaceInstUsesWith(I, RHS);
4602     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4603       break;
4604     }
4605     break;
4606   case ICmpInst::ICMP_UGT:
4607     switch (RHSCC) {
4608     default: llvm_unreachable("Unknown integer condition code!");
4609     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4610     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4611       return ReplaceInstUsesWith(I, LHS);
4612     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4613       break;
4614     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4615     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4616       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4617     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4618       break;
4619     }
4620     break;
4621   case ICmpInst::ICMP_SGT:
4622     switch (RHSCC) {
4623     default: llvm_unreachable("Unknown integer condition code!");
4624     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4625     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4626       return ReplaceInstUsesWith(I, LHS);
4627     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4628       break;
4629     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4630     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4631       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4632     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4633       break;
4634     }
4635     break;
4636   }
4637   return 0;
4638 }
4639
4640 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4641                                          FCmpInst *RHS) {
4642   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4643       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4644       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4645     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4646       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4647         // If either of the constants are nans, then the whole thing returns
4648         // true.
4649         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4650           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4651         
4652         // Otherwise, no need to compare the two constants, compare the
4653         // rest.
4654         return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4655                             LHS->getOperand(0), RHS->getOperand(0));
4656       }
4657     
4658     // Handle vector zeros.  This occurs because the canonical form of
4659     // "fcmp uno x,x" is "fcmp uno x, 0".
4660     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4661         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4662       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4663                           LHS->getOperand(0), RHS->getOperand(0));
4664     
4665     return 0;
4666   }
4667   
4668   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4669   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4670   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4671   
4672   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4673     // Swap RHS operands to match LHS.
4674     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4675     std::swap(Op1LHS, Op1RHS);
4676   }
4677   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4678     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4679     if (Op0CC == Op1CC)
4680       return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4681                           Op0LHS, Op0RHS);
4682     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4683       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4684     if (Op0CC == FCmpInst::FCMP_FALSE)
4685       return ReplaceInstUsesWith(I, RHS);
4686     if (Op1CC == FCmpInst::FCMP_FALSE)
4687       return ReplaceInstUsesWith(I, LHS);
4688     bool Op0Ordered;
4689     bool Op1Ordered;
4690     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4691     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4692     if (Op0Ordered == Op1Ordered) {
4693       // If both are ordered or unordered, return a new fcmp with
4694       // or'ed predicates.
4695       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4696                                Op0LHS, Op0RHS, Context);
4697       if (Instruction *I = dyn_cast<Instruction>(RV))
4698         return I;
4699       // Otherwise, it's a constant boolean value...
4700       return ReplaceInstUsesWith(I, RV);
4701     }
4702   }
4703   return 0;
4704 }
4705
4706 /// FoldOrWithConstants - This helper function folds:
4707 ///
4708 ///     ((A | B) & C1) | (B & C2)
4709 ///
4710 /// into:
4711 /// 
4712 ///     (A & C1) | B
4713 ///
4714 /// when the XOR of the two constants is "all ones" (-1).
4715 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4716                                                Value *A, Value *B, Value *C) {
4717   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4718   if (!CI1) return 0;
4719
4720   Value *V1 = 0;
4721   ConstantInt *CI2 = 0;
4722   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4723
4724   APInt Xor = CI1->getValue() ^ CI2->getValue();
4725   if (!Xor.isAllOnesValue()) return 0;
4726
4727   if (V1 == A || V1 == B) {
4728     Instruction *NewOp =
4729       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4730     return BinaryOperator::CreateOr(NewOp, V1);
4731   }
4732
4733   return 0;
4734 }
4735
4736 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4737   bool Changed = SimplifyCommutative(I);
4738   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4739
4740   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4741     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4742
4743   // or X, X = X
4744   if (Op0 == Op1)
4745     return ReplaceInstUsesWith(I, Op0);
4746
4747   // See if we can simplify any instructions used by the instruction whose sole 
4748   // purpose is to compute bits we don't care about.
4749   if (SimplifyDemandedInstructionBits(I))
4750     return &I;
4751   if (isa<VectorType>(I.getType())) {
4752     if (isa<ConstantAggregateZero>(Op1)) {
4753       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4754     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4755       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4756         return ReplaceInstUsesWith(I, I.getOperand(1));
4757     }
4758   }
4759
4760   // or X, -1 == -1
4761   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4762     ConstantInt *C1 = 0; Value *X = 0;
4763     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4764     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4765         isOnlyUse(Op0)) {
4766       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4767       InsertNewInstBefore(Or, I);
4768       Or->takeName(Op0);
4769       return BinaryOperator::CreateAnd(Or, 
4770                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4771     }
4772
4773     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4774     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4775         isOnlyUse(Op0)) {
4776       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4777       InsertNewInstBefore(Or, I);
4778       Or->takeName(Op0);
4779       return BinaryOperator::CreateXor(Or,
4780                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4781     }
4782
4783     // Try to fold constant and into select arguments.
4784     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4785       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4786         return R;
4787     if (isa<PHINode>(Op0))
4788       if (Instruction *NV = FoldOpIntoPhi(I))
4789         return NV;
4790   }
4791
4792   Value *A = 0, *B = 0;
4793   ConstantInt *C1 = 0, *C2 = 0;
4794
4795   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4796     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4797       return ReplaceInstUsesWith(I, Op1);
4798   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4799     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4800       return ReplaceInstUsesWith(I, Op0);
4801
4802   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4803   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4804   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4805       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4806       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4807        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4808     if (Instruction *BSwap = MatchBSwap(I))
4809       return BSwap;
4810   }
4811   
4812   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4813   if (Op0->hasOneUse() &&
4814       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4815       MaskedValueIsZero(Op1, C1->getValue())) {
4816     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4817     InsertNewInstBefore(NOr, I);
4818     NOr->takeName(Op0);
4819     return BinaryOperator::CreateXor(NOr, C1);
4820   }
4821
4822   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4823   if (Op1->hasOneUse() &&
4824       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4825       MaskedValueIsZero(Op0, C1->getValue())) {
4826     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4827     InsertNewInstBefore(NOr, I);
4828     NOr->takeName(Op0);
4829     return BinaryOperator::CreateXor(NOr, C1);
4830   }
4831
4832   // (A & C)|(B & D)
4833   Value *C = 0, *D = 0;
4834   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4835       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4836     Value *V1 = 0, *V2 = 0, *V3 = 0;
4837     C1 = dyn_cast<ConstantInt>(C);
4838     C2 = dyn_cast<ConstantInt>(D);
4839     if (C1 && C2) {  // (A & C1)|(B & C2)
4840       // If we have: ((V + N) & C1) | (V & C2)
4841       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4842       // replace with V+N.
4843       if (C1->getValue() == ~C2->getValue()) {
4844         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4845             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4846           // Add commutes, try both ways.
4847           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4848             return ReplaceInstUsesWith(I, A);
4849           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4850             return ReplaceInstUsesWith(I, A);
4851         }
4852         // Or commutes, try both ways.
4853         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4854             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4855           // Add commutes, try both ways.
4856           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4857             return ReplaceInstUsesWith(I, B);
4858           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4859             return ReplaceInstUsesWith(I, B);
4860         }
4861       }
4862       V1 = 0; V2 = 0; V3 = 0;
4863     }
4864     
4865     // Check to see if we have any common things being and'ed.  If so, find the
4866     // terms for V1 & (V2|V3).
4867     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4868       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4869         V1 = A, V2 = C, V3 = D;
4870       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4871         V1 = A, V2 = B, V3 = C;
4872       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4873         V1 = C, V2 = A, V3 = D;
4874       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4875         V1 = C, V2 = A, V3 = B;
4876       
4877       if (V1) {
4878         Value *Or =
4879           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4880         return BinaryOperator::CreateAnd(V1, Or);
4881       }
4882     }
4883
4884     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4885     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4886       return Match;
4887     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4888       return Match;
4889     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4890       return Match;
4891     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4892       return Match;
4893
4894     // ((A&~B)|(~A&B)) -> A^B
4895     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4896          match(B, m_Not(m_Specific(A)), *Context)))
4897       return BinaryOperator::CreateXor(A, D);
4898     // ((~B&A)|(~A&B)) -> A^B
4899     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4900          match(B, m_Not(m_Specific(C)), *Context)))
4901       return BinaryOperator::CreateXor(C, D);
4902     // ((A&~B)|(B&~A)) -> A^B
4903     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4904          match(D, m_Not(m_Specific(A)), *Context)))
4905       return BinaryOperator::CreateXor(A, B);
4906     // ((~B&A)|(B&~A)) -> A^B
4907     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4908          match(D, m_Not(m_Specific(C)), *Context)))
4909       return BinaryOperator::CreateXor(C, B);
4910   }
4911   
4912   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4913   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4914     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4915       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4916           SI0->getOperand(1) == SI1->getOperand(1) &&
4917           (SI0->hasOneUse() || SI1->hasOneUse())) {
4918         Instruction *NewOp =
4919         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4920                                                      SI1->getOperand(0),
4921                                                      SI0->getName()), I);
4922         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4923                                       SI1->getOperand(1));
4924       }
4925   }
4926
4927   // ((A|B)&1)|(B&-2) -> (A&1) | B
4928   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4929       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4930     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4931     if (Ret) return Ret;
4932   }
4933   // (B&-2)|((A|B)&1) -> (A&1) | B
4934   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4935       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4936     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4937     if (Ret) return Ret;
4938   }
4939
4940   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4941     if (A == Op1)   // ~A | A == -1
4942       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4943   } else {
4944     A = 0;
4945   }
4946   // Note, A is still live here!
4947   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4948     if (Op0 == B)
4949       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4950
4951     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4952     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4953       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4954                                               I.getName()+".demorgan"), I);
4955       return BinaryOperator::CreateNot(*Context, And);
4956     }
4957   }
4958
4959   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4960   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4961     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4962       return R;
4963
4964     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4965       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4966         return Res;
4967   }
4968     
4969   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4970   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4971     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4972       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4973         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4974             !isa<ICmpInst>(Op1C->getOperand(0))) {
4975           const Type *SrcTy = Op0C->getOperand(0)->getType();
4976           if (SrcTy == Op1C->getOperand(0)->getType() &&
4977               SrcTy->isIntOrIntVector() &&
4978               // Only do this if the casts both really cause code to be
4979               // generated.
4980               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4981                                 I.getType(), TD) &&
4982               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4983                                 I.getType(), TD)) {
4984             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4985                                                           Op1C->getOperand(0),
4986                                                           I.getName());
4987             InsertNewInstBefore(NewOp, I);
4988             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4989           }
4990         }
4991       }
4992   }
4993   
4994     
4995   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4996   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4997     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4998       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4999         return Res;
5000   }
5001
5002   return Changed ? &I : 0;
5003 }
5004
5005 namespace {
5006
5007 // XorSelf - Implements: X ^ X --> 0
5008 struct XorSelf {
5009   Value *RHS;
5010   XorSelf(Value *rhs) : RHS(rhs) {}
5011   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5012   Instruction *apply(BinaryOperator &Xor) const {
5013     return &Xor;
5014   }
5015 };
5016
5017 }
5018
5019 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5020   bool Changed = SimplifyCommutative(I);
5021   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5022
5023   if (isa<UndefValue>(Op1)) {
5024     if (isa<UndefValue>(Op0))
5025       // Handle undef ^ undef -> 0 special case. This is a common
5026       // idiom (misuse).
5027       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5028     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5029   }
5030
5031   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5032   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5033     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5034     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5035   }
5036   
5037   // See if we can simplify any instructions used by the instruction whose sole 
5038   // purpose is to compute bits we don't care about.
5039   if (SimplifyDemandedInstructionBits(I))
5040     return &I;
5041   if (isa<VectorType>(I.getType()))
5042     if (isa<ConstantAggregateZero>(Op1))
5043       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5044
5045   // Is this a ~ operation?
5046   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5047     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5048     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5049     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5050       if (Op0I->getOpcode() == Instruction::And || 
5051           Op0I->getOpcode() == Instruction::Or) {
5052         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5053         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5054           Instruction *NotY =
5055             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5056                                       Op0I->getOperand(1)->getName()+".not");
5057           InsertNewInstBefore(NotY, I);
5058           if (Op0I->getOpcode() == Instruction::And)
5059             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5060           else
5061             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5062         }
5063       }
5064     }
5065   }
5066   
5067   
5068   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5069     if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5070       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5071       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5072         return new ICmpInst(*Context, ICI->getInversePredicate(),
5073                             ICI->getOperand(0), ICI->getOperand(1));
5074
5075       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5076         return new FCmpInst(*Context, FCI->getInversePredicate(),
5077                             FCI->getOperand(0), FCI->getOperand(1));
5078     }
5079
5080     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5081     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5082       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5083         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5084           Instruction::CastOps Opcode = Op0C->getOpcode();
5085           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5086             if (RHS == ConstantExpr::getCast(Opcode, 
5087                                              ConstantInt::getTrue(*Context),
5088                                              Op0C->getDestTy())) {
5089               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5090                                      *Context,
5091                                      CI->getOpcode(), CI->getInversePredicate(),
5092                                      CI->getOperand(0), CI->getOperand(1)), I);
5093               NewCI->takeName(CI);
5094               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5095             }
5096           }
5097         }
5098       }
5099     }
5100
5101     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5102       // ~(c-X) == X-c-1 == X+(-c-1)
5103       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5104         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5105           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5106           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5107                                       ConstantInt::get(I.getType(), 1));
5108           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5109         }
5110           
5111       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5112         if (Op0I->getOpcode() == Instruction::Add) {
5113           // ~(X-c) --> (-c-1)-X
5114           if (RHS->isAllOnesValue()) {
5115             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5116             return BinaryOperator::CreateSub(
5117                            ConstantExpr::getSub(NegOp0CI,
5118                                       ConstantInt::get(I.getType(), 1)),
5119                                       Op0I->getOperand(0));
5120           } else if (RHS->getValue().isSignBit()) {
5121             // (X + C) ^ signbit -> (X + C + signbit)
5122             Constant *C = ConstantInt::get(*Context,
5123                                            RHS->getValue() + Op0CI->getValue());
5124             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5125
5126           }
5127         } else if (Op0I->getOpcode() == Instruction::Or) {
5128           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5129           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5130             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5131             // Anything in both C1 and C2 is known to be zero, remove it from
5132             // NewRHS.
5133             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5134             NewRHS = ConstantExpr::getAnd(NewRHS, 
5135                                        ConstantExpr::getNot(CommonBits));
5136             AddToWorkList(Op0I);
5137             I.setOperand(0, Op0I->getOperand(0));
5138             I.setOperand(1, NewRHS);
5139             return &I;
5140           }
5141         }
5142       }
5143     }
5144
5145     // Try to fold constant and into select arguments.
5146     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5147       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5148         return R;
5149     if (isa<PHINode>(Op0))
5150       if (Instruction *NV = FoldOpIntoPhi(I))
5151         return NV;
5152   }
5153
5154   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5155     if (X == Op1)
5156       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5157
5158   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5159     if (X == Op0)
5160       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5161
5162   
5163   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5164   if (Op1I) {
5165     Value *A, *B;
5166     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5167       if (A == Op0) {              // B^(B|A) == (A|B)^B
5168         Op1I->swapOperands();
5169         I.swapOperands();
5170         std::swap(Op0, Op1);
5171       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5172         I.swapOperands();     // Simplified below.
5173         std::swap(Op0, Op1);
5174       }
5175     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5176       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5177     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5178       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5179     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5180                Op1I->hasOneUse()){
5181       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5182         Op1I->swapOperands();
5183         std::swap(A, B);
5184       }
5185       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5186         I.swapOperands();     // Simplified below.
5187         std::swap(Op0, Op1);
5188       }
5189     }
5190   }
5191   
5192   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5193   if (Op0I) {
5194     Value *A, *B;
5195     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5196         Op0I->hasOneUse()) {
5197       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5198         std::swap(A, B);
5199       if (B == Op1) {                                // (A|B)^B == A & ~B
5200         Instruction *NotB =
5201           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5202                                                         Op1, "tmp"), I);
5203         return BinaryOperator::CreateAnd(A, NotB);
5204       }
5205     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5206       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5207     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5208       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5209     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5210                Op0I->hasOneUse()){
5211       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5212         std::swap(A, B);
5213       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5214           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5215         Instruction *N =
5216           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5217         return BinaryOperator::CreateAnd(N, Op1);
5218       }
5219     }
5220   }
5221   
5222   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5223   if (Op0I && Op1I && Op0I->isShift() && 
5224       Op0I->getOpcode() == Op1I->getOpcode() && 
5225       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5226       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5227     Instruction *NewOp =
5228       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5229                                                     Op1I->getOperand(0),
5230                                                     Op0I->getName()), I);
5231     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5232                                   Op1I->getOperand(1));
5233   }
5234     
5235   if (Op0I && Op1I) {
5236     Value *A, *B, *C, *D;
5237     // (A & B)^(A | B) -> A ^ B
5238     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5239         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5240       if ((A == C && B == D) || (A == D && B == C)) 
5241         return BinaryOperator::CreateXor(A, B);
5242     }
5243     // (A | B)^(A & B) -> A ^ B
5244     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5245         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5246       if ((A == C && B == D) || (A == D && B == C)) 
5247         return BinaryOperator::CreateXor(A, B);
5248     }
5249     
5250     // (A & B)^(C & D)
5251     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5252         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5253         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5254       // (X & Y)^(X & Y) -> (Y^Z) & X
5255       Value *X = 0, *Y = 0, *Z = 0;
5256       if (A == C)
5257         X = A, Y = B, Z = D;
5258       else if (A == D)
5259         X = A, Y = B, Z = C;
5260       else if (B == C)
5261         X = B, Y = A, Z = D;
5262       else if (B == D)
5263         X = B, Y = A, Z = C;
5264       
5265       if (X) {
5266         Instruction *NewOp =
5267         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5268         return BinaryOperator::CreateAnd(NewOp, X);
5269       }
5270     }
5271   }
5272     
5273   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5274   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5275     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5276       return R;
5277
5278   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5279   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5280     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5281       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5282         const Type *SrcTy = Op0C->getOperand(0)->getType();
5283         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5284             // Only do this if the casts both really cause code to be generated.
5285             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5286                               I.getType(), TD) &&
5287             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5288                               I.getType(), TD)) {
5289           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5290                                                          Op1C->getOperand(0),
5291                                                          I.getName());
5292           InsertNewInstBefore(NewOp, I);
5293           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5294         }
5295       }
5296   }
5297
5298   return Changed ? &I : 0;
5299 }
5300
5301 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5302                                    LLVMContext *Context) {
5303   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5304 }
5305
5306 static bool HasAddOverflow(ConstantInt *Result,
5307                            ConstantInt *In1, ConstantInt *In2,
5308                            bool IsSigned) {
5309   if (IsSigned)
5310     if (In2->getValue().isNegative())
5311       return Result->getValue().sgt(In1->getValue());
5312     else
5313       return Result->getValue().slt(In1->getValue());
5314   else
5315     return Result->getValue().ult(In1->getValue());
5316 }
5317
5318 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5319 /// overflowed for this type.
5320 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5321                             Constant *In2, LLVMContext *Context,
5322                             bool IsSigned = false) {
5323   Result = ConstantExpr::getAdd(In1, In2);
5324
5325   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5326     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5327       Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5328       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5329                          ExtractElement(In1, Idx, Context),
5330                          ExtractElement(In2, Idx, Context),
5331                          IsSigned))
5332         return true;
5333     }
5334     return false;
5335   }
5336
5337   return HasAddOverflow(cast<ConstantInt>(Result),
5338                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5339                         IsSigned);
5340 }
5341
5342 static bool HasSubOverflow(ConstantInt *Result,
5343                            ConstantInt *In1, ConstantInt *In2,
5344                            bool IsSigned) {
5345   if (IsSigned)
5346     if (In2->getValue().isNegative())
5347       return Result->getValue().slt(In1->getValue());
5348     else
5349       return Result->getValue().sgt(In1->getValue());
5350   else
5351     return Result->getValue().ugt(In1->getValue());
5352 }
5353
5354 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5355 /// overflowed for this type.
5356 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5357                             Constant *In2, LLVMContext *Context,
5358                             bool IsSigned = false) {
5359   Result = ConstantExpr::getSub(In1, In2);
5360
5361   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5362     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5363       Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5364       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5365                          ExtractElement(In1, Idx, Context),
5366                          ExtractElement(In2, Idx, Context),
5367                          IsSigned))
5368         return true;
5369     }
5370     return false;
5371   }
5372
5373   return HasSubOverflow(cast<ConstantInt>(Result),
5374                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5375                         IsSigned);
5376 }
5377
5378 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5379 /// code necessary to compute the offset from the base pointer (without adding
5380 /// in the base pointer).  Return the result as a signed integer of intptr size.
5381 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5382   TargetData &TD = *IC.getTargetData();
5383   gep_type_iterator GTI = gep_type_begin(GEP);
5384   const Type *IntPtrTy = TD.getIntPtrType();
5385   LLVMContext *Context = IC.getContext();
5386   Value *Result = Constant::getNullValue(IntPtrTy);
5387
5388   // Build a mask for high order bits.
5389   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5390   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5391
5392   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5393        ++i, ++GTI) {
5394     Value *Op = *i;
5395     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5396     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5397       if (OpC->isZero()) continue;
5398       
5399       // Handle a struct index, which adds its field offset to the pointer.
5400       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5401         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5402         
5403         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5404           Result = 
5405              ConstantInt::get(*Context, 
5406                               RC->getValue() + APInt(IntPtrWidth, Size));
5407         else
5408           Result = IC.InsertNewInstBefore(
5409                    BinaryOperator::CreateAdd(Result,
5410                                         ConstantInt::get(IntPtrTy, Size),
5411                                              GEP->getName()+".offs"), I);
5412         continue;
5413       }
5414       
5415       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5416       Constant *OC =
5417               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5418       Scale = ConstantExpr::getMul(OC, Scale);
5419       if (Constant *RC = dyn_cast<Constant>(Result))
5420         Result = ConstantExpr::getAdd(RC, Scale);
5421       else {
5422         // Emit an add instruction.
5423         Result = IC.InsertNewInstBefore(
5424            BinaryOperator::CreateAdd(Result, Scale,
5425                                      GEP->getName()+".offs"), I);
5426       }
5427       continue;
5428     }
5429     // Convert to correct type.
5430     if (Op->getType() != IntPtrTy) {
5431       if (Constant *OpC = dyn_cast<Constant>(Op))
5432         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5433       else
5434         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5435                                                                 true,
5436                                                       Op->getName()+".c"), I);
5437     }
5438     if (Size != 1) {
5439       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5440       if (Constant *OpC = dyn_cast<Constant>(Op))
5441         Op = ConstantExpr::getMul(OpC, Scale);
5442       else    // We'll let instcombine(mul) convert this to a shl if possible.
5443         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5444                                                   GEP->getName()+".idx"), I);
5445     }
5446
5447     // Emit an add instruction.
5448     if (isa<Constant>(Op) && isa<Constant>(Result))
5449       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5450                                     cast<Constant>(Result));
5451     else
5452       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5453                                                   GEP->getName()+".offs"), I);
5454   }
5455   return Result;
5456 }
5457
5458
5459 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5460 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5461 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5462 /// be complex, and scales are involved.  The above expression would also be
5463 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5464 /// This later form is less amenable to optimization though, and we are allowed
5465 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5466 ///
5467 /// If we can't emit an optimized form for this expression, this returns null.
5468 /// 
5469 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5470                                           InstCombiner &IC) {
5471   TargetData &TD = *IC.getTargetData();
5472   gep_type_iterator GTI = gep_type_begin(GEP);
5473
5474   // Check to see if this gep only has a single variable index.  If so, and if
5475   // any constant indices are a multiple of its scale, then we can compute this
5476   // in terms of the scale of the variable index.  For example, if the GEP
5477   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5478   // because the expression will cross zero at the same point.
5479   unsigned i, e = GEP->getNumOperands();
5480   int64_t Offset = 0;
5481   for (i = 1; i != e; ++i, ++GTI) {
5482     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5483       // Compute the aggregate offset of constant indices.
5484       if (CI->isZero()) continue;
5485
5486       // Handle a struct index, which adds its field offset to the pointer.
5487       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5488         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5489       } else {
5490         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5491         Offset += Size*CI->getSExtValue();
5492       }
5493     } else {
5494       // Found our variable index.
5495       break;
5496     }
5497   }
5498   
5499   // If there are no variable indices, we must have a constant offset, just
5500   // evaluate it the general way.
5501   if (i == e) return 0;
5502   
5503   Value *VariableIdx = GEP->getOperand(i);
5504   // Determine the scale factor of the variable element.  For example, this is
5505   // 4 if the variable index is into an array of i32.
5506   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5507   
5508   // Verify that there are no other variable indices.  If so, emit the hard way.
5509   for (++i, ++GTI; i != e; ++i, ++GTI) {
5510     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5511     if (!CI) return 0;
5512    
5513     // Compute the aggregate offset of constant indices.
5514     if (CI->isZero()) continue;
5515     
5516     // Handle a struct index, which adds its field offset to the pointer.
5517     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5518       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5519     } else {
5520       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5521       Offset += Size*CI->getSExtValue();
5522     }
5523   }
5524   
5525   // Okay, we know we have a single variable index, which must be a
5526   // pointer/array/vector index.  If there is no offset, life is simple, return
5527   // the index.
5528   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5529   if (Offset == 0) {
5530     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5531     // we don't need to bother extending: the extension won't affect where the
5532     // computation crosses zero.
5533     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5534       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5535                                   VariableIdx->getName(), &I);
5536     return VariableIdx;
5537   }
5538   
5539   // Otherwise, there is an index.  The computation we will do will be modulo
5540   // the pointer size, so get it.
5541   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5542   
5543   Offset &= PtrSizeMask;
5544   VariableScale &= PtrSizeMask;
5545
5546   // To do this transformation, any constant index must be a multiple of the
5547   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5548   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5549   // multiple of the variable scale.
5550   int64_t NewOffs = Offset / (int64_t)VariableScale;
5551   if (Offset != NewOffs*(int64_t)VariableScale)
5552     return 0;
5553
5554   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5555   const Type *IntPtrTy = TD.getIntPtrType();
5556   if (VariableIdx->getType() != IntPtrTy)
5557     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5558                                               true /*SExt*/, 
5559                                               VariableIdx->getName(), &I);
5560   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5561   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5562 }
5563
5564
5565 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5566 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5567 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5568                                        ICmpInst::Predicate Cond,
5569                                        Instruction &I) {
5570   // Look through bitcasts.
5571   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5572     RHS = BCI->getOperand(0);
5573
5574   Value *PtrBase = GEPLHS->getOperand(0);
5575   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5576     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5577     // This transformation (ignoring the base and scales) is valid because we
5578     // know pointers can't overflow since the gep is inbounds.  See if we can
5579     // output an optimized form.
5580     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5581     
5582     // If not, synthesize the offset the hard way.
5583     if (Offset == 0)
5584       Offset = EmitGEPOffset(GEPLHS, I, *this);
5585     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5586                         Constant::getNullValue(Offset->getType()));
5587   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5588     // If the base pointers are different, but the indices are the same, just
5589     // compare the base pointer.
5590     if (PtrBase != GEPRHS->getOperand(0)) {
5591       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5592       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5593                         GEPRHS->getOperand(0)->getType();
5594       if (IndicesTheSame)
5595         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5596           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5597             IndicesTheSame = false;
5598             break;
5599           }
5600
5601       // If all indices are the same, just compare the base pointers.
5602       if (IndicesTheSame)
5603         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5604                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5605
5606       // Otherwise, the base pointers are different and the indices are
5607       // different, bail out.
5608       return 0;
5609     }
5610
5611     // If one of the GEPs has all zero indices, recurse.
5612     bool AllZeros = true;
5613     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5614       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5615           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5616         AllZeros = false;
5617         break;
5618       }
5619     if (AllZeros)
5620       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5621                           ICmpInst::getSwappedPredicate(Cond), I);
5622
5623     // If the other GEP has all zero indices, recurse.
5624     AllZeros = true;
5625     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5626       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5627           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5628         AllZeros = false;
5629         break;
5630       }
5631     if (AllZeros)
5632       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5633
5634     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5635       // If the GEPs only differ by one index, compare it.
5636       unsigned NumDifferences = 0;  // Keep track of # differences.
5637       unsigned DiffOperand = 0;     // The operand that differs.
5638       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5639         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5640           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5641                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5642             // Irreconcilable differences.
5643             NumDifferences = 2;
5644             break;
5645           } else {
5646             if (NumDifferences++) break;
5647             DiffOperand = i;
5648           }
5649         }
5650
5651       if (NumDifferences == 0)   // SAME GEP?
5652         return ReplaceInstUsesWith(I, // No comparison is needed here.
5653                                    ConstantInt::get(Type::Int1Ty,
5654                                              ICmpInst::isTrueWhenEqual(Cond)));
5655
5656       else if (NumDifferences == 1) {
5657         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5658         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5659         // Make sure we do a signed comparison here.
5660         return new ICmpInst(*Context,
5661                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5662       }
5663     }
5664
5665     // Only lower this if the icmp is the only user of the GEP or if we expect
5666     // the result to fold to a constant!
5667     if (TD &&
5668         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5669         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5670       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5671       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5672       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5673       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5674     }
5675   }
5676   return 0;
5677 }
5678
5679 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5680 ///
5681 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5682                                                 Instruction *LHSI,
5683                                                 Constant *RHSC) {
5684   if (!isa<ConstantFP>(RHSC)) return 0;
5685   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5686   
5687   // Get the width of the mantissa.  We don't want to hack on conversions that
5688   // might lose information from the integer, e.g. "i64 -> float"
5689   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5690   if (MantissaWidth == -1) return 0;  // Unknown.
5691   
5692   // Check to see that the input is converted from an integer type that is small
5693   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5694   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5695   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5696   
5697   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5698   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5699   if (LHSUnsigned)
5700     ++InputSize;
5701   
5702   // If the conversion would lose info, don't hack on this.
5703   if ((int)InputSize > MantissaWidth)
5704     return 0;
5705   
5706   // Otherwise, we can potentially simplify the comparison.  We know that it
5707   // will always come through as an integer value and we know the constant is
5708   // not a NAN (it would have been previously simplified).
5709   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5710   
5711   ICmpInst::Predicate Pred;
5712   switch (I.getPredicate()) {
5713   default: llvm_unreachable("Unexpected predicate!");
5714   case FCmpInst::FCMP_UEQ:
5715   case FCmpInst::FCMP_OEQ:
5716     Pred = ICmpInst::ICMP_EQ;
5717     break;
5718   case FCmpInst::FCMP_UGT:
5719   case FCmpInst::FCMP_OGT:
5720     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5721     break;
5722   case FCmpInst::FCMP_UGE:
5723   case FCmpInst::FCMP_OGE:
5724     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5725     break;
5726   case FCmpInst::FCMP_ULT:
5727   case FCmpInst::FCMP_OLT:
5728     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5729     break;
5730   case FCmpInst::FCMP_ULE:
5731   case FCmpInst::FCMP_OLE:
5732     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5733     break;
5734   case FCmpInst::FCMP_UNE:
5735   case FCmpInst::FCMP_ONE:
5736     Pred = ICmpInst::ICMP_NE;
5737     break;
5738   case FCmpInst::FCMP_ORD:
5739     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5740   case FCmpInst::FCMP_UNO:
5741     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5742   }
5743   
5744   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5745   
5746   // Now we know that the APFloat is a normal number, zero or inf.
5747   
5748   // See if the FP constant is too large for the integer.  For example,
5749   // comparing an i8 to 300.0.
5750   unsigned IntWidth = IntTy->getScalarSizeInBits();
5751   
5752   if (!LHSUnsigned) {
5753     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5754     // and large values.
5755     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5756     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5757                           APFloat::rmNearestTiesToEven);
5758     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5759       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5760           Pred == ICmpInst::ICMP_SLE)
5761         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5762       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5763     }
5764   } else {
5765     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5766     // +INF and large values.
5767     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5768     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5769                           APFloat::rmNearestTiesToEven);
5770     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5771       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5772           Pred == ICmpInst::ICMP_ULE)
5773         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5774       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5775     }
5776   }
5777   
5778   if (!LHSUnsigned) {
5779     // See if the RHS value is < SignedMin.
5780     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5781     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5782                           APFloat::rmNearestTiesToEven);
5783     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5784       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5785           Pred == ICmpInst::ICMP_SGE)
5786         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5787       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5788     }
5789   }
5790
5791   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5792   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5793   // casting the FP value to the integer value and back, checking for equality.
5794   // Don't do this for zero, because -0.0 is not fractional.
5795   Constant *RHSInt = LHSUnsigned
5796     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5797     : ConstantExpr::getFPToSI(RHSC, IntTy);
5798   if (!RHS.isZero()) {
5799     bool Equal = LHSUnsigned
5800       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5801       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5802     if (!Equal) {
5803       // If we had a comparison against a fractional value, we have to adjust
5804       // the compare predicate and sometimes the value.  RHSC is rounded towards
5805       // zero at this point.
5806       switch (Pred) {
5807       default: llvm_unreachable("Unexpected integer comparison!");
5808       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5809         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5810       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5811         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5812       case ICmpInst::ICMP_ULE:
5813         // (float)int <= 4.4   --> int <= 4
5814         // (float)int <= -4.4  --> false
5815         if (RHS.isNegative())
5816           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5817         break;
5818       case ICmpInst::ICMP_SLE:
5819         // (float)int <= 4.4   --> int <= 4
5820         // (float)int <= -4.4  --> int < -4
5821         if (RHS.isNegative())
5822           Pred = ICmpInst::ICMP_SLT;
5823         break;
5824       case ICmpInst::ICMP_ULT:
5825         // (float)int < -4.4   --> false
5826         // (float)int < 4.4    --> int <= 4
5827         if (RHS.isNegative())
5828           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5829         Pred = ICmpInst::ICMP_ULE;
5830         break;
5831       case ICmpInst::ICMP_SLT:
5832         // (float)int < -4.4   --> int < -4
5833         // (float)int < 4.4    --> int <= 4
5834         if (!RHS.isNegative())
5835           Pred = ICmpInst::ICMP_SLE;
5836         break;
5837       case ICmpInst::ICMP_UGT:
5838         // (float)int > 4.4    --> int > 4
5839         // (float)int > -4.4   --> true
5840         if (RHS.isNegative())
5841           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5842         break;
5843       case ICmpInst::ICMP_SGT:
5844         // (float)int > 4.4    --> int > 4
5845         // (float)int > -4.4   --> int >= -4
5846         if (RHS.isNegative())
5847           Pred = ICmpInst::ICMP_SGE;
5848         break;
5849       case ICmpInst::ICMP_UGE:
5850         // (float)int >= -4.4   --> true
5851         // (float)int >= 4.4    --> int > 4
5852         if (!RHS.isNegative())
5853           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5854         Pred = ICmpInst::ICMP_UGT;
5855         break;
5856       case ICmpInst::ICMP_SGE:
5857         // (float)int >= -4.4   --> int >= -4
5858         // (float)int >= 4.4    --> int > 4
5859         if (!RHS.isNegative())
5860           Pred = ICmpInst::ICMP_SGT;
5861         break;
5862       }
5863     }
5864   }
5865
5866   // Lower this FP comparison into an appropriate integer version of the
5867   // comparison.
5868   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5869 }
5870
5871 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5872   bool Changed = SimplifyCompare(I);
5873   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5874
5875   // Fold trivial predicates.
5876   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5877     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5878   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5879     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5880   
5881   // Simplify 'fcmp pred X, X'
5882   if (Op0 == Op1) {
5883     switch (I.getPredicate()) {
5884     default: llvm_unreachable("Unknown predicate!");
5885     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5886     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5887     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5888       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5889     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5890     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5891     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5892       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5893       
5894     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5895     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5896     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5897     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5898       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5899       I.setPredicate(FCmpInst::FCMP_UNO);
5900       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5901       return &I;
5902       
5903     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5904     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5905     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5906     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5907       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5908       I.setPredicate(FCmpInst::FCMP_ORD);
5909       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5910       return &I;
5911     }
5912   }
5913     
5914   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5915     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5916
5917   // Handle fcmp with constant RHS
5918   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5919     // If the constant is a nan, see if we can fold the comparison based on it.
5920     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5921       if (CFP->getValueAPF().isNaN()) {
5922         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5923           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5924         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5925                "Comparison must be either ordered or unordered!");
5926         // True if unordered.
5927         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5928       }
5929     }
5930     
5931     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5932       switch (LHSI->getOpcode()) {
5933       case Instruction::PHI:
5934         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5935         // block.  If in the same block, we're encouraging jump threading.  If
5936         // not, we are just pessimizing the code by making an i1 phi.
5937         if (LHSI->getParent() == I.getParent())
5938           if (Instruction *NV = FoldOpIntoPhi(I))
5939             return NV;
5940         break;
5941       case Instruction::SIToFP:
5942       case Instruction::UIToFP:
5943         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5944           return NV;
5945         break;
5946       case Instruction::Select:
5947         // If either operand of the select is a constant, we can fold the
5948         // comparison into the select arms, which will cause one to be
5949         // constant folded and the select turned into a bitwise or.
5950         Value *Op1 = 0, *Op2 = 0;
5951         if (LHSI->hasOneUse()) {
5952           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5953             // Fold the known value into the constant operand.
5954             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5955             // Insert a new FCmp of the other select operand.
5956             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5957                                                       LHSI->getOperand(2), RHSC,
5958                                                       I.getName()), I);
5959           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5960             // Fold the known value into the constant operand.
5961             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5962             // Insert a new FCmp of the other select operand.
5963             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5964                                                       LHSI->getOperand(1), RHSC,
5965                                                       I.getName()), I);
5966           }
5967         }
5968
5969         if (Op1)
5970           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5971         break;
5972       }
5973   }
5974
5975   return Changed ? &I : 0;
5976 }
5977
5978 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5979   bool Changed = SimplifyCompare(I);
5980   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5981   const Type *Ty = Op0->getType();
5982
5983   // icmp X, X
5984   if (Op0 == Op1)
5985     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5986                                                    I.isTrueWhenEqual()));
5987
5988   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5989     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5990   
5991   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5992   // addresses never equal each other!  We already know that Op0 != Op1.
5993   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5994        isa<ConstantPointerNull>(Op0)) &&
5995       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5996        isa<ConstantPointerNull>(Op1)))
5997     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5998                                                    !I.isTrueWhenEqual()));
5999
6000   // icmp's with boolean values can always be turned into bitwise operations
6001   if (Ty == Type::Int1Ty) {
6002     switch (I.getPredicate()) {
6003     default: llvm_unreachable("Invalid icmp instruction!");
6004     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6005       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6006       InsertNewInstBefore(Xor, I);
6007       return BinaryOperator::CreateNot(*Context, Xor);
6008     }
6009     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6010       return BinaryOperator::CreateXor(Op0, Op1);
6011
6012     case ICmpInst::ICMP_UGT:
6013       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6014       // FALL THROUGH
6015     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6016       Instruction *Not = BinaryOperator::CreateNot(*Context,
6017                                                    Op0, I.getName()+"tmp");
6018       InsertNewInstBefore(Not, I);
6019       return BinaryOperator::CreateAnd(Not, Op1);
6020     }
6021     case ICmpInst::ICMP_SGT:
6022       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6023       // FALL THROUGH
6024     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6025       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6026                                                    Op1, I.getName()+"tmp");
6027       InsertNewInstBefore(Not, I);
6028       return BinaryOperator::CreateAnd(Not, Op0);
6029     }
6030     case ICmpInst::ICMP_UGE:
6031       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6032       // FALL THROUGH
6033     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6034       Instruction *Not = BinaryOperator::CreateNot(*Context,
6035                                                    Op0, I.getName()+"tmp");
6036       InsertNewInstBefore(Not, I);
6037       return BinaryOperator::CreateOr(Not, Op1);
6038     }
6039     case ICmpInst::ICMP_SGE:
6040       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6041       // FALL THROUGH
6042     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6043       Instruction *Not = BinaryOperator::CreateNot(*Context,
6044                                                    Op1, I.getName()+"tmp");
6045       InsertNewInstBefore(Not, I);
6046       return BinaryOperator::CreateOr(Not, Op0);
6047     }
6048     }
6049   }
6050
6051   unsigned BitWidth = 0;
6052   if (TD)
6053     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6054   else if (Ty->isIntOrIntVector())
6055     BitWidth = Ty->getScalarSizeInBits();
6056
6057   bool isSignBit = false;
6058
6059   // See if we are doing a comparison with a constant.
6060   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6061     Value *A = 0, *B = 0;
6062     
6063     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6064     if (I.isEquality() && CI->isNullValue() &&
6065         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6066       // (icmp cond A B) if cond is equality
6067       return new ICmpInst(*Context, I.getPredicate(), A, B);
6068     }
6069     
6070     // If we have an icmp le or icmp ge instruction, turn it into the
6071     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6072     // them being folded in the code below.
6073     switch (I.getPredicate()) {
6074     default: break;
6075     case ICmpInst::ICMP_ULE:
6076       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6077         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6078       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6079                           AddOne(CI, Context));
6080     case ICmpInst::ICMP_SLE:
6081       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6082         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6083       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6084                           AddOne(CI, Context));
6085     case ICmpInst::ICMP_UGE:
6086       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6087         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6088       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6089                           SubOne(CI, Context));
6090     case ICmpInst::ICMP_SGE:
6091       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6092         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6093       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6094                           SubOne(CI, Context));
6095     }
6096     
6097     // If this comparison is a normal comparison, it demands all
6098     // bits, if it is a sign bit comparison, it only demands the sign bit.
6099     bool UnusedBit;
6100     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6101   }
6102
6103   // See if we can fold the comparison based on range information we can get
6104   // by checking whether bits are known to be zero or one in the input.
6105   if (BitWidth != 0) {
6106     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6107     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6108
6109     if (SimplifyDemandedBits(I.getOperandUse(0),
6110                              isSignBit ? APInt::getSignBit(BitWidth)
6111                                        : APInt::getAllOnesValue(BitWidth),
6112                              Op0KnownZero, Op0KnownOne, 0))
6113       return &I;
6114     if (SimplifyDemandedBits(I.getOperandUse(1),
6115                              APInt::getAllOnesValue(BitWidth),
6116                              Op1KnownZero, Op1KnownOne, 0))
6117       return &I;
6118
6119     // Given the known and unknown bits, compute a range that the LHS could be
6120     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6121     // EQ and NE we use unsigned values.
6122     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6123     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6124     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6125       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6126                                              Op0Min, Op0Max);
6127       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6128                                              Op1Min, Op1Max);
6129     } else {
6130       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6131                                                Op0Min, Op0Max);
6132       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6133                                                Op1Min, Op1Max);
6134     }
6135
6136     // If Min and Max are known to be the same, then SimplifyDemandedBits
6137     // figured out that the LHS is a constant.  Just constant fold this now so
6138     // that code below can assume that Min != Max.
6139     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6140       return new ICmpInst(*Context, I.getPredicate(),
6141                           ConstantInt::get(*Context, Op0Min), Op1);
6142     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6143       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6144                           ConstantInt::get(*Context, Op1Min));
6145
6146     // Based on the range information we know about the LHS, see if we can
6147     // simplify this comparison.  For example, (x&4) < 8  is always true.
6148     switch (I.getPredicate()) {
6149     default: llvm_unreachable("Unknown icmp opcode!");
6150     case ICmpInst::ICMP_EQ:
6151       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6152         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6153       break;
6154     case ICmpInst::ICMP_NE:
6155       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6156         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6157       break;
6158     case ICmpInst::ICMP_ULT:
6159       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6160         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6161       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6162         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6163       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6164         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6165       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6166         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6167           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6168                               SubOne(CI, Context));
6169
6170         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6171         if (CI->isMinValue(true))
6172           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6173                            Constant::getAllOnesValue(Op0->getType()));
6174       }
6175       break;
6176     case ICmpInst::ICMP_UGT:
6177       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6178         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6179       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6180         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6181
6182       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6183         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6184       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6185         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6186           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6187                               AddOne(CI, Context));
6188
6189         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6190         if (CI->isMaxValue(true))
6191           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6192                               Constant::getNullValue(Op0->getType()));
6193       }
6194       break;
6195     case ICmpInst::ICMP_SLT:
6196       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6197         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6198       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6199         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6200       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6201         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6202       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6203         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6204           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6205                               SubOne(CI, Context));
6206       }
6207       break;
6208     case ICmpInst::ICMP_SGT:
6209       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6210         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6211       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6212         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6213
6214       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6215         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6216       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6217         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6218           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6219                               AddOne(CI, Context));
6220       }
6221       break;
6222     case ICmpInst::ICMP_SGE:
6223       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6224       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6225         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6226       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6227         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6228       break;
6229     case ICmpInst::ICMP_SLE:
6230       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6231       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6232         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6233       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6234         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6235       break;
6236     case ICmpInst::ICMP_UGE:
6237       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6238       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6239         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6240       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6241         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6242       break;
6243     case ICmpInst::ICMP_ULE:
6244       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6245       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6246         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6247       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6248         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6249       break;
6250     }
6251
6252     // Turn a signed comparison into an unsigned one if both operands
6253     // are known to have the same sign.
6254     if (I.isSignedPredicate() &&
6255         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6256          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6257       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6258   }
6259
6260   // Test if the ICmpInst instruction is used exclusively by a select as
6261   // part of a minimum or maximum operation. If so, refrain from doing
6262   // any other folding. This helps out other analyses which understand
6263   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6264   // and CodeGen. And in this case, at least one of the comparison
6265   // operands has at least one user besides the compare (the select),
6266   // which would often largely negate the benefit of folding anyway.
6267   if (I.hasOneUse())
6268     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6269       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6270           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6271         return 0;
6272
6273   // See if we are doing a comparison between a constant and an instruction that
6274   // can be folded into the comparison.
6275   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6276     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6277     // instruction, see if that instruction also has constants so that the 
6278     // instruction can be folded into the icmp 
6279     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6280       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6281         return Res;
6282   }
6283
6284   // Handle icmp with constant (but not simple integer constant) RHS
6285   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6286     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6287       switch (LHSI->getOpcode()) {
6288       case Instruction::GetElementPtr:
6289         if (RHSC->isNullValue()) {
6290           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6291           bool isAllZeros = true;
6292           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6293             if (!isa<Constant>(LHSI->getOperand(i)) ||
6294                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6295               isAllZeros = false;
6296               break;
6297             }
6298           if (isAllZeros)
6299             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6300                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6301         }
6302         break;
6303
6304       case Instruction::PHI:
6305         // Only fold icmp into the PHI if the phi and fcmp are in the same
6306         // block.  If in the same block, we're encouraging jump threading.  If
6307         // not, we are just pessimizing the code by making an i1 phi.
6308         if (LHSI->getParent() == I.getParent())
6309           if (Instruction *NV = FoldOpIntoPhi(I))
6310             return NV;
6311         break;
6312       case Instruction::Select: {
6313         // If either operand of the select is a constant, we can fold the
6314         // comparison into the select arms, which will cause one to be
6315         // constant folded and the select turned into a bitwise or.
6316         Value *Op1 = 0, *Op2 = 0;
6317         if (LHSI->hasOneUse()) {
6318           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6319             // Fold the known value into the constant operand.
6320             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6321             // Insert a new ICmp of the other select operand.
6322             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6323                                                    LHSI->getOperand(2), RHSC,
6324                                                    I.getName()), I);
6325           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6326             // Fold the known value into the constant operand.
6327             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6328             // Insert a new ICmp of the other select operand.
6329             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6330                                                    LHSI->getOperand(1), RHSC,
6331                                                    I.getName()), I);
6332           }
6333         }
6334
6335         if (Op1)
6336           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6337         break;
6338       }
6339       case Instruction::Malloc:
6340         // If we have (malloc != null), and if the malloc has a single use, we
6341         // can assume it is successful and remove the malloc.
6342         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6343           AddToWorkList(LHSI);
6344           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6345                                                          !I.isTrueWhenEqual()));
6346         }
6347         break;
6348       }
6349   }
6350
6351   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6352   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6353     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6354       return NI;
6355   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6356     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6357                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6358       return NI;
6359
6360   // Test to see if the operands of the icmp are casted versions of other
6361   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6362   // now.
6363   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6364     if (isa<PointerType>(Op0->getType()) && 
6365         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6366       // We keep moving the cast from the left operand over to the right
6367       // operand, where it can often be eliminated completely.
6368       Op0 = CI->getOperand(0);
6369
6370       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6371       // so eliminate it as well.
6372       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6373         Op1 = CI2->getOperand(0);
6374
6375       // If Op1 is a constant, we can fold the cast into the constant.
6376       if (Op0->getType() != Op1->getType()) {
6377         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6378           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6379         } else {
6380           // Otherwise, cast the RHS right before the icmp
6381           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6382         }
6383       }
6384       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6385     }
6386   }
6387   
6388   if (isa<CastInst>(Op0)) {
6389     // Handle the special case of: icmp (cast bool to X), <cst>
6390     // This comes up when you have code like
6391     //   int X = A < B;
6392     //   if (X) ...
6393     // For generality, we handle any zero-extension of any operand comparison
6394     // with a constant or another cast from the same type.
6395     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6396       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6397         return R;
6398   }
6399   
6400   // See if it's the same type of instruction on the left and right.
6401   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6402     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6403       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6404           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6405         switch (Op0I->getOpcode()) {
6406         default: break;
6407         case Instruction::Add:
6408         case Instruction::Sub:
6409         case Instruction::Xor:
6410           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6411             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6412                                 Op1I->getOperand(0));
6413           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6414           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6415             if (CI->getValue().isSignBit()) {
6416               ICmpInst::Predicate Pred = I.isSignedPredicate()
6417                                              ? I.getUnsignedPredicate()
6418                                              : I.getSignedPredicate();
6419               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6420                                   Op1I->getOperand(0));
6421             }
6422             
6423             if (CI->getValue().isMaxSignedValue()) {
6424               ICmpInst::Predicate Pred = I.isSignedPredicate()
6425                                              ? I.getUnsignedPredicate()
6426                                              : I.getSignedPredicate();
6427               Pred = I.getSwappedPredicate(Pred);
6428               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6429                                   Op1I->getOperand(0));
6430             }
6431           }
6432           break;
6433         case Instruction::Mul:
6434           if (!I.isEquality())
6435             break;
6436
6437           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6438             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6439             // Mask = -1 >> count-trailing-zeros(Cst).
6440             if (!CI->isZero() && !CI->isOne()) {
6441               const APInt &AP = CI->getValue();
6442               ConstantInt *Mask = ConstantInt::get(*Context, 
6443                                       APInt::getLowBitsSet(AP.getBitWidth(),
6444                                                            AP.getBitWidth() -
6445                                                       AP.countTrailingZeros()));
6446               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6447                                                             Mask);
6448               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6449                                                             Mask);
6450               InsertNewInstBefore(And1, I);
6451               InsertNewInstBefore(And2, I);
6452               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6453             }
6454           }
6455           break;
6456         }
6457       }
6458     }
6459   }
6460   
6461   // ~x < ~y --> y < x
6462   { Value *A, *B;
6463     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6464         match(Op1, m_Not(m_Value(B)), *Context))
6465       return new ICmpInst(*Context, I.getPredicate(), B, A);
6466   }
6467   
6468   if (I.isEquality()) {
6469     Value *A, *B, *C, *D;
6470     
6471     // -x == -y --> x == y
6472     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6473         match(Op1, m_Neg(m_Value(B)), *Context))
6474       return new ICmpInst(*Context, I.getPredicate(), A, B);
6475     
6476     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6477       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6478         Value *OtherVal = A == Op1 ? B : A;
6479         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6480                             Constant::getNullValue(A->getType()));
6481       }
6482
6483       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6484         // A^c1 == C^c2 --> A == C^(c1^c2)
6485         ConstantInt *C1, *C2;
6486         if (match(B, m_ConstantInt(C1), *Context) &&
6487             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6488           Constant *NC = 
6489                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6490           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6491           return new ICmpInst(*Context, I.getPredicate(), A,
6492                               InsertNewInstBefore(Xor, I));
6493         }
6494         
6495         // A^B == A^D -> B == D
6496         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6497         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6498         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6499         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6500       }
6501     }
6502     
6503     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6504         (A == Op0 || B == Op0)) {
6505       // A == (A^B)  ->  B == 0
6506       Value *OtherVal = A == Op0 ? B : A;
6507       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6508                           Constant::getNullValue(A->getType()));
6509     }
6510
6511     // (A-B) == A  ->  B == 0
6512     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6513       return new ICmpInst(*Context, I.getPredicate(), B, 
6514                           Constant::getNullValue(B->getType()));
6515
6516     // A == (A-B)  ->  B == 0
6517     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6518       return new ICmpInst(*Context, I.getPredicate(), B,
6519                           Constant::getNullValue(B->getType()));
6520     
6521     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6522     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6523         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6524         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6525       Value *X = 0, *Y = 0, *Z = 0;
6526       
6527       if (A == C) {
6528         X = B; Y = D; Z = A;
6529       } else if (A == D) {
6530         X = B; Y = C; Z = A;
6531       } else if (B == C) {
6532         X = A; Y = D; Z = B;
6533       } else if (B == D) {
6534         X = A; Y = C; Z = B;
6535       }
6536       
6537       if (X) {   // Build (X^Y) & Z
6538         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6539         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6540         I.setOperand(0, Op1);
6541         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6542         return &I;
6543       }
6544     }
6545   }
6546   return Changed ? &I : 0;
6547 }
6548
6549
6550 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6551 /// and CmpRHS are both known to be integer constants.
6552 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6553                                           ConstantInt *DivRHS) {
6554   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6555   const APInt &CmpRHSV = CmpRHS->getValue();
6556   
6557   // FIXME: If the operand types don't match the type of the divide 
6558   // then don't attempt this transform. The code below doesn't have the
6559   // logic to deal with a signed divide and an unsigned compare (and
6560   // vice versa). This is because (x /s C1) <s C2  produces different 
6561   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6562   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6563   // work. :(  The if statement below tests that condition and bails 
6564   // if it finds it. 
6565   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6566   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6567     return 0;
6568   if (DivRHS->isZero())
6569     return 0; // The ProdOV computation fails on divide by zero.
6570   if (DivIsSigned && DivRHS->isAllOnesValue())
6571     return 0; // The overflow computation also screws up here
6572   if (DivRHS->isOne())
6573     return 0; // Not worth bothering, and eliminates some funny cases
6574               // with INT_MIN.
6575
6576   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6577   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6578   // C2 (CI). By solving for X we can turn this into a range check 
6579   // instead of computing a divide. 
6580   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6581
6582   // Determine if the product overflows by seeing if the product is
6583   // not equal to the divide. Make sure we do the same kind of divide
6584   // as in the LHS instruction that we're folding. 
6585   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6586                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6587
6588   // Get the ICmp opcode
6589   ICmpInst::Predicate Pred = ICI.getPredicate();
6590
6591   // Figure out the interval that is being checked.  For example, a comparison
6592   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6593   // Compute this interval based on the constants involved and the signedness of
6594   // the compare/divide.  This computes a half-open interval, keeping track of
6595   // whether either value in the interval overflows.  After analysis each
6596   // overflow variable is set to 0 if it's corresponding bound variable is valid
6597   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6598   int LoOverflow = 0, HiOverflow = 0;
6599   Constant *LoBound = 0, *HiBound = 0;
6600   
6601   if (!DivIsSigned) {  // udiv
6602     // e.g. X/5 op 3  --> [15, 20)
6603     LoBound = Prod;
6604     HiOverflow = LoOverflow = ProdOV;
6605     if (!HiOverflow)
6606       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6607   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6608     if (CmpRHSV == 0) {       // (X / pos) op 0
6609       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6610       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS, 
6611                                                                     Context)));
6612       HiBound = DivRHS;
6613     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6614       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6615       HiOverflow = LoOverflow = ProdOV;
6616       if (!HiOverflow)
6617         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6618     } else {                       // (X / pos) op neg
6619       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6620       HiBound = AddOne(Prod, Context);
6621       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6622       if (!LoOverflow) {
6623         ConstantInt* DivNeg =
6624                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6625         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6626                                      true) ? -1 : 0;
6627        }
6628     }
6629   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6630     if (CmpRHSV == 0) {       // (X / neg) op 0
6631       // e.g. X/-5 op 0  --> [-4, 5)
6632       LoBound = AddOne(DivRHS, Context);
6633       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6634       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6635         HiOverflow = 1;            // [INTMIN+1, overflow)
6636         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6637       }
6638     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6639       // e.g. X/-5 op 3  --> [-19, -14)
6640       HiBound = AddOne(Prod, Context);
6641       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6642       if (!LoOverflow)
6643         LoOverflow = AddWithOverflow(LoBound, HiBound,
6644                                      DivRHS, Context, true) ? -1 : 0;
6645     } else {                       // (X / neg) op neg
6646       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6647       LoOverflow = HiOverflow = ProdOV;
6648       if (!HiOverflow)
6649         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6650     }
6651     
6652     // Dividing by a negative swaps the condition.  LT <-> GT
6653     Pred = ICmpInst::getSwappedPredicate(Pred);
6654   }
6655
6656   Value *X = DivI->getOperand(0);
6657   switch (Pred) {
6658   default: llvm_unreachable("Unhandled icmp opcode!");
6659   case ICmpInst::ICMP_EQ:
6660     if (LoOverflow && HiOverflow)
6661       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6662     else if (HiOverflow)
6663       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6664                           ICmpInst::ICMP_UGE, X, LoBound);
6665     else if (LoOverflow)
6666       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6667                           ICmpInst::ICMP_ULT, X, HiBound);
6668     else
6669       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6670   case ICmpInst::ICMP_NE:
6671     if (LoOverflow && HiOverflow)
6672       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6673     else if (HiOverflow)
6674       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6675                           ICmpInst::ICMP_ULT, X, LoBound);
6676     else if (LoOverflow)
6677       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6678                           ICmpInst::ICMP_UGE, X, HiBound);
6679     else
6680       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6681   case ICmpInst::ICMP_ULT:
6682   case ICmpInst::ICMP_SLT:
6683     if (LoOverflow == +1)   // Low bound is greater than input range.
6684       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6685     if (LoOverflow == -1)   // Low bound is less than input range.
6686       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6687     return new ICmpInst(*Context, Pred, X, LoBound);
6688   case ICmpInst::ICMP_UGT:
6689   case ICmpInst::ICMP_SGT:
6690     if (HiOverflow == +1)       // High bound greater than input range.
6691       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6692     else if (HiOverflow == -1)  // High bound less than input range.
6693       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6694     if (Pred == ICmpInst::ICMP_UGT)
6695       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6696     else
6697       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6698   }
6699 }
6700
6701
6702 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6703 ///
6704 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6705                                                           Instruction *LHSI,
6706                                                           ConstantInt *RHS) {
6707   const APInt &RHSV = RHS->getValue();
6708   
6709   switch (LHSI->getOpcode()) {
6710   case Instruction::Trunc:
6711     if (ICI.isEquality() && LHSI->hasOneUse()) {
6712       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6713       // of the high bits truncated out of x are known.
6714       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6715              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6716       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6717       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6718       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6719       
6720       // If all the high bits are known, we can do this xform.
6721       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6722         // Pull in the high bits from known-ones set.
6723         APInt NewRHS(RHS->getValue());
6724         NewRHS.zext(SrcBits);
6725         NewRHS |= KnownOne;
6726         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6727                             ConstantInt::get(*Context, NewRHS));
6728       }
6729     }
6730     break;
6731       
6732   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6733     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6734       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6735       // fold the xor.
6736       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6737           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6738         Value *CompareVal = LHSI->getOperand(0);
6739         
6740         // If the sign bit of the XorCST is not set, there is no change to
6741         // the operation, just stop using the Xor.
6742         if (!XorCST->getValue().isNegative()) {
6743           ICI.setOperand(0, CompareVal);
6744           AddToWorkList(LHSI);
6745           return &ICI;
6746         }
6747         
6748         // Was the old condition true if the operand is positive?
6749         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6750         
6751         // If so, the new one isn't.
6752         isTrueIfPositive ^= true;
6753         
6754         if (isTrueIfPositive)
6755           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6756                               SubOne(RHS, Context));
6757         else
6758           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6759                               AddOne(RHS, Context));
6760       }
6761
6762       if (LHSI->hasOneUse()) {
6763         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6764         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6765           const APInt &SignBit = XorCST->getValue();
6766           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6767                                          ? ICI.getUnsignedPredicate()
6768                                          : ICI.getSignedPredicate();
6769           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6770                               ConstantInt::get(*Context, RHSV ^ SignBit));
6771         }
6772
6773         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6774         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6775           const APInt &NotSignBit = XorCST->getValue();
6776           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6777                                          ? ICI.getUnsignedPredicate()
6778                                          : ICI.getSignedPredicate();
6779           Pred = ICI.getSwappedPredicate(Pred);
6780           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6781                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6782         }
6783       }
6784     }
6785     break;
6786   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6787     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6788         LHSI->getOperand(0)->hasOneUse()) {
6789       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6790       
6791       // If the LHS is an AND of a truncating cast, we can widen the
6792       // and/compare to be the input width without changing the value
6793       // produced, eliminating a cast.
6794       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6795         // We can do this transformation if either the AND constant does not
6796         // have its sign bit set or if it is an equality comparison. 
6797         // Extending a relational comparison when we're checking the sign
6798         // bit would not work.
6799         if (Cast->hasOneUse() &&
6800             (ICI.isEquality() ||
6801              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6802           uint32_t BitWidth = 
6803             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6804           APInt NewCST = AndCST->getValue();
6805           NewCST.zext(BitWidth);
6806           APInt NewCI = RHSV;
6807           NewCI.zext(BitWidth);
6808           Instruction *NewAnd = 
6809             BinaryOperator::CreateAnd(Cast->getOperand(0),
6810                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6811           InsertNewInstBefore(NewAnd, ICI);
6812           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6813                               ConstantInt::get(*Context, NewCI));
6814         }
6815       }
6816       
6817       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6818       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6819       // happens a LOT in code produced by the C front-end, for bitfield
6820       // access.
6821       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6822       if (Shift && !Shift->isShift())
6823         Shift = 0;
6824       
6825       ConstantInt *ShAmt;
6826       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6827       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6828       const Type *AndTy = AndCST->getType();          // Type of the and.
6829       
6830       // We can fold this as long as we can't shift unknown bits
6831       // into the mask.  This can only happen with signed shift
6832       // rights, as they sign-extend.
6833       if (ShAmt) {
6834         bool CanFold = Shift->isLogicalShift();
6835         if (!CanFold) {
6836           // To test for the bad case of the signed shr, see if any
6837           // of the bits shifted in could be tested after the mask.
6838           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6839           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6840           
6841           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6842           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6843                AndCST->getValue()) == 0)
6844             CanFold = true;
6845         }
6846         
6847         if (CanFold) {
6848           Constant *NewCst;
6849           if (Shift->getOpcode() == Instruction::Shl)
6850             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6851           else
6852             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6853           
6854           // Check to see if we are shifting out any of the bits being
6855           // compared.
6856           if (ConstantExpr::get(Shift->getOpcode(),
6857                                        NewCst, ShAmt) != RHS) {
6858             // If we shifted bits out, the fold is not going to work out.
6859             // As a special case, check to see if this means that the
6860             // result is always true or false now.
6861             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6862               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6863             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6864               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6865           } else {
6866             ICI.setOperand(1, NewCst);
6867             Constant *NewAndCST;
6868             if (Shift->getOpcode() == Instruction::Shl)
6869               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6870             else
6871               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6872             LHSI->setOperand(1, NewAndCST);
6873             LHSI->setOperand(0, Shift->getOperand(0));
6874             AddToWorkList(Shift); // Shift is dead.
6875             AddUsesToWorkList(ICI);
6876             return &ICI;
6877           }
6878         }
6879       }
6880       
6881       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6882       // preferable because it allows the C<<Y expression to be hoisted out
6883       // of a loop if Y is invariant and X is not.
6884       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6885           ICI.isEquality() && !Shift->isArithmeticShift() &&
6886           !isa<Constant>(Shift->getOperand(0))) {
6887         // Compute C << Y.
6888         Value *NS;
6889         if (Shift->getOpcode() == Instruction::LShr) {
6890           NS = BinaryOperator::CreateShl(AndCST, 
6891                                          Shift->getOperand(1), "tmp");
6892         } else {
6893           // Insert a logical shift.
6894           NS = BinaryOperator::CreateLShr(AndCST,
6895                                           Shift->getOperand(1), "tmp");
6896         }
6897         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6898         
6899         // Compute X & (C << Y).
6900         Instruction *NewAnd = 
6901           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6902         InsertNewInstBefore(NewAnd, ICI);
6903         
6904         ICI.setOperand(0, NewAnd);
6905         return &ICI;
6906       }
6907     }
6908     break;
6909     
6910   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6911     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6912     if (!ShAmt) break;
6913     
6914     uint32_t TypeBits = RHSV.getBitWidth();
6915     
6916     // Check that the shift amount is in range.  If not, don't perform
6917     // undefined shifts.  When the shift is visited it will be
6918     // simplified.
6919     if (ShAmt->uge(TypeBits))
6920       break;
6921     
6922     if (ICI.isEquality()) {
6923       // If we are comparing against bits always shifted out, the
6924       // comparison cannot succeed.
6925       Constant *Comp =
6926         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6927                                                                  ShAmt);
6928       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6929         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6930         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6931         return ReplaceInstUsesWith(ICI, Cst);
6932       }
6933       
6934       if (LHSI->hasOneUse()) {
6935         // Otherwise strength reduce the shift into an and.
6936         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6937         Constant *Mask =
6938           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6939                                                        TypeBits-ShAmtVal));
6940         
6941         Instruction *AndI =
6942           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6943                                     Mask, LHSI->getName()+".mask");
6944         Value *And = InsertNewInstBefore(AndI, ICI);
6945         return new ICmpInst(*Context, ICI.getPredicate(), And,
6946                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6947       }
6948     }
6949     
6950     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6951     bool TrueIfSigned = false;
6952     if (LHSI->hasOneUse() &&
6953         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6954       // (X << 31) <s 0  --> (X&1) != 0
6955       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6956                                            (TypeBits-ShAmt->getZExtValue()-1));
6957       Instruction *AndI =
6958         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6959                                   Mask, LHSI->getName()+".mask");
6960       Value *And = InsertNewInstBefore(AndI, ICI);
6961       
6962       return new ICmpInst(*Context,
6963                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6964                           And, Constant::getNullValue(And->getType()));
6965     }
6966     break;
6967   }
6968     
6969   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6970   case Instruction::AShr: {
6971     // Only handle equality comparisons of shift-by-constant.
6972     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6973     if (!ShAmt || !ICI.isEquality()) break;
6974
6975     // Check that the shift amount is in range.  If not, don't perform
6976     // undefined shifts.  When the shift is visited it will be
6977     // simplified.
6978     uint32_t TypeBits = RHSV.getBitWidth();
6979     if (ShAmt->uge(TypeBits))
6980       break;
6981     
6982     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6983       
6984     // If we are comparing against bits always shifted out, the
6985     // comparison cannot succeed.
6986     APInt Comp = RHSV << ShAmtVal;
6987     if (LHSI->getOpcode() == Instruction::LShr)
6988       Comp = Comp.lshr(ShAmtVal);
6989     else
6990       Comp = Comp.ashr(ShAmtVal);
6991     
6992     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6993       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6994       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6995       return ReplaceInstUsesWith(ICI, Cst);
6996     }
6997     
6998     // Otherwise, check to see if the bits shifted out are known to be zero.
6999     // If so, we can compare against the unshifted value:
7000     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7001     if (LHSI->hasOneUse() &&
7002         MaskedValueIsZero(LHSI->getOperand(0), 
7003                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7004       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7005                           ConstantExpr::getShl(RHS, ShAmt));
7006     }
7007       
7008     if (LHSI->hasOneUse()) {
7009       // Otherwise strength reduce the shift into an and.
7010       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7011       Constant *Mask = ConstantInt::get(*Context, Val);
7012       
7013       Instruction *AndI =
7014         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7015                                   Mask, LHSI->getName()+".mask");
7016       Value *And = InsertNewInstBefore(AndI, ICI);
7017       return new ICmpInst(*Context, ICI.getPredicate(), And,
7018                           ConstantExpr::getShl(RHS, ShAmt));
7019     }
7020     break;
7021   }
7022     
7023   case Instruction::SDiv:
7024   case Instruction::UDiv:
7025     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7026     // Fold this div into the comparison, producing a range check. 
7027     // Determine, based on the divide type, what the range is being 
7028     // checked.  If there is an overflow on the low or high side, remember 
7029     // it, otherwise compute the range [low, hi) bounding the new value.
7030     // See: InsertRangeTest above for the kinds of replacements possible.
7031     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7032       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7033                                           DivRHS))
7034         return R;
7035     break;
7036
7037   case Instruction::Add:
7038     // Fold: icmp pred (add, X, C1), C2
7039
7040     if (!ICI.isEquality()) {
7041       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7042       if (!LHSC) break;
7043       const APInt &LHSV = LHSC->getValue();
7044
7045       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7046                             .subtract(LHSV);
7047
7048       if (ICI.isSignedPredicate()) {
7049         if (CR.getLower().isSignBit()) {
7050           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7051                               ConstantInt::get(*Context, CR.getUpper()));
7052         } else if (CR.getUpper().isSignBit()) {
7053           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7054                               ConstantInt::get(*Context, CR.getLower()));
7055         }
7056       } else {
7057         if (CR.getLower().isMinValue()) {
7058           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7059                               ConstantInt::get(*Context, CR.getUpper()));
7060         } else if (CR.getUpper().isMinValue()) {
7061           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7062                               ConstantInt::get(*Context, CR.getLower()));
7063         }
7064       }
7065     }
7066     break;
7067   }
7068   
7069   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7070   if (ICI.isEquality()) {
7071     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7072     
7073     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7074     // the second operand is a constant, simplify a bit.
7075     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7076       switch (BO->getOpcode()) {
7077       case Instruction::SRem:
7078         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7079         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7080           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7081           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7082             Instruction *NewRem =
7083               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7084                                          BO->getName());
7085             InsertNewInstBefore(NewRem, ICI);
7086             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7087                                 Constant::getNullValue(BO->getType()));
7088           }
7089         }
7090         break;
7091       case Instruction::Add:
7092         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7093         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7094           if (BO->hasOneUse())
7095             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7096                                 ConstantExpr::getSub(RHS, BOp1C));
7097         } else if (RHSV == 0) {
7098           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7099           // efficiently invertible, or if the add has just this one use.
7100           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7101           
7102           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7103             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7104           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7105             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7106           else if (BO->hasOneUse()) {
7107             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7108             InsertNewInstBefore(Neg, ICI);
7109             Neg->takeName(BO);
7110             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7111           }
7112         }
7113         break;
7114       case Instruction::Xor:
7115         // For the xor case, we can xor two constants together, eliminating
7116         // the explicit xor.
7117         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7118           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7119                               ConstantExpr::getXor(RHS, BOC));
7120         
7121         // FALLTHROUGH
7122       case Instruction::Sub:
7123         // Replace (([sub|xor] A, B) != 0) with (A != B)
7124         if (RHSV == 0)
7125           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7126                               BO->getOperand(1));
7127         break;
7128         
7129       case Instruction::Or:
7130         // If bits are being or'd in that are not present in the constant we
7131         // are comparing against, then the comparison could never succeed!
7132         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7133           Constant *NotCI = ConstantExpr::getNot(RHS);
7134           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7135             return ReplaceInstUsesWith(ICI,
7136                                        ConstantInt::get(Type::Int1Ty, 
7137                                        isICMP_NE));
7138         }
7139         break;
7140         
7141       case Instruction::And:
7142         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7143           // If bits are being compared against that are and'd out, then the
7144           // comparison can never succeed!
7145           if ((RHSV & ~BOC->getValue()) != 0)
7146             return ReplaceInstUsesWith(ICI,
7147                                        ConstantInt::get(Type::Int1Ty,
7148                                        isICMP_NE));
7149           
7150           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7151           if (RHS == BOC && RHSV.isPowerOf2())
7152             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7153                                 ICmpInst::ICMP_NE, LHSI,
7154                                 Constant::getNullValue(RHS->getType()));
7155           
7156           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7157           if (BOC->getValue().isSignBit()) {
7158             Value *X = BO->getOperand(0);
7159             Constant *Zero = Constant::getNullValue(X->getType());
7160             ICmpInst::Predicate pred = isICMP_NE ? 
7161               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7162             return new ICmpInst(*Context, pred, X, Zero);
7163           }
7164           
7165           // ((X & ~7) == 0) --> X < 8
7166           if (RHSV == 0 && isHighOnes(BOC)) {
7167             Value *X = BO->getOperand(0);
7168             Constant *NegX = ConstantExpr::getNeg(BOC);
7169             ICmpInst::Predicate pred = isICMP_NE ? 
7170               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7171             return new ICmpInst(*Context, pred, X, NegX);
7172           }
7173         }
7174       default: break;
7175       }
7176     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7177       // Handle icmp {eq|ne} <intrinsic>, intcst.
7178       if (II->getIntrinsicID() == Intrinsic::bswap) {
7179         AddToWorkList(II);
7180         ICI.setOperand(0, II->getOperand(1));
7181         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7182         return &ICI;
7183       }
7184     }
7185   }
7186   return 0;
7187 }
7188
7189 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7190 /// We only handle extending casts so far.
7191 ///
7192 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7193   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7194   Value *LHSCIOp        = LHSCI->getOperand(0);
7195   const Type *SrcTy     = LHSCIOp->getType();
7196   const Type *DestTy    = LHSCI->getType();
7197   Value *RHSCIOp;
7198
7199   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7200   // integer type is the same size as the pointer type.
7201   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7202       TD->getPointerSizeInBits() ==
7203          cast<IntegerType>(DestTy)->getBitWidth()) {
7204     Value *RHSOp = 0;
7205     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7206       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7207     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7208       RHSOp = RHSC->getOperand(0);
7209       // If the pointer types don't match, insert a bitcast.
7210       if (LHSCIOp->getType() != RHSOp->getType())
7211         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7212     }
7213
7214     if (RHSOp)
7215       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7216   }
7217   
7218   // The code below only handles extension cast instructions, so far.
7219   // Enforce this.
7220   if (LHSCI->getOpcode() != Instruction::ZExt &&
7221       LHSCI->getOpcode() != Instruction::SExt)
7222     return 0;
7223
7224   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7225   bool isSignedCmp = ICI.isSignedPredicate();
7226
7227   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7228     // Not an extension from the same type?
7229     RHSCIOp = CI->getOperand(0);
7230     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7231       return 0;
7232     
7233     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7234     // and the other is a zext), then we can't handle this.
7235     if (CI->getOpcode() != LHSCI->getOpcode())
7236       return 0;
7237
7238     // Deal with equality cases early.
7239     if (ICI.isEquality())
7240       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7241
7242     // A signed comparison of sign extended values simplifies into a
7243     // signed comparison.
7244     if (isSignedCmp && isSignedExt)
7245       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7246
7247     // The other three cases all fold into an unsigned comparison.
7248     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7249   }
7250
7251   // If we aren't dealing with a constant on the RHS, exit early
7252   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7253   if (!CI)
7254     return 0;
7255
7256   // Compute the constant that would happen if we truncated to SrcTy then
7257   // reextended to DestTy.
7258   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7259   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7260                                                 Res1, DestTy);
7261
7262   // If the re-extended constant didn't change...
7263   if (Res2 == CI) {
7264     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7265     // For example, we might have:
7266     //    %A = sext i16 %X to i32
7267     //    %B = icmp ugt i32 %A, 1330
7268     // It is incorrect to transform this into 
7269     //    %B = icmp ugt i16 %X, 1330
7270     // because %A may have negative value. 
7271     //
7272     // However, we allow this when the compare is EQ/NE, because they are
7273     // signless.
7274     if (isSignedExt == isSignedCmp || ICI.isEquality())
7275       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7276     return 0;
7277   }
7278
7279   // The re-extended constant changed so the constant cannot be represented 
7280   // in the shorter type. Consequently, we cannot emit a simple comparison.
7281
7282   // First, handle some easy cases. We know the result cannot be equal at this
7283   // point so handle the ICI.isEquality() cases
7284   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7285     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7286   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7287     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7288
7289   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7290   // should have been folded away previously and not enter in here.
7291   Value *Result;
7292   if (isSignedCmp) {
7293     // We're performing a signed comparison.
7294     if (cast<ConstantInt>(CI)->getValue().isNegative())
7295       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7296     else
7297       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7298   } else {
7299     // We're performing an unsigned comparison.
7300     if (isSignedExt) {
7301       // We're performing an unsigned comp with a sign extended value.
7302       // This is true if the input is >= 0. [aka >s -1]
7303       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7304       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7305                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7306     } else {
7307       // Unsigned extend & unsigned compare -> always true.
7308       Result = ConstantInt::getTrue(*Context);
7309     }
7310   }
7311
7312   // Finally, return the value computed.
7313   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7314       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7315     return ReplaceInstUsesWith(ICI, Result);
7316
7317   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7318           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7319          "ICmp should be folded!");
7320   if (Constant *CI = dyn_cast<Constant>(Result))
7321     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7322   return BinaryOperator::CreateNot(*Context, Result);
7323 }
7324
7325 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7326   return commonShiftTransforms(I);
7327 }
7328
7329 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7330   return commonShiftTransforms(I);
7331 }
7332
7333 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7334   if (Instruction *R = commonShiftTransforms(I))
7335     return R;
7336   
7337   Value *Op0 = I.getOperand(0);
7338   
7339   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7340   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7341     if (CSI->isAllOnesValue())
7342       return ReplaceInstUsesWith(I, CSI);
7343
7344   // See if we can turn a signed shr into an unsigned shr.
7345   if (MaskedValueIsZero(Op0,
7346                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7347     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7348
7349   // Arithmetic shifting an all-sign-bit value is a no-op.
7350   unsigned NumSignBits = ComputeNumSignBits(Op0);
7351   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7352     return ReplaceInstUsesWith(I, Op0);
7353
7354   return 0;
7355 }
7356
7357 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7358   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7359   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7360
7361   // shl X, 0 == X and shr X, 0 == X
7362   // shl 0, X == 0 and shr 0, X == 0
7363   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7364       Op0 == Constant::getNullValue(Op0->getType()))
7365     return ReplaceInstUsesWith(I, Op0);
7366   
7367   if (isa<UndefValue>(Op0)) {            
7368     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7369       return ReplaceInstUsesWith(I, Op0);
7370     else                                    // undef << X -> 0, undef >>u X -> 0
7371       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7372   }
7373   if (isa<UndefValue>(Op1)) {
7374     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7375       return ReplaceInstUsesWith(I, Op0);          
7376     else                                     // X << undef, X >>u undef -> 0
7377       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7378   }
7379
7380   // See if we can fold away this shift.
7381   if (SimplifyDemandedInstructionBits(I))
7382     return &I;
7383
7384   // Try to fold constant and into select arguments.
7385   if (isa<Constant>(Op0))
7386     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7387       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7388         return R;
7389
7390   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7391     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7392       return Res;
7393   return 0;
7394 }
7395
7396 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7397                                                BinaryOperator &I) {
7398   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7399
7400   // See if we can simplify any instructions used by the instruction whose sole 
7401   // purpose is to compute bits we don't care about.
7402   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7403   
7404   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7405   // a signed shift.
7406   //
7407   if (Op1->uge(TypeBits)) {
7408     if (I.getOpcode() != Instruction::AShr)
7409       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7410     else {
7411       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7412       return &I;
7413     }
7414   }
7415   
7416   // ((X*C1) << C2) == (X * (C1 << C2))
7417   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7418     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7419       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7420         return BinaryOperator::CreateMul(BO->getOperand(0),
7421                                         ConstantExpr::getShl(BOOp, Op1));
7422   
7423   // Try to fold constant and into select arguments.
7424   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7425     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7426       return R;
7427   if (isa<PHINode>(Op0))
7428     if (Instruction *NV = FoldOpIntoPhi(I))
7429       return NV;
7430   
7431   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7432   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7433     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7434     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7435     // place.  Don't try to do this transformation in this case.  Also, we
7436     // require that the input operand is a shift-by-constant so that we have
7437     // confidence that the shifts will get folded together.  We could do this
7438     // xform in more cases, but it is unlikely to be profitable.
7439     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7440         isa<ConstantInt>(TrOp->getOperand(1))) {
7441       // Okay, we'll do this xform.  Make the shift of shift.
7442       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7443       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7444                                                 I.getName());
7445       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7446
7447       // For logical shifts, the truncation has the effect of making the high
7448       // part of the register be zeros.  Emulate this by inserting an AND to
7449       // clear the top bits as needed.  This 'and' will usually be zapped by
7450       // other xforms later if dead.
7451       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7452       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7453       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7454       
7455       // The mask we constructed says what the trunc would do if occurring
7456       // between the shifts.  We want to know the effect *after* the second
7457       // shift.  We know that it is a logical shift by a constant, so adjust the
7458       // mask as appropriate.
7459       if (I.getOpcode() == Instruction::Shl)
7460         MaskV <<= Op1->getZExtValue();
7461       else {
7462         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7463         MaskV = MaskV.lshr(Op1->getZExtValue());
7464       }
7465
7466       Instruction *And =
7467         BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV), 
7468                                   TI->getName());
7469       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7470
7471       // Return the value truncated to the interesting size.
7472       return new TruncInst(And, I.getType());
7473     }
7474   }
7475   
7476   if (Op0->hasOneUse()) {
7477     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7478       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7479       Value *V1, *V2;
7480       ConstantInt *CC;
7481       switch (Op0BO->getOpcode()) {
7482         default: break;
7483         case Instruction::Add:
7484         case Instruction::And:
7485         case Instruction::Or:
7486         case Instruction::Xor: {
7487           // These operators commute.
7488           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7489           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7490               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7491                     m_Specific(Op1)), *Context)){
7492             Instruction *YS = BinaryOperator::CreateShl(
7493                                             Op0BO->getOperand(0), Op1,
7494                                             Op0BO->getName());
7495             InsertNewInstBefore(YS, I); // (Y << C)
7496             Instruction *X = 
7497               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7498                                      Op0BO->getOperand(1)->getName());
7499             InsertNewInstBefore(X, I);  // (X + (Y << C))
7500             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7501             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7502                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7503           }
7504           
7505           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7506           Value *Op0BOOp1 = Op0BO->getOperand(1);
7507           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7508               match(Op0BOOp1, 
7509                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7510                           m_ConstantInt(CC)), *Context) &&
7511               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7512             Instruction *YS = BinaryOperator::CreateShl(
7513                                                      Op0BO->getOperand(0), Op1,
7514                                                      Op0BO->getName());
7515             InsertNewInstBefore(YS, I); // (Y << C)
7516             Instruction *XM =
7517               BinaryOperator::CreateAnd(V1,
7518                                         ConstantExpr::getShl(CC, Op1),
7519                                         V1->getName()+".mask");
7520             InsertNewInstBefore(XM, I); // X & (CC << C)
7521             
7522             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7523           }
7524         }
7525           
7526         // FALL THROUGH.
7527         case Instruction::Sub: {
7528           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7529           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7530               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7531                     m_Specific(Op1)), *Context)){
7532             Instruction *YS = BinaryOperator::CreateShl(
7533                                                      Op0BO->getOperand(1), Op1,
7534                                                      Op0BO->getName());
7535             InsertNewInstBefore(YS, I); // (Y << C)
7536             Instruction *X =
7537               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7538                                      Op0BO->getOperand(0)->getName());
7539             InsertNewInstBefore(X, I);  // (X + (Y << C))
7540             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7541             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7542                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7543           }
7544           
7545           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7546           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7547               match(Op0BO->getOperand(0),
7548                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7549                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7550               cast<BinaryOperator>(Op0BO->getOperand(0))
7551                   ->getOperand(0)->hasOneUse()) {
7552             Instruction *YS = BinaryOperator::CreateShl(
7553                                                      Op0BO->getOperand(1), Op1,
7554                                                      Op0BO->getName());
7555             InsertNewInstBefore(YS, I); // (Y << C)
7556             Instruction *XM =
7557               BinaryOperator::CreateAnd(V1, 
7558                                         ConstantExpr::getShl(CC, Op1),
7559                                         V1->getName()+".mask");
7560             InsertNewInstBefore(XM, I); // X & (CC << C)
7561             
7562             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7563           }
7564           
7565           break;
7566         }
7567       }
7568       
7569       
7570       // If the operand is an bitwise operator with a constant RHS, and the
7571       // shift is the only use, we can pull it out of the shift.
7572       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7573         bool isValid = true;     // Valid only for And, Or, Xor
7574         bool highBitSet = false; // Transform if high bit of constant set?
7575         
7576         switch (Op0BO->getOpcode()) {
7577           default: isValid = false; break;   // Do not perform transform!
7578           case Instruction::Add:
7579             isValid = isLeftShift;
7580             break;
7581           case Instruction::Or:
7582           case Instruction::Xor:
7583             highBitSet = false;
7584             break;
7585           case Instruction::And:
7586             highBitSet = true;
7587             break;
7588         }
7589         
7590         // If this is a signed shift right, and the high bit is modified
7591         // by the logical operation, do not perform the transformation.
7592         // The highBitSet boolean indicates the value of the high bit of
7593         // the constant which would cause it to be modified for this
7594         // operation.
7595         //
7596         if (isValid && I.getOpcode() == Instruction::AShr)
7597           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7598         
7599         if (isValid) {
7600           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7601           
7602           Instruction *NewShift =
7603             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7604           InsertNewInstBefore(NewShift, I);
7605           NewShift->takeName(Op0BO);
7606           
7607           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7608                                         NewRHS);
7609         }
7610       }
7611     }
7612   }
7613   
7614   // Find out if this is a shift of a shift by a constant.
7615   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7616   if (ShiftOp && !ShiftOp->isShift())
7617     ShiftOp = 0;
7618   
7619   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7620     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7621     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7622     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7623     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7624     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7625     Value *X = ShiftOp->getOperand(0);
7626     
7627     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7628     
7629     const IntegerType *Ty = cast<IntegerType>(I.getType());
7630     
7631     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7632     if (I.getOpcode() == ShiftOp->getOpcode()) {
7633       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7634       // saturates.
7635       if (AmtSum >= TypeBits) {
7636         if (I.getOpcode() != Instruction::AShr)
7637           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7638         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7639       }
7640       
7641       return BinaryOperator::Create(I.getOpcode(), X,
7642                                     ConstantInt::get(Ty, AmtSum));
7643     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7644                I.getOpcode() == Instruction::AShr) {
7645       if (AmtSum >= TypeBits)
7646         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7647       
7648       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7649       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7650     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7651                I.getOpcode() == Instruction::LShr) {
7652       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7653       if (AmtSum >= TypeBits)
7654         AmtSum = TypeBits-1;
7655       
7656       Instruction *Shift =
7657         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7658       InsertNewInstBefore(Shift, I);
7659
7660       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7661       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7662     }
7663     
7664     // Okay, if we get here, one shift must be left, and the other shift must be
7665     // right.  See if the amounts are equal.
7666     if (ShiftAmt1 == ShiftAmt2) {
7667       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7668       if (I.getOpcode() == Instruction::Shl) {
7669         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7670         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7671       }
7672       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7673       if (I.getOpcode() == Instruction::LShr) {
7674         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7675         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7676       }
7677       // We can simplify ((X << C) >>s C) into a trunc + sext.
7678       // NOTE: we could do this for any C, but that would make 'unusual' integer
7679       // types.  For now, just stick to ones well-supported by the code
7680       // generators.
7681       const Type *SExtType = 0;
7682       switch (Ty->getBitWidth() - ShiftAmt1) {
7683       case 1  :
7684       case 8  :
7685       case 16 :
7686       case 32 :
7687       case 64 :
7688       case 128:
7689         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7690         break;
7691       default: break;
7692       }
7693       if (SExtType) {
7694         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7695         InsertNewInstBefore(NewTrunc, I);
7696         return new SExtInst(NewTrunc, Ty);
7697       }
7698       // Otherwise, we can't handle it yet.
7699     } else if (ShiftAmt1 < ShiftAmt2) {
7700       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7701       
7702       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7703       if (I.getOpcode() == Instruction::Shl) {
7704         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7705                ShiftOp->getOpcode() == Instruction::AShr);
7706         Instruction *Shift =
7707           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7708         InsertNewInstBefore(Shift, I);
7709         
7710         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7711         return BinaryOperator::CreateAnd(Shift,
7712                                          ConstantInt::get(*Context, Mask));
7713       }
7714       
7715       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7716       if (I.getOpcode() == Instruction::LShr) {
7717         assert(ShiftOp->getOpcode() == Instruction::Shl);
7718         Instruction *Shift =
7719           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7720         InsertNewInstBefore(Shift, I);
7721         
7722         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7723         return BinaryOperator::CreateAnd(Shift,
7724                                          ConstantInt::get(*Context, Mask));
7725       }
7726       
7727       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7728     } else {
7729       assert(ShiftAmt2 < ShiftAmt1);
7730       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7731
7732       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7733       if (I.getOpcode() == Instruction::Shl) {
7734         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7735                ShiftOp->getOpcode() == Instruction::AShr);
7736         Instruction *Shift =
7737           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7738                                  ConstantInt::get(Ty, ShiftDiff));
7739         InsertNewInstBefore(Shift, I);
7740         
7741         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7742         return BinaryOperator::CreateAnd(Shift,
7743                                          ConstantInt::get(*Context, Mask));
7744       }
7745       
7746       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7747       if (I.getOpcode() == Instruction::LShr) {
7748         assert(ShiftOp->getOpcode() == Instruction::Shl);
7749         Instruction *Shift =
7750           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7751         InsertNewInstBefore(Shift, I);
7752         
7753         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7754         return BinaryOperator::CreateAnd(Shift,
7755                                          ConstantInt::get(*Context, Mask));
7756       }
7757       
7758       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7759     }
7760   }
7761   return 0;
7762 }
7763
7764
7765 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7766 /// expression.  If so, decompose it, returning some value X, such that Val is
7767 /// X*Scale+Offset.
7768 ///
7769 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7770                                         int &Offset, LLVMContext *Context) {
7771   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7772   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7773     Offset = CI->getZExtValue();
7774     Scale  = 0;
7775     return ConstantInt::get(Type::Int32Ty, 0);
7776   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7777     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7778       if (I->getOpcode() == Instruction::Shl) {
7779         // This is a value scaled by '1 << the shift amt'.
7780         Scale = 1U << RHS->getZExtValue();
7781         Offset = 0;
7782         return I->getOperand(0);
7783       } else if (I->getOpcode() == Instruction::Mul) {
7784         // This value is scaled by 'RHS'.
7785         Scale = RHS->getZExtValue();
7786         Offset = 0;
7787         return I->getOperand(0);
7788       } else if (I->getOpcode() == Instruction::Add) {
7789         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7790         // where C1 is divisible by C2.
7791         unsigned SubScale;
7792         Value *SubVal = 
7793           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7794                                     Offset, Context);
7795         Offset += RHS->getZExtValue();
7796         Scale = SubScale;
7797         return SubVal;
7798       }
7799     }
7800   }
7801
7802   // Otherwise, we can't look past this.
7803   Scale = 1;
7804   Offset = 0;
7805   return Val;
7806 }
7807
7808
7809 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7810 /// try to eliminate the cast by moving the type information into the alloc.
7811 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7812                                                    AllocationInst &AI) {
7813   const PointerType *PTy = cast<PointerType>(CI.getType());
7814   
7815   // Remove any uses of AI that are dead.
7816   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7817   
7818   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7819     Instruction *User = cast<Instruction>(*UI++);
7820     if (isInstructionTriviallyDead(User)) {
7821       while (UI != E && *UI == User)
7822         ++UI; // If this instruction uses AI more than once, don't break UI.
7823       
7824       ++NumDeadInst;
7825       DOUT << "IC: DCE: " << *User;
7826       EraseInstFromFunction(*User);
7827     }
7828   }
7829
7830   // This requires TargetData to get the alloca alignment and size information.
7831   if (!TD) return 0;
7832
7833   // Get the type really allocated and the type casted to.
7834   const Type *AllocElTy = AI.getAllocatedType();
7835   const Type *CastElTy = PTy->getElementType();
7836   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7837
7838   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7839   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7840   if (CastElTyAlign < AllocElTyAlign) return 0;
7841
7842   // If the allocation has multiple uses, only promote it if we are strictly
7843   // increasing the alignment of the resultant allocation.  If we keep it the
7844   // same, we open the door to infinite loops of various kinds.  (A reference
7845   // from a dbg.declare doesn't count as a use for this purpose.)
7846   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7847       CastElTyAlign == AllocElTyAlign) return 0;
7848
7849   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7850   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7851   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7852
7853   // See if we can satisfy the modulus by pulling a scale out of the array
7854   // size argument.
7855   unsigned ArraySizeScale;
7856   int ArrayOffset;
7857   Value *NumElements = // See if the array size is a decomposable linear expr.
7858     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7859                               ArrayOffset, Context);
7860  
7861   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7862   // do the xform.
7863   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7864       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7865
7866   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7867   Value *Amt = 0;
7868   if (Scale == 1) {
7869     Amt = NumElements;
7870   } else {
7871     // If the allocation size is constant, form a constant mul expression
7872     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7873     if (isa<ConstantInt>(NumElements))
7874       Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7875                                  cast<ConstantInt>(Amt));
7876     // otherwise multiply the amount and the number of elements
7877     else {
7878       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7879       Amt = InsertNewInstBefore(Tmp, AI);
7880     }
7881   }
7882   
7883   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7884     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7885     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7886     Amt = InsertNewInstBefore(Tmp, AI);
7887   }
7888   
7889   AllocationInst *New;
7890   if (isa<MallocInst>(AI))
7891     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7892   else
7893     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7894   InsertNewInstBefore(New, AI);
7895   New->takeName(&AI);
7896   
7897   // If the allocation has one real use plus a dbg.declare, just remove the
7898   // declare.
7899   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7900     EraseInstFromFunction(*DI);
7901   }
7902   // If the allocation has multiple real uses, insert a cast and change all
7903   // things that used it to use the new cast.  This will also hack on CI, but it
7904   // will die soon.
7905   else if (!AI.hasOneUse()) {
7906     AddUsesToWorkList(AI);
7907     // New is the allocation instruction, pointer typed. AI is the original
7908     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7909     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7910     InsertNewInstBefore(NewCast, AI);
7911     AI.replaceAllUsesWith(NewCast);
7912   }
7913   return ReplaceInstUsesWith(CI, New);
7914 }
7915
7916 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7917 /// and return it as type Ty without inserting any new casts and without
7918 /// changing the computed value.  This is used by code that tries to decide
7919 /// whether promoting or shrinking integer operations to wider or smaller types
7920 /// will allow us to eliminate a truncate or extend.
7921 ///
7922 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7923 /// extension operation if Ty is larger.
7924 ///
7925 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7926 /// should return true if trunc(V) can be computed by computing V in the smaller
7927 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7928 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7929 /// efficiently truncated.
7930 ///
7931 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7932 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7933 /// the final result.
7934 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7935                                               unsigned CastOpc,
7936                                               int &NumCastsRemoved){
7937   // We can always evaluate constants in another type.
7938   if (isa<Constant>(V))
7939     return true;
7940   
7941   Instruction *I = dyn_cast<Instruction>(V);
7942   if (!I) return false;
7943   
7944   const Type *OrigTy = V->getType();
7945   
7946   // If this is an extension or truncate, we can often eliminate it.
7947   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7948     // If this is a cast from the destination type, we can trivially eliminate
7949     // it, and this will remove a cast overall.
7950     if (I->getOperand(0)->getType() == Ty) {
7951       // If the first operand is itself a cast, and is eliminable, do not count
7952       // this as an eliminable cast.  We would prefer to eliminate those two
7953       // casts first.
7954       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7955         ++NumCastsRemoved;
7956       return true;
7957     }
7958   }
7959
7960   // We can't extend or shrink something that has multiple uses: doing so would
7961   // require duplicating the instruction in general, which isn't profitable.
7962   if (!I->hasOneUse()) return false;
7963
7964   unsigned Opc = I->getOpcode();
7965   switch (Opc) {
7966   case Instruction::Add:
7967   case Instruction::Sub:
7968   case Instruction::Mul:
7969   case Instruction::And:
7970   case Instruction::Or:
7971   case Instruction::Xor:
7972     // These operators can all arbitrarily be extended or truncated.
7973     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7974                                       NumCastsRemoved) &&
7975            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7976                                       NumCastsRemoved);
7977
7978   case Instruction::UDiv:
7979   case Instruction::URem: {
7980     // UDiv and URem can be truncated if all the truncated bits are zero.
7981     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7982     uint32_t BitWidth = Ty->getScalarSizeInBits();
7983     if (BitWidth < OrigBitWidth) {
7984       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7985       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7986           MaskedValueIsZero(I->getOperand(1), Mask)) {
7987         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7988                                           NumCastsRemoved) &&
7989                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7990                                           NumCastsRemoved);
7991       }
7992     }
7993     break;
7994   }
7995   case Instruction::Shl:
7996     // If we are truncating the result of this SHL, and if it's a shift of a
7997     // constant amount, we can always perform a SHL in a smaller type.
7998     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7999       uint32_t BitWidth = Ty->getScalarSizeInBits();
8000       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8001           CI->getLimitedValue(BitWidth) < BitWidth)
8002         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8003                                           NumCastsRemoved);
8004     }
8005     break;
8006   case Instruction::LShr:
8007     // If this is a truncate of a logical shr, we can truncate it to a smaller
8008     // lshr iff we know that the bits we would otherwise be shifting in are
8009     // already zeros.
8010     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8011       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8012       uint32_t BitWidth = Ty->getScalarSizeInBits();
8013       if (BitWidth < OrigBitWidth &&
8014           MaskedValueIsZero(I->getOperand(0),
8015             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8016           CI->getLimitedValue(BitWidth) < BitWidth) {
8017         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8018                                           NumCastsRemoved);
8019       }
8020     }
8021     break;
8022   case Instruction::ZExt:
8023   case Instruction::SExt:
8024   case Instruction::Trunc:
8025     // If this is the same kind of case as our original (e.g. zext+zext), we
8026     // can safely replace it.  Note that replacing it does not reduce the number
8027     // of casts in the input.
8028     if (Opc == CastOpc)
8029       return true;
8030
8031     // sext (zext ty1), ty2 -> zext ty2
8032     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8033       return true;
8034     break;
8035   case Instruction::Select: {
8036     SelectInst *SI = cast<SelectInst>(I);
8037     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8038                                       NumCastsRemoved) &&
8039            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8040                                       NumCastsRemoved);
8041   }
8042   case Instruction::PHI: {
8043     // We can change a phi if we can change all operands.
8044     PHINode *PN = cast<PHINode>(I);
8045     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8046       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8047                                       NumCastsRemoved))
8048         return false;
8049     return true;
8050   }
8051   default:
8052     // TODO: Can handle more cases here.
8053     break;
8054   }
8055   
8056   return false;
8057 }
8058
8059 /// EvaluateInDifferentType - Given an expression that 
8060 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8061 /// evaluate the expression.
8062 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8063                                              bool isSigned) {
8064   if (Constant *C = dyn_cast<Constant>(V))
8065     return ConstantExpr::getIntegerCast(C, Ty,
8066                                                isSigned /*Sext or ZExt*/);
8067
8068   // Otherwise, it must be an instruction.
8069   Instruction *I = cast<Instruction>(V);
8070   Instruction *Res = 0;
8071   unsigned Opc = I->getOpcode();
8072   switch (Opc) {
8073   case Instruction::Add:
8074   case Instruction::Sub:
8075   case Instruction::Mul:
8076   case Instruction::And:
8077   case Instruction::Or:
8078   case Instruction::Xor:
8079   case Instruction::AShr:
8080   case Instruction::LShr:
8081   case Instruction::Shl:
8082   case Instruction::UDiv:
8083   case Instruction::URem: {
8084     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8085     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8086     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8087     break;
8088   }    
8089   case Instruction::Trunc:
8090   case Instruction::ZExt:
8091   case Instruction::SExt:
8092     // If the source type of the cast is the type we're trying for then we can
8093     // just return the source.  There's no need to insert it because it is not
8094     // new.
8095     if (I->getOperand(0)->getType() == Ty)
8096       return I->getOperand(0);
8097     
8098     // Otherwise, must be the same type of cast, so just reinsert a new one.
8099     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8100                            Ty);
8101     break;
8102   case Instruction::Select: {
8103     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8104     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8105     Res = SelectInst::Create(I->getOperand(0), True, False);
8106     break;
8107   }
8108   case Instruction::PHI: {
8109     PHINode *OPN = cast<PHINode>(I);
8110     PHINode *NPN = PHINode::Create(Ty);
8111     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8112       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8113       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8114     }
8115     Res = NPN;
8116     break;
8117   }
8118   default: 
8119     // TODO: Can handle more cases here.
8120     llvm_unreachable("Unreachable!");
8121     break;
8122   }
8123   
8124   Res->takeName(I);
8125   return InsertNewInstBefore(Res, *I);
8126 }
8127
8128 /// @brief Implement the transforms common to all CastInst visitors.
8129 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8130   Value *Src = CI.getOperand(0);
8131
8132   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8133   // eliminate it now.
8134   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8135     if (Instruction::CastOps opc = 
8136         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8137       // The first cast (CSrc) is eliminable so we need to fix up or replace
8138       // the second cast (CI). CSrc will then have a good chance of being dead.
8139       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8140     }
8141   }
8142
8143   // If we are casting a select then fold the cast into the select
8144   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8145     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8146       return NV;
8147
8148   // If we are casting a PHI then fold the cast into the PHI
8149   if (isa<PHINode>(Src))
8150     if (Instruction *NV = FoldOpIntoPhi(CI))
8151       return NV;
8152   
8153   return 0;
8154 }
8155
8156 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8157 /// or not there is a sequence of GEP indices into the type that will land us at
8158 /// the specified offset.  If so, fill them into NewIndices and return the
8159 /// resultant element type, otherwise return null.
8160 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8161                                        SmallVectorImpl<Value*> &NewIndices,
8162                                        const TargetData *TD,
8163                                        LLVMContext *Context) {
8164   if (!TD) return 0;
8165   if (!Ty->isSized()) return 0;
8166   
8167   // Start with the index over the outer type.  Note that the type size
8168   // might be zero (even if the offset isn't zero) if the indexed type
8169   // is something like [0 x {int, int}]
8170   const Type *IntPtrTy = TD->getIntPtrType();
8171   int64_t FirstIdx = 0;
8172   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8173     FirstIdx = Offset/TySize;
8174     Offset -= FirstIdx*TySize;
8175     
8176     // Handle hosts where % returns negative instead of values [0..TySize).
8177     if (Offset < 0) {
8178       --FirstIdx;
8179       Offset += TySize;
8180       assert(Offset >= 0);
8181     }
8182     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8183   }
8184   
8185   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8186     
8187   // Index into the types.  If we fail, set OrigBase to null.
8188   while (Offset) {
8189     // Indexing into tail padding between struct/array elements.
8190     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8191       return 0;
8192     
8193     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8194       const StructLayout *SL = TD->getStructLayout(STy);
8195       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8196              "Offset must stay within the indexed type");
8197       
8198       unsigned Elt = SL->getElementContainingOffset(Offset);
8199       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8200       
8201       Offset -= SL->getElementOffset(Elt);
8202       Ty = STy->getElementType(Elt);
8203     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8204       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8205       assert(EltSize && "Cannot index into a zero-sized array");
8206       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8207       Offset %= EltSize;
8208       Ty = AT->getElementType();
8209     } else {
8210       // Otherwise, we can't index into the middle of this atomic type, bail.
8211       return 0;
8212     }
8213   }
8214   
8215   return Ty;
8216 }
8217
8218 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8219 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8220   Value *Src = CI.getOperand(0);
8221   
8222   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8223     // If casting the result of a getelementptr instruction with no offset, turn
8224     // this into a cast of the original pointer!
8225     if (GEP->hasAllZeroIndices()) {
8226       // Changing the cast operand is usually not a good idea but it is safe
8227       // here because the pointer operand is being replaced with another 
8228       // pointer operand so the opcode doesn't need to change.
8229       AddToWorkList(GEP);
8230       CI.setOperand(0, GEP->getOperand(0));
8231       return &CI;
8232     }
8233     
8234     // If the GEP has a single use, and the base pointer is a bitcast, and the
8235     // GEP computes a constant offset, see if we can convert these three
8236     // instructions into fewer.  This typically happens with unions and other
8237     // non-type-safe code.
8238     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8239       if (GEP->hasAllConstantIndices()) {
8240         // We are guaranteed to get a constant from EmitGEPOffset.
8241         ConstantInt *OffsetV =
8242                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8243         int64_t Offset = OffsetV->getSExtValue();
8244         
8245         // Get the base pointer input of the bitcast, and the type it points to.
8246         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8247         const Type *GEPIdxTy =
8248           cast<PointerType>(OrigBase->getType())->getElementType();
8249         SmallVector<Value*, 8> NewIndices;
8250         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8251           // If we were able to index down into an element, create the GEP
8252           // and bitcast the result.  This eliminates one bitcast, potentially
8253           // two.
8254           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8255                                                         NewIndices.begin(),
8256                                                         NewIndices.end(), "");
8257           InsertNewInstBefore(NGEP, CI);
8258           NGEP->takeName(GEP);
8259           if (cast<GEPOperator>(GEP)->isInBounds())
8260             cast<GEPOperator>(NGEP)->setIsInBounds(true);
8261           
8262           if (isa<BitCastInst>(CI))
8263             return new BitCastInst(NGEP, CI.getType());
8264           assert(isa<PtrToIntInst>(CI));
8265           return new PtrToIntInst(NGEP, CI.getType());
8266         }
8267       }      
8268     }
8269   }
8270     
8271   return commonCastTransforms(CI);
8272 }
8273
8274 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8275 /// type like i42.  We don't want to introduce operations on random non-legal
8276 /// integer types where they don't already exist in the code.  In the future,
8277 /// we should consider making this based off target-data, so that 32-bit targets
8278 /// won't get i64 operations etc.
8279 static bool isSafeIntegerType(const Type *Ty) {
8280   switch (Ty->getPrimitiveSizeInBits()) {
8281   case 8:
8282   case 16:
8283   case 32:
8284   case 64:
8285     return true;
8286   default: 
8287     return false;
8288   }
8289 }
8290
8291 /// commonIntCastTransforms - This function implements the common transforms
8292 /// for trunc, zext, and sext.
8293 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8294   if (Instruction *Result = commonCastTransforms(CI))
8295     return Result;
8296
8297   Value *Src = CI.getOperand(0);
8298   const Type *SrcTy = Src->getType();
8299   const Type *DestTy = CI.getType();
8300   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8301   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8302
8303   // See if we can simplify any instructions used by the LHS whose sole 
8304   // purpose is to compute bits we don't care about.
8305   if (SimplifyDemandedInstructionBits(CI))
8306     return &CI;
8307
8308   // If the source isn't an instruction or has more than one use then we
8309   // can't do anything more. 
8310   Instruction *SrcI = dyn_cast<Instruction>(Src);
8311   if (!SrcI || !Src->hasOneUse())
8312     return 0;
8313
8314   // Attempt to propagate the cast into the instruction for int->int casts.
8315   int NumCastsRemoved = 0;
8316   // Only do this if the dest type is a simple type, don't convert the
8317   // expression tree to something weird like i93 unless the source is also
8318   // strange.
8319   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8320        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8321       CanEvaluateInDifferentType(SrcI, DestTy,
8322                                  CI.getOpcode(), NumCastsRemoved)) {
8323     // If this cast is a truncate, evaluting in a different type always
8324     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8325     // we need to do an AND to maintain the clear top-part of the computation,
8326     // so we require that the input have eliminated at least one cast.  If this
8327     // is a sign extension, we insert two new casts (to do the extension) so we
8328     // require that two casts have been eliminated.
8329     bool DoXForm = false;
8330     bool JustReplace = false;
8331     switch (CI.getOpcode()) {
8332     default:
8333       // All the others use floating point so we shouldn't actually 
8334       // get here because of the check above.
8335       llvm_unreachable("Unknown cast type");
8336     case Instruction::Trunc:
8337       DoXForm = true;
8338       break;
8339     case Instruction::ZExt: {
8340       DoXForm = NumCastsRemoved >= 1;
8341       if (!DoXForm && 0) {
8342         // If it's unnecessary to issue an AND to clear the high bits, it's
8343         // always profitable to do this xform.
8344         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8345         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8346         if (MaskedValueIsZero(TryRes, Mask))
8347           return ReplaceInstUsesWith(CI, TryRes);
8348         
8349         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8350           if (TryI->use_empty())
8351             EraseInstFromFunction(*TryI);
8352       }
8353       break;
8354     }
8355     case Instruction::SExt: {
8356       DoXForm = NumCastsRemoved >= 2;
8357       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8358         // If we do not have to emit the truncate + sext pair, then it's always
8359         // profitable to do this xform.
8360         //
8361         // It's not safe to eliminate the trunc + sext pair if one of the
8362         // eliminated cast is a truncate. e.g.
8363         // t2 = trunc i32 t1 to i16
8364         // t3 = sext i16 t2 to i32
8365         // !=
8366         // i32 t1
8367         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8368         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8369         if (NumSignBits > (DestBitSize - SrcBitSize))
8370           return ReplaceInstUsesWith(CI, TryRes);
8371         
8372         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8373           if (TryI->use_empty())
8374             EraseInstFromFunction(*TryI);
8375       }
8376       break;
8377     }
8378     }
8379     
8380     if (DoXForm) {
8381       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8382            << " cast: " << CI;
8383       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8384                                            CI.getOpcode() == Instruction::SExt);
8385       if (JustReplace)
8386         // Just replace this cast with the result.
8387         return ReplaceInstUsesWith(CI, Res);
8388
8389       assert(Res->getType() == DestTy);
8390       switch (CI.getOpcode()) {
8391       default: llvm_unreachable("Unknown cast type!");
8392       case Instruction::Trunc:
8393         // Just replace this cast with the result.
8394         return ReplaceInstUsesWith(CI, Res);
8395       case Instruction::ZExt: {
8396         assert(SrcBitSize < DestBitSize && "Not a zext?");
8397
8398         // If the high bits are already zero, just replace this cast with the
8399         // result.
8400         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8401         if (MaskedValueIsZero(Res, Mask))
8402           return ReplaceInstUsesWith(CI, Res);
8403
8404         // We need to emit an AND to clear the high bits.
8405         Constant *C = ConstantInt::get(*Context, 
8406                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8407         return BinaryOperator::CreateAnd(Res, C);
8408       }
8409       case Instruction::SExt: {
8410         // If the high bits are already filled with sign bit, just replace this
8411         // cast with the result.
8412         unsigned NumSignBits = ComputeNumSignBits(Res);
8413         if (NumSignBits > (DestBitSize - SrcBitSize))
8414           return ReplaceInstUsesWith(CI, Res);
8415
8416         // We need to emit a cast to truncate, then a cast to sext.
8417         return CastInst::Create(Instruction::SExt,
8418             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8419                              CI), DestTy);
8420       }
8421       }
8422     }
8423   }
8424   
8425   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8426   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8427
8428   switch (SrcI->getOpcode()) {
8429   case Instruction::Add:
8430   case Instruction::Mul:
8431   case Instruction::And:
8432   case Instruction::Or:
8433   case Instruction::Xor:
8434     // If we are discarding information, rewrite.
8435     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8436       // Don't insert two casts unless at least one can be eliminated.
8437       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8438           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8439         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8440         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8441         return BinaryOperator::Create(
8442             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8443       }
8444     }
8445
8446     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8447     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8448         SrcI->getOpcode() == Instruction::Xor &&
8449         Op1 == ConstantInt::getTrue(*Context) &&
8450         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8451       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8452       return BinaryOperator::CreateXor(New,
8453                                       ConstantInt::get(CI.getType(), 1));
8454     }
8455     break;
8456
8457   case Instruction::Shl: {
8458     // Canonicalize trunc inside shl, if we can.
8459     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8460     if (CI && DestBitSize < SrcBitSize &&
8461         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8462       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8463       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8464       return BinaryOperator::CreateShl(Op0c, Op1c);
8465     }
8466     break;
8467   }
8468   }
8469   return 0;
8470 }
8471
8472 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8473   if (Instruction *Result = commonIntCastTransforms(CI))
8474     return Result;
8475   
8476   Value *Src = CI.getOperand(0);
8477   const Type *Ty = CI.getType();
8478   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8479   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8480
8481   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8482   if (DestBitWidth == 1) {
8483     Constant *One = ConstantInt::get(Src->getType(), 1);
8484     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8485     Value *Zero = Constant::getNullValue(Src->getType());
8486     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8487   }
8488
8489   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8490   ConstantInt *ShAmtV = 0;
8491   Value *ShiftOp = 0;
8492   if (Src->hasOneUse() &&
8493       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8494     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8495     
8496     // Get a mask for the bits shifting in.
8497     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8498     if (MaskedValueIsZero(ShiftOp, Mask)) {
8499       if (ShAmt >= DestBitWidth)        // All zeros.
8500         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8501       
8502       // Okay, we can shrink this.  Truncate the input, then return a new
8503       // shift.
8504       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8505       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8506       return BinaryOperator::CreateLShr(V1, V2);
8507     }
8508   }
8509   
8510   return 0;
8511 }
8512
8513 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8514 /// in order to eliminate the icmp.
8515 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8516                                              bool DoXform) {
8517   // If we are just checking for a icmp eq of a single bit and zext'ing it
8518   // to an integer, then shift the bit to the appropriate place and then
8519   // cast to integer to avoid the comparison.
8520   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8521     const APInt &Op1CV = Op1C->getValue();
8522       
8523     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8524     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8525     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8526         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8527       if (!DoXform) return ICI;
8528
8529       Value *In = ICI->getOperand(0);
8530       Value *Sh = ConstantInt::get(In->getType(),
8531                                    In->getType()->getScalarSizeInBits()-1);
8532       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8533                                                         In->getName()+".lobit"),
8534                                CI);
8535       if (In->getType() != CI.getType())
8536         In = CastInst::CreateIntegerCast(In, CI.getType(),
8537                                          false/*ZExt*/, "tmp", &CI);
8538
8539       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8540         Constant *One = ConstantInt::get(In->getType(), 1);
8541         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8542                                                          In->getName()+".not"),
8543                                  CI);
8544       }
8545
8546       return ReplaceInstUsesWith(CI, In);
8547     }
8548       
8549       
8550       
8551     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8552     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8553     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8554     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8555     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8556     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8557     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8558     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8559     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8560         // This only works for EQ and NE
8561         ICI->isEquality()) {
8562       // If Op1C some other power of two, convert:
8563       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8564       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8565       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8566       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8567         
8568       APInt KnownZeroMask(~KnownZero);
8569       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8570         if (!DoXform) return ICI;
8571
8572         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8573         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8574           // (X&4) == 2 --> false
8575           // (X&4) != 2 --> true
8576           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8577           Res = ConstantExpr::getZExt(Res, CI.getType());
8578           return ReplaceInstUsesWith(CI, Res);
8579         }
8580           
8581         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8582         Value *In = ICI->getOperand(0);
8583         if (ShiftAmt) {
8584           // Perform a logical shr by shiftamt.
8585           // Insert the shift to put the result in the low bit.
8586           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8587                               ConstantInt::get(In->getType(), ShiftAmt),
8588                                                    In->getName()+".lobit"), CI);
8589         }
8590           
8591         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8592           Constant *One = ConstantInt::get(In->getType(), 1);
8593           In = BinaryOperator::CreateXor(In, One, "tmp");
8594           InsertNewInstBefore(cast<Instruction>(In), CI);
8595         }
8596           
8597         if (CI.getType() == In->getType())
8598           return ReplaceInstUsesWith(CI, In);
8599         else
8600           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8601       }
8602     }
8603   }
8604
8605   return 0;
8606 }
8607
8608 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8609   // If one of the common conversion will work ..
8610   if (Instruction *Result = commonIntCastTransforms(CI))
8611     return Result;
8612
8613   Value *Src = CI.getOperand(0);
8614
8615   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8616   // types and if the sizes are just right we can convert this into a logical
8617   // 'and' which will be much cheaper than the pair of casts.
8618   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8619     // Get the sizes of the types involved.  We know that the intermediate type
8620     // will be smaller than A or C, but don't know the relation between A and C.
8621     Value *A = CSrc->getOperand(0);
8622     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8623     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8624     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8625     // If we're actually extending zero bits, then if
8626     // SrcSize <  DstSize: zext(a & mask)
8627     // SrcSize == DstSize: a & mask
8628     // SrcSize  > DstSize: trunc(a) & mask
8629     if (SrcSize < DstSize) {
8630       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8631       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8632       Instruction *And =
8633         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8634       InsertNewInstBefore(And, CI);
8635       return new ZExtInst(And, CI.getType());
8636     } else if (SrcSize == DstSize) {
8637       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8638       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8639                                                            AndValue));
8640     } else if (SrcSize > DstSize) {
8641       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8642       InsertNewInstBefore(Trunc, CI);
8643       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8644       return BinaryOperator::CreateAnd(Trunc, 
8645                                        ConstantInt::get(Trunc->getType(),
8646                                                                AndValue));
8647     }
8648   }
8649
8650   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8651     return transformZExtICmp(ICI, CI);
8652
8653   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8654   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8655     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8656     // of the (zext icmp) will be transformed.
8657     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8658     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8659     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8660         (transformZExtICmp(LHS, CI, false) ||
8661          transformZExtICmp(RHS, CI, false))) {
8662       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8663       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8664       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8665     }
8666   }
8667
8668   // zext(trunc(t) & C) -> (t & zext(C)).
8669   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8670     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8671       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8672         Value *TI0 = TI->getOperand(0);
8673         if (TI0->getType() == CI.getType())
8674           return
8675             BinaryOperator::CreateAnd(TI0,
8676                                 ConstantExpr::getZExt(C, CI.getType()));
8677       }
8678
8679   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8680   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8681     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8682       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8683         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8684             And->getOperand(1) == C)
8685           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8686             Value *TI0 = TI->getOperand(0);
8687             if (TI0->getType() == CI.getType()) {
8688               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8689               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8690               InsertNewInstBefore(NewAnd, *And);
8691               return BinaryOperator::CreateXor(NewAnd, ZC);
8692             }
8693           }
8694
8695   return 0;
8696 }
8697
8698 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8699   if (Instruction *I = commonIntCastTransforms(CI))
8700     return I;
8701   
8702   Value *Src = CI.getOperand(0);
8703   
8704   // Canonicalize sign-extend from i1 to a select.
8705   if (Src->getType() == Type::Int1Ty)
8706     return SelectInst::Create(Src,
8707                               Constant::getAllOnesValue(CI.getType()),
8708                               Constant::getNullValue(CI.getType()));
8709
8710   // See if the value being truncated is already sign extended.  If so, just
8711   // eliminate the trunc/sext pair.
8712   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8713     Value *Op = cast<User>(Src)->getOperand(0);
8714     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8715     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8716     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8717     unsigned NumSignBits = ComputeNumSignBits(Op);
8718
8719     if (OpBits == DestBits) {
8720       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8721       // bits, it is already ready.
8722       if (NumSignBits > DestBits-MidBits)
8723         return ReplaceInstUsesWith(CI, Op);
8724     } else if (OpBits < DestBits) {
8725       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8726       // bits, just sext from i32.
8727       if (NumSignBits > OpBits-MidBits)
8728         return new SExtInst(Op, CI.getType(), "tmp");
8729     } else {
8730       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8731       // bits, just truncate to i32.
8732       if (NumSignBits > OpBits-MidBits)
8733         return new TruncInst(Op, CI.getType(), "tmp");
8734     }
8735   }
8736
8737   // If the input is a shl/ashr pair of a same constant, then this is a sign
8738   // extension from a smaller value.  If we could trust arbitrary bitwidth
8739   // integers, we could turn this into a truncate to the smaller bit and then
8740   // use a sext for the whole extension.  Since we don't, look deeper and check
8741   // for a truncate.  If the source and dest are the same type, eliminate the
8742   // trunc and extend and just do shifts.  For example, turn:
8743   //   %a = trunc i32 %i to i8
8744   //   %b = shl i8 %a, 6
8745   //   %c = ashr i8 %b, 6
8746   //   %d = sext i8 %c to i32
8747   // into:
8748   //   %a = shl i32 %i, 30
8749   //   %d = ashr i32 %a, 30
8750   Value *A = 0;
8751   ConstantInt *BA = 0, *CA = 0;
8752   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8753                         m_ConstantInt(CA)), *Context) &&
8754       BA == CA && isa<TruncInst>(A)) {
8755     Value *I = cast<TruncInst>(A)->getOperand(0);
8756     if (I->getType() == CI.getType()) {
8757       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8758       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8759       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8760       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8761       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8762                                                         CI.getName()), CI);
8763       return BinaryOperator::CreateAShr(I, ShAmtV);
8764     }
8765   }
8766   
8767   return 0;
8768 }
8769
8770 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8771 /// in the specified FP type without changing its value.
8772 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8773                               LLVMContext *Context) {
8774   bool losesInfo;
8775   APFloat F = CFP->getValueAPF();
8776   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8777   if (!losesInfo)
8778     return ConstantFP::get(*Context, F);
8779   return 0;
8780 }
8781
8782 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8783 /// through it until we get the source value.
8784 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8785   if (Instruction *I = dyn_cast<Instruction>(V))
8786     if (I->getOpcode() == Instruction::FPExt)
8787       return LookThroughFPExtensions(I->getOperand(0), Context);
8788   
8789   // If this value is a constant, return the constant in the smallest FP type
8790   // that can accurately represent it.  This allows us to turn
8791   // (float)((double)X+2.0) into x+2.0f.
8792   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8793     if (CFP->getType() == Type::PPC_FP128Ty)
8794       return V;  // No constant folding of this.
8795     // See if the value can be truncated to float and then reextended.
8796     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8797       return V;
8798     if (CFP->getType() == Type::DoubleTy)
8799       return V;  // Won't shrink.
8800     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8801       return V;
8802     // Don't try to shrink to various long double types.
8803   }
8804   
8805   return V;
8806 }
8807
8808 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8809   if (Instruction *I = commonCastTransforms(CI))
8810     return I;
8811   
8812   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8813   // smaller than the destination type, we can eliminate the truncate by doing
8814   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8815   // many builtins (sqrt, etc).
8816   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8817   if (OpI && OpI->hasOneUse()) {
8818     switch (OpI->getOpcode()) {
8819     default: break;
8820     case Instruction::FAdd:
8821     case Instruction::FSub:
8822     case Instruction::FMul:
8823     case Instruction::FDiv:
8824     case Instruction::FRem:
8825       const Type *SrcTy = OpI->getType();
8826       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8827       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8828       if (LHSTrunc->getType() != SrcTy && 
8829           RHSTrunc->getType() != SrcTy) {
8830         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8831         // If the source types were both smaller than the destination type of
8832         // the cast, do this xform.
8833         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8834             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8835           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8836                                       CI.getType(), CI);
8837           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8838                                       CI.getType(), CI);
8839           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8840         }
8841       }
8842       break;  
8843     }
8844   }
8845   return 0;
8846 }
8847
8848 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8849   return commonCastTransforms(CI);
8850 }
8851
8852 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8853   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8854   if (OpI == 0)
8855     return commonCastTransforms(FI);
8856
8857   // fptoui(uitofp(X)) --> X
8858   // fptoui(sitofp(X)) --> X
8859   // This is safe if the intermediate type has enough bits in its mantissa to
8860   // accurately represent all values of X.  For example, do not do this with
8861   // i64->float->i64.  This is also safe for sitofp case, because any negative
8862   // 'X' value would cause an undefined result for the fptoui. 
8863   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8864       OpI->getOperand(0)->getType() == FI.getType() &&
8865       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8866                     OpI->getType()->getFPMantissaWidth())
8867     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8868
8869   return commonCastTransforms(FI);
8870 }
8871
8872 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8873   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8874   if (OpI == 0)
8875     return commonCastTransforms(FI);
8876   
8877   // fptosi(sitofp(X)) --> X
8878   // fptosi(uitofp(X)) --> X
8879   // This is safe if the intermediate type has enough bits in its mantissa to
8880   // accurately represent all values of X.  For example, do not do this with
8881   // i64->float->i64.  This is also safe for sitofp case, because any negative
8882   // 'X' value would cause an undefined result for the fptoui. 
8883   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8884       OpI->getOperand(0)->getType() == FI.getType() &&
8885       (int)FI.getType()->getScalarSizeInBits() <=
8886                     OpI->getType()->getFPMantissaWidth())
8887     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8888   
8889   return commonCastTransforms(FI);
8890 }
8891
8892 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8893   return commonCastTransforms(CI);
8894 }
8895
8896 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8897   return commonCastTransforms(CI);
8898 }
8899
8900 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8901   // If the destination integer type is smaller than the intptr_t type for
8902   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8903   // trunc to be exposed to other transforms.  Don't do this for extending
8904   // ptrtoint's, because we don't know if the target sign or zero extends its
8905   // pointers.
8906   if (TD &&
8907       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8908     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8909                                                     TD->getIntPtrType(),
8910                                                     "tmp"), CI);
8911     return new TruncInst(P, CI.getType());
8912   }
8913   
8914   return commonPointerCastTransforms(CI);
8915 }
8916
8917 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8918   // If the source integer type is larger than the intptr_t type for
8919   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8920   // allows the trunc to be exposed to other transforms.  Don't do this for
8921   // extending inttoptr's, because we don't know if the target sign or zero
8922   // extends to pointers.
8923   if (TD &&
8924       CI.getOperand(0)->getType()->getScalarSizeInBits() >
8925       TD->getPointerSizeInBits()) {
8926     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8927                                                  TD->getIntPtrType(),
8928                                                  "tmp"), CI);
8929     return new IntToPtrInst(P, CI.getType());
8930   }
8931   
8932   if (Instruction *I = commonCastTransforms(CI))
8933     return I;
8934
8935   return 0;
8936 }
8937
8938 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8939   // If the operands are integer typed then apply the integer transforms,
8940   // otherwise just apply the common ones.
8941   Value *Src = CI.getOperand(0);
8942   const Type *SrcTy = Src->getType();
8943   const Type *DestTy = CI.getType();
8944
8945   if (isa<PointerType>(SrcTy)) {
8946     if (Instruction *I = commonPointerCastTransforms(CI))
8947       return I;
8948   } else {
8949     if (Instruction *Result = commonCastTransforms(CI))
8950       return Result;
8951   }
8952
8953
8954   // Get rid of casts from one type to the same type. These are useless and can
8955   // be replaced by the operand.
8956   if (DestTy == Src->getType())
8957     return ReplaceInstUsesWith(CI, Src);
8958
8959   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8960     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8961     const Type *DstElTy = DstPTy->getElementType();
8962     const Type *SrcElTy = SrcPTy->getElementType();
8963     
8964     // If the address spaces don't match, don't eliminate the bitcast, which is
8965     // required for changing types.
8966     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8967       return 0;
8968     
8969     // If we are casting a malloc or alloca to a pointer to a type of the same
8970     // size, rewrite the allocation instruction to allocate the "right" type.
8971     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8972       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8973         return V;
8974     
8975     // If the source and destination are pointers, and this cast is equivalent
8976     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8977     // This can enhance SROA and other transforms that want type-safe pointers.
8978     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8979     unsigned NumZeros = 0;
8980     while (SrcElTy != DstElTy && 
8981            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8982            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8983       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8984       ++NumZeros;
8985     }
8986
8987     // If we found a path from the src to dest, create the getelementptr now.
8988     if (SrcElTy == DstElTy) {
8989       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8990       Instruction *GEP = GetElementPtrInst::Create(Src,
8991                                                    Idxs.begin(), Idxs.end(), "",
8992                                                    ((Instruction*) NULL));
8993       cast<GEPOperator>(GEP)->setIsInBounds(true);
8994       return GEP;
8995     }
8996   }
8997
8998   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8999     if (DestVTy->getNumElements() == 1) {
9000       if (!isa<VectorType>(SrcTy)) {
9001         Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9002                                        DestVTy->getElementType(), CI);
9003         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9004                                          Constant::getNullValue(Type::Int32Ty));
9005       }
9006       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9007     }
9008   }
9009
9010   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9011     if (SrcVTy->getNumElements() == 1) {
9012       if (!isa<VectorType>(DestTy)) {
9013         Instruction *Elem =
9014           ExtractElementInst::Create(Src, Constant::getNullValue(Type::Int32Ty));
9015         InsertNewInstBefore(Elem, CI);
9016         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9017       }
9018     }
9019   }
9020
9021   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9022     if (SVI->hasOneUse()) {
9023       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9024       // a bitconvert to a vector with the same # elts.
9025       if (isa<VectorType>(DestTy) && 
9026           cast<VectorType>(DestTy)->getNumElements() ==
9027                 SVI->getType()->getNumElements() &&
9028           SVI->getType()->getNumElements() ==
9029             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9030         CastInst *Tmp;
9031         // If either of the operands is a cast from CI.getType(), then
9032         // evaluating the shuffle in the casted destination's type will allow
9033         // us to eliminate at least one cast.
9034         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9035              Tmp->getOperand(0)->getType() == DestTy) ||
9036             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9037              Tmp->getOperand(0)->getType() == DestTy)) {
9038           Value *LHS = InsertCastBefore(Instruction::BitCast,
9039                                         SVI->getOperand(0), DestTy, CI);
9040           Value *RHS = InsertCastBefore(Instruction::BitCast,
9041                                         SVI->getOperand(1), DestTy, CI);
9042           // Return a new shuffle vector.  Use the same element ID's, as we
9043           // know the vector types match #elts.
9044           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9045         }
9046       }
9047     }
9048   }
9049   return 0;
9050 }
9051
9052 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9053 ///   %C = or %A, %B
9054 ///   %D = select %cond, %C, %A
9055 /// into:
9056 ///   %C = select %cond, %B, 0
9057 ///   %D = or %A, %C
9058 ///
9059 /// Assuming that the specified instruction is an operand to the select, return
9060 /// a bitmask indicating which operands of this instruction are foldable if they
9061 /// equal the other incoming value of the select.
9062 ///
9063 static unsigned GetSelectFoldableOperands(Instruction *I) {
9064   switch (I->getOpcode()) {
9065   case Instruction::Add:
9066   case Instruction::Mul:
9067   case Instruction::And:
9068   case Instruction::Or:
9069   case Instruction::Xor:
9070     return 3;              // Can fold through either operand.
9071   case Instruction::Sub:   // Can only fold on the amount subtracted.
9072   case Instruction::Shl:   // Can only fold on the shift amount.
9073   case Instruction::LShr:
9074   case Instruction::AShr:
9075     return 1;
9076   default:
9077     return 0;              // Cannot fold
9078   }
9079 }
9080
9081 /// GetSelectFoldableConstant - For the same transformation as the previous
9082 /// function, return the identity constant that goes into the select.
9083 static Constant *GetSelectFoldableConstant(Instruction *I,
9084                                            LLVMContext *Context) {
9085   switch (I->getOpcode()) {
9086   default: llvm_unreachable("This cannot happen!");
9087   case Instruction::Add:
9088   case Instruction::Sub:
9089   case Instruction::Or:
9090   case Instruction::Xor:
9091   case Instruction::Shl:
9092   case Instruction::LShr:
9093   case Instruction::AShr:
9094     return Constant::getNullValue(I->getType());
9095   case Instruction::And:
9096     return Constant::getAllOnesValue(I->getType());
9097   case Instruction::Mul:
9098     return ConstantInt::get(I->getType(), 1);
9099   }
9100 }
9101
9102 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9103 /// have the same opcode and only one use each.  Try to simplify this.
9104 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9105                                           Instruction *FI) {
9106   if (TI->getNumOperands() == 1) {
9107     // If this is a non-volatile load or a cast from the same type,
9108     // merge.
9109     if (TI->isCast()) {
9110       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9111         return 0;
9112     } else {
9113       return 0;  // unknown unary op.
9114     }
9115
9116     // Fold this by inserting a select from the input values.
9117     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9118                                           FI->getOperand(0), SI.getName()+".v");
9119     InsertNewInstBefore(NewSI, SI);
9120     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9121                             TI->getType());
9122   }
9123
9124   // Only handle binary operators here.
9125   if (!isa<BinaryOperator>(TI))
9126     return 0;
9127
9128   // Figure out if the operations have any operands in common.
9129   Value *MatchOp, *OtherOpT, *OtherOpF;
9130   bool MatchIsOpZero;
9131   if (TI->getOperand(0) == FI->getOperand(0)) {
9132     MatchOp  = TI->getOperand(0);
9133     OtherOpT = TI->getOperand(1);
9134     OtherOpF = FI->getOperand(1);
9135     MatchIsOpZero = true;
9136   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9137     MatchOp  = TI->getOperand(1);
9138     OtherOpT = TI->getOperand(0);
9139     OtherOpF = FI->getOperand(0);
9140     MatchIsOpZero = false;
9141   } else if (!TI->isCommutative()) {
9142     return 0;
9143   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9144     MatchOp  = TI->getOperand(0);
9145     OtherOpT = TI->getOperand(1);
9146     OtherOpF = FI->getOperand(0);
9147     MatchIsOpZero = true;
9148   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9149     MatchOp  = TI->getOperand(1);
9150     OtherOpT = TI->getOperand(0);
9151     OtherOpF = FI->getOperand(1);
9152     MatchIsOpZero = true;
9153   } else {
9154     return 0;
9155   }
9156
9157   // If we reach here, they do have operations in common.
9158   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9159                                          OtherOpF, SI.getName()+".v");
9160   InsertNewInstBefore(NewSI, SI);
9161
9162   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9163     if (MatchIsOpZero)
9164       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9165     else
9166       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9167   }
9168   llvm_unreachable("Shouldn't get here");
9169   return 0;
9170 }
9171
9172 static bool isSelect01(Constant *C1, Constant *C2) {
9173   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9174   if (!C1I)
9175     return false;
9176   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9177   if (!C2I)
9178     return false;
9179   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9180 }
9181
9182 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9183 /// facilitate further optimization.
9184 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9185                                             Value *FalseVal) {
9186   // See the comment above GetSelectFoldableOperands for a description of the
9187   // transformation we are doing here.
9188   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9189     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9190         !isa<Constant>(FalseVal)) {
9191       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9192         unsigned OpToFold = 0;
9193         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9194           OpToFold = 1;
9195         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9196           OpToFold = 2;
9197         }
9198
9199         if (OpToFold) {
9200           Constant *C = GetSelectFoldableConstant(TVI, Context);
9201           Value *OOp = TVI->getOperand(2-OpToFold);
9202           // Avoid creating select between 2 constants unless it's selecting
9203           // between 0 and 1.
9204           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9205             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9206             InsertNewInstBefore(NewSel, SI);
9207             NewSel->takeName(TVI);
9208             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9209               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9210             llvm_unreachable("Unknown instruction!!");
9211           }
9212         }
9213       }
9214     }
9215   }
9216
9217   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9218     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9219         !isa<Constant>(TrueVal)) {
9220       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9221         unsigned OpToFold = 0;
9222         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9223           OpToFold = 1;
9224         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9225           OpToFold = 2;
9226         }
9227
9228         if (OpToFold) {
9229           Constant *C = GetSelectFoldableConstant(FVI, Context);
9230           Value *OOp = FVI->getOperand(2-OpToFold);
9231           // Avoid creating select between 2 constants unless it's selecting
9232           // between 0 and 1.
9233           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9234             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9235             InsertNewInstBefore(NewSel, SI);
9236             NewSel->takeName(FVI);
9237             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9238               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9239             llvm_unreachable("Unknown instruction!!");
9240           }
9241         }
9242       }
9243     }
9244   }
9245
9246   return 0;
9247 }
9248
9249 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9250 /// ICmpInst as its first operand.
9251 ///
9252 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9253                                                    ICmpInst *ICI) {
9254   bool Changed = false;
9255   ICmpInst::Predicate Pred = ICI->getPredicate();
9256   Value *CmpLHS = ICI->getOperand(0);
9257   Value *CmpRHS = ICI->getOperand(1);
9258   Value *TrueVal = SI.getTrueValue();
9259   Value *FalseVal = SI.getFalseValue();
9260
9261   // Check cases where the comparison is with a constant that
9262   // can be adjusted to fit the min/max idiom. We may edit ICI in
9263   // place here, so make sure the select is the only user.
9264   if (ICI->hasOneUse())
9265     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9266       switch (Pred) {
9267       default: break;
9268       case ICmpInst::ICMP_ULT:
9269       case ICmpInst::ICMP_SLT: {
9270         // X < MIN ? T : F  -->  F
9271         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9272           return ReplaceInstUsesWith(SI, FalseVal);
9273         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9274         Constant *AdjustedRHS = SubOne(CI, Context);
9275         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9276             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9277           Pred = ICmpInst::getSwappedPredicate(Pred);
9278           CmpRHS = AdjustedRHS;
9279           std::swap(FalseVal, TrueVal);
9280           ICI->setPredicate(Pred);
9281           ICI->setOperand(1, CmpRHS);
9282           SI.setOperand(1, TrueVal);
9283           SI.setOperand(2, FalseVal);
9284           Changed = true;
9285         }
9286         break;
9287       }
9288       case ICmpInst::ICMP_UGT:
9289       case ICmpInst::ICMP_SGT: {
9290         // X > MAX ? T : F  -->  F
9291         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9292           return ReplaceInstUsesWith(SI, FalseVal);
9293         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9294         Constant *AdjustedRHS = AddOne(CI, Context);
9295         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9296             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9297           Pred = ICmpInst::getSwappedPredicate(Pred);
9298           CmpRHS = AdjustedRHS;
9299           std::swap(FalseVal, TrueVal);
9300           ICI->setPredicate(Pred);
9301           ICI->setOperand(1, CmpRHS);
9302           SI.setOperand(1, TrueVal);
9303           SI.setOperand(2, FalseVal);
9304           Changed = true;
9305         }
9306         break;
9307       }
9308       }
9309
9310       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9311       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9312       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9313       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9314           match(FalseVal, m_ConstantInt<0>(), *Context))
9315         Pred = ICI->getPredicate();
9316       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9317                match(FalseVal, m_ConstantInt<-1>(), *Context))
9318         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9319       
9320       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9321         // If we are just checking for a icmp eq of a single bit and zext'ing it
9322         // to an integer, then shift the bit to the appropriate place and then
9323         // cast to integer to avoid the comparison.
9324         const APInt &Op1CV = CI->getValue();
9325     
9326         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9327         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9328         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9329             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9330           Value *In = ICI->getOperand(0);
9331           Value *Sh = ConstantInt::get(In->getType(),
9332                                        In->getType()->getScalarSizeInBits()-1);
9333           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9334                                                         In->getName()+".lobit"),
9335                                    *ICI);
9336           if (In->getType() != SI.getType())
9337             In = CastInst::CreateIntegerCast(In, SI.getType(),
9338                                              true/*SExt*/, "tmp", ICI);
9339     
9340           if (Pred == ICmpInst::ICMP_SGT)
9341             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9342                                        In->getName()+".not"), *ICI);
9343     
9344           return ReplaceInstUsesWith(SI, In);
9345         }
9346       }
9347     }
9348
9349   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9350     // Transform (X == Y) ? X : Y  -> Y
9351     if (Pred == ICmpInst::ICMP_EQ)
9352       return ReplaceInstUsesWith(SI, FalseVal);
9353     // Transform (X != Y) ? X : Y  -> X
9354     if (Pred == ICmpInst::ICMP_NE)
9355       return ReplaceInstUsesWith(SI, TrueVal);
9356     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9357
9358   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9359     // Transform (X == Y) ? Y : X  -> X
9360     if (Pred == ICmpInst::ICMP_EQ)
9361       return ReplaceInstUsesWith(SI, FalseVal);
9362     // Transform (X != Y) ? Y : X  -> Y
9363     if (Pred == ICmpInst::ICMP_NE)
9364       return ReplaceInstUsesWith(SI, TrueVal);
9365     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9366   }
9367
9368   /// NOTE: if we wanted to, this is where to detect integer ABS
9369
9370   return Changed ? &SI : 0;
9371 }
9372
9373 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9374   Value *CondVal = SI.getCondition();
9375   Value *TrueVal = SI.getTrueValue();
9376   Value *FalseVal = SI.getFalseValue();
9377
9378   // select true, X, Y  -> X
9379   // select false, X, Y -> Y
9380   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9381     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9382
9383   // select C, X, X -> X
9384   if (TrueVal == FalseVal)
9385     return ReplaceInstUsesWith(SI, TrueVal);
9386
9387   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9388     return ReplaceInstUsesWith(SI, FalseVal);
9389   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9390     return ReplaceInstUsesWith(SI, TrueVal);
9391   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9392     if (isa<Constant>(TrueVal))
9393       return ReplaceInstUsesWith(SI, TrueVal);
9394     else
9395       return ReplaceInstUsesWith(SI, FalseVal);
9396   }
9397
9398   if (SI.getType() == Type::Int1Ty) {
9399     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9400       if (C->getZExtValue()) {
9401         // Change: A = select B, true, C --> A = or B, C
9402         return BinaryOperator::CreateOr(CondVal, FalseVal);
9403       } else {
9404         // Change: A = select B, false, C --> A = and !B, C
9405         Value *NotCond =
9406           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9407                                              "not."+CondVal->getName()), SI);
9408         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9409       }
9410     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9411       if (C->getZExtValue() == false) {
9412         // Change: A = select B, C, false --> A = and B, C
9413         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9414       } else {
9415         // Change: A = select B, C, true --> A = or !B, C
9416         Value *NotCond =
9417           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9418                                              "not."+CondVal->getName()), SI);
9419         return BinaryOperator::CreateOr(NotCond, TrueVal);
9420       }
9421     }
9422     
9423     // select a, b, a  -> a&b
9424     // select a, a, b  -> a|b
9425     if (CondVal == TrueVal)
9426       return BinaryOperator::CreateOr(CondVal, FalseVal);
9427     else if (CondVal == FalseVal)
9428       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9429   }
9430
9431   // Selecting between two integer constants?
9432   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9433     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9434       // select C, 1, 0 -> zext C to int
9435       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9436         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9437       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9438         // select C, 0, 1 -> zext !C to int
9439         Value *NotCond =
9440           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9441                                                "not."+CondVal->getName()), SI);
9442         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9443       }
9444
9445       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9446         // If one of the constants is zero (we know they can't both be) and we
9447         // have an icmp instruction with zero, and we have an 'and' with the
9448         // non-constant value, eliminate this whole mess.  This corresponds to
9449         // cases like this: ((X & 27) ? 27 : 0)
9450         if (TrueValC->isZero() || FalseValC->isZero())
9451           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9452               cast<Constant>(IC->getOperand(1))->isNullValue())
9453             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9454               if (ICA->getOpcode() == Instruction::And &&
9455                   isa<ConstantInt>(ICA->getOperand(1)) &&
9456                   (ICA->getOperand(1) == TrueValC ||
9457                    ICA->getOperand(1) == FalseValC) &&
9458                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9459                 // Okay, now we know that everything is set up, we just don't
9460                 // know whether we have a icmp_ne or icmp_eq and whether the 
9461                 // true or false val is the zero.
9462                 bool ShouldNotVal = !TrueValC->isZero();
9463                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9464                 Value *V = ICA;
9465                 if (ShouldNotVal)
9466                   V = InsertNewInstBefore(BinaryOperator::Create(
9467                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9468                 return ReplaceInstUsesWith(SI, V);
9469               }
9470       }
9471     }
9472
9473   // See if we are selecting two values based on a comparison of the two values.
9474   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9475     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9476       // Transform (X == Y) ? X : Y  -> Y
9477       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9478         // This is not safe in general for floating point:  
9479         // consider X== -0, Y== +0.
9480         // It becomes safe if either operand is a nonzero constant.
9481         ConstantFP *CFPt, *CFPf;
9482         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9483               !CFPt->getValueAPF().isZero()) ||
9484             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9485              !CFPf->getValueAPF().isZero()))
9486         return ReplaceInstUsesWith(SI, FalseVal);
9487       }
9488       // Transform (X != Y) ? X : Y  -> X
9489       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9490         return ReplaceInstUsesWith(SI, TrueVal);
9491       // NOTE: if we wanted to, this is where to detect MIN/MAX
9492
9493     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9494       // Transform (X == Y) ? Y : X  -> X
9495       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9496         // This is not safe in general for floating point:  
9497         // consider X== -0, Y== +0.
9498         // It becomes safe if either operand is a nonzero constant.
9499         ConstantFP *CFPt, *CFPf;
9500         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9501               !CFPt->getValueAPF().isZero()) ||
9502             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9503              !CFPf->getValueAPF().isZero()))
9504           return ReplaceInstUsesWith(SI, FalseVal);
9505       }
9506       // Transform (X != Y) ? Y : X  -> Y
9507       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9508         return ReplaceInstUsesWith(SI, TrueVal);
9509       // NOTE: if we wanted to, this is where to detect MIN/MAX
9510     }
9511     // NOTE: if we wanted to, this is where to detect ABS
9512   }
9513
9514   // See if we are selecting two values based on a comparison of the two values.
9515   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9516     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9517       return Result;
9518
9519   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9520     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9521       if (TI->hasOneUse() && FI->hasOneUse()) {
9522         Instruction *AddOp = 0, *SubOp = 0;
9523
9524         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9525         if (TI->getOpcode() == FI->getOpcode())
9526           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9527             return IV;
9528
9529         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9530         // even legal for FP.
9531         if ((TI->getOpcode() == Instruction::Sub &&
9532              FI->getOpcode() == Instruction::Add) ||
9533             (TI->getOpcode() == Instruction::FSub &&
9534              FI->getOpcode() == Instruction::FAdd)) {
9535           AddOp = FI; SubOp = TI;
9536         } else if ((FI->getOpcode() == Instruction::Sub &&
9537                     TI->getOpcode() == Instruction::Add) ||
9538                    (FI->getOpcode() == Instruction::FSub &&
9539                     TI->getOpcode() == Instruction::FAdd)) {
9540           AddOp = TI; SubOp = FI;
9541         }
9542
9543         if (AddOp) {
9544           Value *OtherAddOp = 0;
9545           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9546             OtherAddOp = AddOp->getOperand(1);
9547           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9548             OtherAddOp = AddOp->getOperand(0);
9549           }
9550
9551           if (OtherAddOp) {
9552             // So at this point we know we have (Y -> OtherAddOp):
9553             //        select C, (add X, Y), (sub X, Z)
9554             Value *NegVal;  // Compute -Z
9555             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9556               NegVal = ConstantExpr::getNeg(C);
9557             } else {
9558               NegVal = InsertNewInstBefore(
9559                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9560                                               "tmp"), SI);
9561             }
9562
9563             Value *NewTrueOp = OtherAddOp;
9564             Value *NewFalseOp = NegVal;
9565             if (AddOp != TI)
9566               std::swap(NewTrueOp, NewFalseOp);
9567             Instruction *NewSel =
9568               SelectInst::Create(CondVal, NewTrueOp,
9569                                  NewFalseOp, SI.getName() + ".p");
9570
9571             NewSel = InsertNewInstBefore(NewSel, SI);
9572             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9573           }
9574         }
9575       }
9576
9577   // See if we can fold the select into one of our operands.
9578   if (SI.getType()->isInteger()) {
9579     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9580     if (FoldI)
9581       return FoldI;
9582   }
9583
9584   if (BinaryOperator::isNot(CondVal)) {
9585     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9586     SI.setOperand(1, FalseVal);
9587     SI.setOperand(2, TrueVal);
9588     return &SI;
9589   }
9590
9591   return 0;
9592 }
9593
9594 /// EnforceKnownAlignment - If the specified pointer points to an object that
9595 /// we control, modify the object's alignment to PrefAlign. This isn't
9596 /// often possible though. If alignment is important, a more reliable approach
9597 /// is to simply align all global variables and allocation instructions to
9598 /// their preferred alignment from the beginning.
9599 ///
9600 static unsigned EnforceKnownAlignment(Value *V,
9601                                       unsigned Align, unsigned PrefAlign) {
9602
9603   User *U = dyn_cast<User>(V);
9604   if (!U) return Align;
9605
9606   switch (Operator::getOpcode(U)) {
9607   default: break;
9608   case Instruction::BitCast:
9609     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9610   case Instruction::GetElementPtr: {
9611     // If all indexes are zero, it is just the alignment of the base pointer.
9612     bool AllZeroOperands = true;
9613     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9614       if (!isa<Constant>(*i) ||
9615           !cast<Constant>(*i)->isNullValue()) {
9616         AllZeroOperands = false;
9617         break;
9618       }
9619
9620     if (AllZeroOperands) {
9621       // Treat this like a bitcast.
9622       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9623     }
9624     break;
9625   }
9626   }
9627
9628   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9629     // If there is a large requested alignment and we can, bump up the alignment
9630     // of the global.
9631     if (!GV->isDeclaration()) {
9632       if (GV->getAlignment() >= PrefAlign)
9633         Align = GV->getAlignment();
9634       else {
9635         GV->setAlignment(PrefAlign);
9636         Align = PrefAlign;
9637       }
9638     }
9639   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9640     // If there is a requested alignment and if this is an alloca, round up.  We
9641     // don't do this for malloc, because some systems can't respect the request.
9642     if (isa<AllocaInst>(AI)) {
9643       if (AI->getAlignment() >= PrefAlign)
9644         Align = AI->getAlignment();
9645       else {
9646         AI->setAlignment(PrefAlign);
9647         Align = PrefAlign;
9648       }
9649     }
9650   }
9651
9652   return Align;
9653 }
9654
9655 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9656 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9657 /// and it is more than the alignment of the ultimate object, see if we can
9658 /// increase the alignment of the ultimate object, making this check succeed.
9659 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9660                                                   unsigned PrefAlign) {
9661   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9662                       sizeof(PrefAlign) * CHAR_BIT;
9663   APInt Mask = APInt::getAllOnesValue(BitWidth);
9664   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9665   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9666   unsigned TrailZ = KnownZero.countTrailingOnes();
9667   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9668
9669   if (PrefAlign > Align)
9670     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9671   
9672     // We don't need to make any adjustment.
9673   return Align;
9674 }
9675
9676 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9677   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9678   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9679   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9680   unsigned CopyAlign = MI->getAlignment();
9681
9682   if (CopyAlign < MinAlign) {
9683     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9684                                              MinAlign, false));
9685     return MI;
9686   }
9687   
9688   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9689   // load/store.
9690   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9691   if (MemOpLength == 0) return 0;
9692   
9693   // Source and destination pointer types are always "i8*" for intrinsic.  See
9694   // if the size is something we can handle with a single primitive load/store.
9695   // A single load+store correctly handles overlapping memory in the memmove
9696   // case.
9697   unsigned Size = MemOpLength->getZExtValue();
9698   if (Size == 0) return MI;  // Delete this mem transfer.
9699   
9700   if (Size > 8 || (Size&(Size-1)))
9701     return 0;  // If not 1/2/4/8 bytes, exit.
9702   
9703   // Use an integer load+store unless we can find something better.
9704   Type *NewPtrTy =
9705                 PointerType::getUnqual(IntegerType::get(Size<<3));
9706   
9707   // Memcpy forces the use of i8* for the source and destination.  That means
9708   // that if you're using memcpy to move one double around, you'll get a cast
9709   // from double* to i8*.  We'd much rather use a double load+store rather than
9710   // an i64 load+store, here because this improves the odds that the source or
9711   // dest address will be promotable.  See if we can find a better type than the
9712   // integer datatype.
9713   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9714     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9715     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9716       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9717       // down through these levels if so.
9718       while (!SrcETy->isSingleValueType()) {
9719         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9720           if (STy->getNumElements() == 1)
9721             SrcETy = STy->getElementType(0);
9722           else
9723             break;
9724         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9725           if (ATy->getNumElements() == 1)
9726             SrcETy = ATy->getElementType();
9727           else
9728             break;
9729         } else
9730           break;
9731       }
9732       
9733       if (SrcETy->isSingleValueType())
9734         NewPtrTy = PointerType::getUnqual(SrcETy);
9735     }
9736   }
9737   
9738   
9739   // If the memcpy/memmove provides better alignment info than we can
9740   // infer, use it.
9741   SrcAlign = std::max(SrcAlign, CopyAlign);
9742   DstAlign = std::max(DstAlign, CopyAlign);
9743   
9744   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9745   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9746   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9747   InsertNewInstBefore(L, *MI);
9748   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9749
9750   // Set the size of the copy to 0, it will be deleted on the next iteration.
9751   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9752   return MI;
9753 }
9754
9755 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9756   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9757   if (MI->getAlignment() < Alignment) {
9758     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9759                                              Alignment, false));
9760     return MI;
9761   }
9762   
9763   // Extract the length and alignment and fill if they are constant.
9764   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9765   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9766   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9767     return 0;
9768   uint64_t Len = LenC->getZExtValue();
9769   Alignment = MI->getAlignment();
9770   
9771   // If the length is zero, this is a no-op
9772   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9773   
9774   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9775   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9776     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9777     
9778     Value *Dest = MI->getDest();
9779     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9780
9781     // Alignment 0 is identity for alignment 1 for memset, but not store.
9782     if (Alignment == 0) Alignment = 1;
9783     
9784     // Extract the fill value and store.
9785     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9786     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9787                                       Dest, false, Alignment), *MI);
9788     
9789     // Set the size of the copy to 0, it will be deleted on the next iteration.
9790     MI->setLength(Constant::getNullValue(LenC->getType()));
9791     return MI;
9792   }
9793
9794   return 0;
9795 }
9796
9797
9798 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9799 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9800 /// the heavy lifting.
9801 ///
9802 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9803   // If the caller function is nounwind, mark the call as nounwind, even if the
9804   // callee isn't.
9805   if (CI.getParent()->getParent()->doesNotThrow() &&
9806       !CI.doesNotThrow()) {
9807     CI.setDoesNotThrow();
9808     return &CI;
9809   }
9810   
9811   
9812   
9813   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9814   if (!II) return visitCallSite(&CI);
9815   
9816   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9817   // visitCallSite.
9818   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9819     bool Changed = false;
9820
9821     // memmove/cpy/set of zero bytes is a noop.
9822     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9823       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9824
9825       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9826         if (CI->getZExtValue() == 1) {
9827           // Replace the instruction with just byte operations.  We would
9828           // transform other cases to loads/stores, but we don't know if
9829           // alignment is sufficient.
9830         }
9831     }
9832
9833     // If we have a memmove and the source operation is a constant global,
9834     // then the source and dest pointers can't alias, so we can change this
9835     // into a call to memcpy.
9836     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9837       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9838         if (GVSrc->isConstant()) {
9839           Module *M = CI.getParent()->getParent()->getParent();
9840           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9841           const Type *Tys[1];
9842           Tys[0] = CI.getOperand(3)->getType();
9843           CI.setOperand(0, 
9844                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9845           Changed = true;
9846         }
9847
9848       // memmove(x,x,size) -> noop.
9849       if (MMI->getSource() == MMI->getDest())
9850         return EraseInstFromFunction(CI);
9851     }
9852
9853     // If we can determine a pointer alignment that is bigger than currently
9854     // set, update the alignment.
9855     if (isa<MemTransferInst>(MI)) {
9856       if (Instruction *I = SimplifyMemTransfer(MI))
9857         return I;
9858     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9859       if (Instruction *I = SimplifyMemSet(MSI))
9860         return I;
9861     }
9862           
9863     if (Changed) return II;
9864   }
9865   
9866   switch (II->getIntrinsicID()) {
9867   default: break;
9868   case Intrinsic::bswap:
9869     // bswap(bswap(x)) -> x
9870     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9871       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9872         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9873     break;
9874   case Intrinsic::ppc_altivec_lvx:
9875   case Intrinsic::ppc_altivec_lvxl:
9876   case Intrinsic::x86_sse_loadu_ps:
9877   case Intrinsic::x86_sse2_loadu_pd:
9878   case Intrinsic::x86_sse2_loadu_dq:
9879     // Turn PPC lvx     -> load if the pointer is known aligned.
9880     // Turn X86 loadups -> load if the pointer is known aligned.
9881     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9882       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9883                                    PointerType::getUnqual(II->getType()),
9884                                        CI);
9885       return new LoadInst(Ptr);
9886     }
9887     break;
9888   case Intrinsic::ppc_altivec_stvx:
9889   case Intrinsic::ppc_altivec_stvxl:
9890     // Turn stvx -> store if the pointer is known aligned.
9891     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9892       const Type *OpPtrTy = 
9893         PointerType::getUnqual(II->getOperand(1)->getType());
9894       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9895       return new StoreInst(II->getOperand(1), Ptr);
9896     }
9897     break;
9898   case Intrinsic::x86_sse_storeu_ps:
9899   case Intrinsic::x86_sse2_storeu_pd:
9900   case Intrinsic::x86_sse2_storeu_dq:
9901     // Turn X86 storeu -> store if the pointer is known aligned.
9902     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9903       const Type *OpPtrTy = 
9904         PointerType::getUnqual(II->getOperand(2)->getType());
9905       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9906       return new StoreInst(II->getOperand(2), Ptr);
9907     }
9908     break;
9909     
9910   case Intrinsic::x86_sse_cvttss2si: {
9911     // These intrinsics only demands the 0th element of its input vector.  If
9912     // we can simplify the input based on that, do so now.
9913     unsigned VWidth =
9914       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9915     APInt DemandedElts(VWidth, 1);
9916     APInt UndefElts(VWidth, 0);
9917     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9918                                               UndefElts)) {
9919       II->setOperand(1, V);
9920       return II;
9921     }
9922     break;
9923   }
9924     
9925   case Intrinsic::ppc_altivec_vperm:
9926     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9927     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9928       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9929       
9930       // Check that all of the elements are integer constants or undefs.
9931       bool AllEltsOk = true;
9932       for (unsigned i = 0; i != 16; ++i) {
9933         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9934             !isa<UndefValue>(Mask->getOperand(i))) {
9935           AllEltsOk = false;
9936           break;
9937         }
9938       }
9939       
9940       if (AllEltsOk) {
9941         // Cast the input vectors to byte vectors.
9942         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9943         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9944         Value *Result = UndefValue::get(Op0->getType());
9945         
9946         // Only extract each element once.
9947         Value *ExtractedElts[32];
9948         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9949         
9950         for (unsigned i = 0; i != 16; ++i) {
9951           if (isa<UndefValue>(Mask->getOperand(i)))
9952             continue;
9953           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9954           Idx &= 31;  // Match the hardware behavior.
9955           
9956           if (ExtractedElts[Idx] == 0) {
9957             Instruction *Elt = 
9958               ExtractElementInst::Create(Idx < 16 ? Op0 : Op1, 
9959                   ConstantInt::get(Type::Int32Ty, Idx&15, false), "tmp");
9960             InsertNewInstBefore(Elt, CI);
9961             ExtractedElts[Idx] = Elt;
9962           }
9963         
9964           // Insert this value into the result vector.
9965           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9966                                ConstantInt::get(Type::Int32Ty, i, false), 
9967                                "tmp");
9968           InsertNewInstBefore(cast<Instruction>(Result), CI);
9969         }
9970         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9971       }
9972     }
9973     break;
9974
9975   case Intrinsic::stackrestore: {
9976     // If the save is right next to the restore, remove the restore.  This can
9977     // happen when variable allocas are DCE'd.
9978     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9979       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9980         BasicBlock::iterator BI = SS;
9981         if (&*++BI == II)
9982           return EraseInstFromFunction(CI);
9983       }
9984     }
9985     
9986     // Scan down this block to see if there is another stack restore in the
9987     // same block without an intervening call/alloca.
9988     BasicBlock::iterator BI = II;
9989     TerminatorInst *TI = II->getParent()->getTerminator();
9990     bool CannotRemove = false;
9991     for (++BI; &*BI != TI; ++BI) {
9992       if (isa<AllocaInst>(BI)) {
9993         CannotRemove = true;
9994         break;
9995       }
9996       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9997         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9998           // If there is a stackrestore below this one, remove this one.
9999           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10000             return EraseInstFromFunction(CI);
10001           // Otherwise, ignore the intrinsic.
10002         } else {
10003           // If we found a non-intrinsic call, we can't remove the stack
10004           // restore.
10005           CannotRemove = true;
10006           break;
10007         }
10008       }
10009     }
10010     
10011     // If the stack restore is in a return/unwind block and if there are no
10012     // allocas or calls between the restore and the return, nuke the restore.
10013     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10014       return EraseInstFromFunction(CI);
10015     break;
10016   }
10017   }
10018
10019   return visitCallSite(II);
10020 }
10021
10022 // InvokeInst simplification
10023 //
10024 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10025   return visitCallSite(&II);
10026 }
10027
10028 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10029 /// passed through the varargs area, we can eliminate the use of the cast.
10030 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10031                                          const CastInst * const CI,
10032                                          const TargetData * const TD,
10033                                          const int ix) {
10034   if (!CI->isLosslessCast())
10035     return false;
10036
10037   // The size of ByVal arguments is derived from the type, so we
10038   // can't change to a type with a different size.  If the size were
10039   // passed explicitly we could avoid this check.
10040   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10041     return true;
10042
10043   const Type* SrcTy = 
10044             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10045   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10046   if (!SrcTy->isSized() || !DstTy->isSized())
10047     return false;
10048   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10049     return false;
10050   return true;
10051 }
10052
10053 // visitCallSite - Improvements for call and invoke instructions.
10054 //
10055 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10056   bool Changed = false;
10057
10058   // If the callee is a constexpr cast of a function, attempt to move the cast
10059   // to the arguments of the call/invoke.
10060   if (transformConstExprCastCall(CS)) return 0;
10061
10062   Value *Callee = CS.getCalledValue();
10063
10064   if (Function *CalleeF = dyn_cast<Function>(Callee))
10065     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10066       Instruction *OldCall = CS.getInstruction();
10067       // If the call and callee calling conventions don't match, this call must
10068       // be unreachable, as the call is undefined.
10069       new StoreInst(ConstantInt::getTrue(*Context),
10070                 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
10071                                   OldCall);
10072       if (!OldCall->use_empty())
10073         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10074       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10075         return EraseInstFromFunction(*OldCall);
10076       return 0;
10077     }
10078
10079   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10080     // This instruction is not reachable, just remove it.  We insert a store to
10081     // undef so that we know that this code is not reachable, despite the fact
10082     // that we can't modify the CFG here.
10083     new StoreInst(ConstantInt::getTrue(*Context),
10084                UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
10085                   CS.getInstruction());
10086
10087     if (!CS.getInstruction()->use_empty())
10088       CS.getInstruction()->
10089         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10090
10091     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10092       // Don't break the CFG, insert a dummy cond branch.
10093       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10094                          ConstantInt::getTrue(*Context), II);
10095     }
10096     return EraseInstFromFunction(*CS.getInstruction());
10097   }
10098
10099   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10100     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10101       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10102         return transformCallThroughTrampoline(CS);
10103
10104   const PointerType *PTy = cast<PointerType>(Callee->getType());
10105   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10106   if (FTy->isVarArg()) {
10107     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10108     // See if we can optimize any arguments passed through the varargs area of
10109     // the call.
10110     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10111            E = CS.arg_end(); I != E; ++I, ++ix) {
10112       CastInst *CI = dyn_cast<CastInst>(*I);
10113       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10114         *I = CI->getOperand(0);
10115         Changed = true;
10116       }
10117     }
10118   }
10119
10120   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10121     // Inline asm calls cannot throw - mark them 'nounwind'.
10122     CS.setDoesNotThrow();
10123     Changed = true;
10124   }
10125
10126   return Changed ? CS.getInstruction() : 0;
10127 }
10128
10129 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10130 // attempt to move the cast to the arguments of the call/invoke.
10131 //
10132 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10133   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10134   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10135   if (CE->getOpcode() != Instruction::BitCast || 
10136       !isa<Function>(CE->getOperand(0)))
10137     return false;
10138   Function *Callee = cast<Function>(CE->getOperand(0));
10139   Instruction *Caller = CS.getInstruction();
10140   const AttrListPtr &CallerPAL = CS.getAttributes();
10141
10142   // Okay, this is a cast from a function to a different type.  Unless doing so
10143   // would cause a type conversion of one of our arguments, change this call to
10144   // be a direct call with arguments casted to the appropriate types.
10145   //
10146   const FunctionType *FT = Callee->getFunctionType();
10147   const Type *OldRetTy = Caller->getType();
10148   const Type *NewRetTy = FT->getReturnType();
10149
10150   if (isa<StructType>(NewRetTy))
10151     return false; // TODO: Handle multiple return values.
10152
10153   // Check to see if we are changing the return type...
10154   if (OldRetTy != NewRetTy) {
10155     if (Callee->isDeclaration() &&
10156         // Conversion is ok if changing from one pointer type to another or from
10157         // a pointer to an integer of the same size.
10158         !((isa<PointerType>(OldRetTy) || !TD ||
10159            OldRetTy == TD->getIntPtrType()) &&
10160           (isa<PointerType>(NewRetTy) || !TD ||
10161            NewRetTy == TD->getIntPtrType())))
10162       return false;   // Cannot transform this return value.
10163
10164     if (!Caller->use_empty() &&
10165         // void -> non-void is handled specially
10166         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10167       return false;   // Cannot transform this return value.
10168
10169     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10170       Attributes RAttrs = CallerPAL.getRetAttributes();
10171       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10172         return false;   // Attribute not compatible with transformed value.
10173     }
10174
10175     // If the callsite is an invoke instruction, and the return value is used by
10176     // a PHI node in a successor, we cannot change the return type of the call
10177     // because there is no place to put the cast instruction (without breaking
10178     // the critical edge).  Bail out in this case.
10179     if (!Caller->use_empty())
10180       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10181         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10182              UI != E; ++UI)
10183           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10184             if (PN->getParent() == II->getNormalDest() ||
10185                 PN->getParent() == II->getUnwindDest())
10186               return false;
10187   }
10188
10189   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10190   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10191
10192   CallSite::arg_iterator AI = CS.arg_begin();
10193   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10194     const Type *ParamTy = FT->getParamType(i);
10195     const Type *ActTy = (*AI)->getType();
10196
10197     if (!CastInst::isCastable(ActTy, ParamTy))
10198       return false;   // Cannot transform this parameter value.
10199
10200     if (CallerPAL.getParamAttributes(i + 1) 
10201         & Attribute::typeIncompatible(ParamTy))
10202       return false;   // Attribute not compatible with transformed value.
10203
10204     // Converting from one pointer type to another or between a pointer and an
10205     // integer of the same size is safe even if we do not have a body.
10206     bool isConvertible = ActTy == ParamTy ||
10207       (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10208               (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
10209     if (Callee->isDeclaration() && !isConvertible) return false;
10210   }
10211
10212   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10213       Callee->isDeclaration())
10214     return false;   // Do not delete arguments unless we have a function body.
10215
10216   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10217       !CallerPAL.isEmpty())
10218     // In this case we have more arguments than the new function type, but we
10219     // won't be dropping them.  Check that these extra arguments have attributes
10220     // that are compatible with being a vararg call argument.
10221     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10222       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10223         break;
10224       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10225       if (PAttrs & Attribute::VarArgsIncompatible)
10226         return false;
10227     }
10228
10229   // Okay, we decided that this is a safe thing to do: go ahead and start
10230   // inserting cast instructions as necessary...
10231   std::vector<Value*> Args;
10232   Args.reserve(NumActualArgs);
10233   SmallVector<AttributeWithIndex, 8> attrVec;
10234   attrVec.reserve(NumCommonArgs);
10235
10236   // Get any return attributes.
10237   Attributes RAttrs = CallerPAL.getRetAttributes();
10238
10239   // If the return value is not being used, the type may not be compatible
10240   // with the existing attributes.  Wipe out any problematic attributes.
10241   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10242
10243   // Add the new return attributes.
10244   if (RAttrs)
10245     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10246
10247   AI = CS.arg_begin();
10248   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10249     const Type *ParamTy = FT->getParamType(i);
10250     if ((*AI)->getType() == ParamTy) {
10251       Args.push_back(*AI);
10252     } else {
10253       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10254           false, ParamTy, false);
10255       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10256       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10257     }
10258
10259     // Add any parameter attributes.
10260     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10261       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10262   }
10263
10264   // If the function takes more arguments than the call was taking, add them
10265   // now...
10266   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10267     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10268
10269   // If we are removing arguments to the function, emit an obnoxious warning...
10270   if (FT->getNumParams() < NumActualArgs) {
10271     if (!FT->isVarArg()) {
10272       errs() << "WARNING: While resolving call to function '"
10273              << Callee->getName() << "' arguments were dropped!\n";
10274     } else {
10275       // Add all of the arguments in their promoted form to the arg list...
10276       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10277         const Type *PTy = getPromotedType((*AI)->getType());
10278         if (PTy != (*AI)->getType()) {
10279           // Must promote to pass through va_arg area!
10280           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10281                                                                 PTy, false);
10282           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10283           InsertNewInstBefore(Cast, *Caller);
10284           Args.push_back(Cast);
10285         } else {
10286           Args.push_back(*AI);
10287         }
10288
10289         // Add any parameter attributes.
10290         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10291           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10292       }
10293     }
10294   }
10295
10296   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10297     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10298
10299   if (NewRetTy == Type::VoidTy)
10300     Caller->setName("");   // Void type should not have a name.
10301
10302   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10303                                                      attrVec.end());
10304
10305   Instruction *NC;
10306   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10307     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10308                             Args.begin(), Args.end(),
10309                             Caller->getName(), Caller);
10310     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10311     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10312   } else {
10313     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10314                           Caller->getName(), Caller);
10315     CallInst *CI = cast<CallInst>(Caller);
10316     if (CI->isTailCall())
10317       cast<CallInst>(NC)->setTailCall();
10318     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10319     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10320   }
10321
10322   // Insert a cast of the return type as necessary.
10323   Value *NV = NC;
10324   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10325     if (NV->getType() != Type::VoidTy) {
10326       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10327                                                             OldRetTy, false);
10328       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10329
10330       // If this is an invoke instruction, we should insert it after the first
10331       // non-phi, instruction in the normal successor block.
10332       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10333         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10334         InsertNewInstBefore(NC, *I);
10335       } else {
10336         // Otherwise, it's a call, just insert cast right after the call instr
10337         InsertNewInstBefore(NC, *Caller);
10338       }
10339       AddUsersToWorkList(*Caller);
10340     } else {
10341       NV = UndefValue::get(Caller->getType());
10342     }
10343   }
10344
10345   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10346     Caller->replaceAllUsesWith(NV);
10347   Caller->eraseFromParent();
10348   RemoveFromWorkList(Caller);
10349   return true;
10350 }
10351
10352 // transformCallThroughTrampoline - Turn a call to a function created by the
10353 // init_trampoline intrinsic into a direct call to the underlying function.
10354 //
10355 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10356   Value *Callee = CS.getCalledValue();
10357   const PointerType *PTy = cast<PointerType>(Callee->getType());
10358   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10359   const AttrListPtr &Attrs = CS.getAttributes();
10360
10361   // If the call already has the 'nest' attribute somewhere then give up -
10362   // otherwise 'nest' would occur twice after splicing in the chain.
10363   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10364     return 0;
10365
10366   IntrinsicInst *Tramp =
10367     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10368
10369   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10370   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10371   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10372
10373   const AttrListPtr &NestAttrs = NestF->getAttributes();
10374   if (!NestAttrs.isEmpty()) {
10375     unsigned NestIdx = 1;
10376     const Type *NestTy = 0;
10377     Attributes NestAttr = Attribute::None;
10378
10379     // Look for a parameter marked with the 'nest' attribute.
10380     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10381          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10382       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10383         // Record the parameter type and any other attributes.
10384         NestTy = *I;
10385         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10386         break;
10387       }
10388
10389     if (NestTy) {
10390       Instruction *Caller = CS.getInstruction();
10391       std::vector<Value*> NewArgs;
10392       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10393
10394       SmallVector<AttributeWithIndex, 8> NewAttrs;
10395       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10396
10397       // Insert the nest argument into the call argument list, which may
10398       // mean appending it.  Likewise for attributes.
10399
10400       // Add any result attributes.
10401       if (Attributes Attr = Attrs.getRetAttributes())
10402         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10403
10404       {
10405         unsigned Idx = 1;
10406         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10407         do {
10408           if (Idx == NestIdx) {
10409             // Add the chain argument and attributes.
10410             Value *NestVal = Tramp->getOperand(3);
10411             if (NestVal->getType() != NestTy)
10412               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10413             NewArgs.push_back(NestVal);
10414             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10415           }
10416
10417           if (I == E)
10418             break;
10419
10420           // Add the original argument and attributes.
10421           NewArgs.push_back(*I);
10422           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10423             NewAttrs.push_back
10424               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10425
10426           ++Idx, ++I;
10427         } while (1);
10428       }
10429
10430       // Add any function attributes.
10431       if (Attributes Attr = Attrs.getFnAttributes())
10432         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10433
10434       // The trampoline may have been bitcast to a bogus type (FTy).
10435       // Handle this by synthesizing a new function type, equal to FTy
10436       // with the chain parameter inserted.
10437
10438       std::vector<const Type*> NewTypes;
10439       NewTypes.reserve(FTy->getNumParams()+1);
10440
10441       // Insert the chain's type into the list of parameter types, which may
10442       // mean appending it.
10443       {
10444         unsigned Idx = 1;
10445         FunctionType::param_iterator I = FTy->param_begin(),
10446           E = FTy->param_end();
10447
10448         do {
10449           if (Idx == NestIdx)
10450             // Add the chain's type.
10451             NewTypes.push_back(NestTy);
10452
10453           if (I == E)
10454             break;
10455
10456           // Add the original type.
10457           NewTypes.push_back(*I);
10458
10459           ++Idx, ++I;
10460         } while (1);
10461       }
10462
10463       // Replace the trampoline call with a direct call.  Let the generic
10464       // code sort out any function type mismatches.
10465       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10466                                                 FTy->isVarArg());
10467       Constant *NewCallee =
10468         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10469         NestF : ConstantExpr::getBitCast(NestF, 
10470                                          PointerType::getUnqual(NewFTy));
10471       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10472                                                    NewAttrs.end());
10473
10474       Instruction *NewCaller;
10475       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10476         NewCaller = InvokeInst::Create(NewCallee,
10477                                        II->getNormalDest(), II->getUnwindDest(),
10478                                        NewArgs.begin(), NewArgs.end(),
10479                                        Caller->getName(), Caller);
10480         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10481         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10482       } else {
10483         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10484                                      Caller->getName(), Caller);
10485         if (cast<CallInst>(Caller)->isTailCall())
10486           cast<CallInst>(NewCaller)->setTailCall();
10487         cast<CallInst>(NewCaller)->
10488           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10489         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10490       }
10491       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10492         Caller->replaceAllUsesWith(NewCaller);
10493       Caller->eraseFromParent();
10494       RemoveFromWorkList(Caller);
10495       return 0;
10496     }
10497   }
10498
10499   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10500   // parameter, there is no need to adjust the argument list.  Let the generic
10501   // code sort out any function type mismatches.
10502   Constant *NewCallee =
10503     NestF->getType() == PTy ? NestF : 
10504                               ConstantExpr::getBitCast(NestF, PTy);
10505   CS.setCalledFunction(NewCallee);
10506   return CS.getInstruction();
10507 }
10508
10509 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10510 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10511 /// and a single binop.
10512 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10513   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10514   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10515   unsigned Opc = FirstInst->getOpcode();
10516   Value *LHSVal = FirstInst->getOperand(0);
10517   Value *RHSVal = FirstInst->getOperand(1);
10518     
10519   const Type *LHSType = LHSVal->getType();
10520   const Type *RHSType = RHSVal->getType();
10521   
10522   // Scan to see if all operands are the same opcode, all have one use, and all
10523   // kill their operands (i.e. the operands have one use).
10524   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10525     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10526     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10527         // Verify type of the LHS matches so we don't fold cmp's of different
10528         // types or GEP's with different index types.
10529         I->getOperand(0)->getType() != LHSType ||
10530         I->getOperand(1)->getType() != RHSType)
10531       return 0;
10532
10533     // If they are CmpInst instructions, check their predicates
10534     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10535       if (cast<CmpInst>(I)->getPredicate() !=
10536           cast<CmpInst>(FirstInst)->getPredicate())
10537         return 0;
10538     
10539     // Keep track of which operand needs a phi node.
10540     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10541     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10542   }
10543   
10544   // Otherwise, this is safe to transform!
10545   
10546   Value *InLHS = FirstInst->getOperand(0);
10547   Value *InRHS = FirstInst->getOperand(1);
10548   PHINode *NewLHS = 0, *NewRHS = 0;
10549   if (LHSVal == 0) {
10550     NewLHS = PHINode::Create(LHSType,
10551                              FirstInst->getOperand(0)->getName() + ".pn");
10552     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10553     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10554     InsertNewInstBefore(NewLHS, PN);
10555     LHSVal = NewLHS;
10556   }
10557   
10558   if (RHSVal == 0) {
10559     NewRHS = PHINode::Create(RHSType,
10560                              FirstInst->getOperand(1)->getName() + ".pn");
10561     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10562     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10563     InsertNewInstBefore(NewRHS, PN);
10564     RHSVal = NewRHS;
10565   }
10566   
10567   // Add all operands to the new PHIs.
10568   if (NewLHS || NewRHS) {
10569     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10570       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10571       if (NewLHS) {
10572         Value *NewInLHS = InInst->getOperand(0);
10573         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10574       }
10575       if (NewRHS) {
10576         Value *NewInRHS = InInst->getOperand(1);
10577         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10578       }
10579     }
10580   }
10581     
10582   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10583     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10584   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10585   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10586                          LHSVal, RHSVal);
10587 }
10588
10589 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10590   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10591   
10592   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10593                                         FirstInst->op_end());
10594   // This is true if all GEP bases are allocas and if all indices into them are
10595   // constants.
10596   bool AllBasePointersAreAllocas = true;
10597   
10598   // Scan to see if all operands are the same opcode, all have one use, and all
10599   // kill their operands (i.e. the operands have one use).
10600   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10601     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10602     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10603       GEP->getNumOperands() != FirstInst->getNumOperands())
10604       return 0;
10605
10606     // Keep track of whether or not all GEPs are of alloca pointers.
10607     if (AllBasePointersAreAllocas &&
10608         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10609          !GEP->hasAllConstantIndices()))
10610       AllBasePointersAreAllocas = false;
10611     
10612     // Compare the operand lists.
10613     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10614       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10615         continue;
10616       
10617       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10618       // if one of the PHIs has a constant for the index.  The index may be
10619       // substantially cheaper to compute for the constants, so making it a
10620       // variable index could pessimize the path.  This also handles the case
10621       // for struct indices, which must always be constant.
10622       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10623           isa<ConstantInt>(GEP->getOperand(op)))
10624         return 0;
10625       
10626       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10627         return 0;
10628       FixedOperands[op] = 0;  // Needs a PHI.
10629     }
10630   }
10631   
10632   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10633   // bother doing this transformation.  At best, this will just save a bit of
10634   // offset calculation, but all the predecessors will have to materialize the
10635   // stack address into a register anyway.  We'd actually rather *clone* the
10636   // load up into the predecessors so that we have a load of a gep of an alloca,
10637   // which can usually all be folded into the load.
10638   if (AllBasePointersAreAllocas)
10639     return 0;
10640   
10641   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10642   // that is variable.
10643   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10644   
10645   bool HasAnyPHIs = false;
10646   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10647     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10648     Value *FirstOp = FirstInst->getOperand(i);
10649     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10650                                      FirstOp->getName()+".pn");
10651     InsertNewInstBefore(NewPN, PN);
10652     
10653     NewPN->reserveOperandSpace(e);
10654     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10655     OperandPhis[i] = NewPN;
10656     FixedOperands[i] = NewPN;
10657     HasAnyPHIs = true;
10658   }
10659
10660   
10661   // Add all operands to the new PHIs.
10662   if (HasAnyPHIs) {
10663     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10664       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10665       BasicBlock *InBB = PN.getIncomingBlock(i);
10666       
10667       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10668         if (PHINode *OpPhi = OperandPhis[op])
10669           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10670     }
10671   }
10672   
10673   Value *Base = FixedOperands[0];
10674   GetElementPtrInst *GEP =
10675     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10676                               FixedOperands.end());
10677   if (cast<GEPOperator>(FirstInst)->isInBounds())
10678     cast<GEPOperator>(GEP)->setIsInBounds(true);
10679   return GEP;
10680 }
10681
10682
10683 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10684 /// sink the load out of the block that defines it.  This means that it must be
10685 /// obvious the value of the load is not changed from the point of the load to
10686 /// the end of the block it is in.
10687 ///
10688 /// Finally, it is safe, but not profitable, to sink a load targetting a
10689 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10690 /// to a register.
10691 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10692   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10693   
10694   for (++BBI; BBI != E; ++BBI)
10695     if (BBI->mayWriteToMemory())
10696       return false;
10697   
10698   // Check for non-address taken alloca.  If not address-taken already, it isn't
10699   // profitable to do this xform.
10700   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10701     bool isAddressTaken = false;
10702     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10703          UI != E; ++UI) {
10704       if (isa<LoadInst>(UI)) continue;
10705       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10706         // If storing TO the alloca, then the address isn't taken.
10707         if (SI->getOperand(1) == AI) continue;
10708       }
10709       isAddressTaken = true;
10710       break;
10711     }
10712     
10713     if (!isAddressTaken && AI->isStaticAlloca())
10714       return false;
10715   }
10716   
10717   // If this load is a load from a GEP with a constant offset from an alloca,
10718   // then we don't want to sink it.  In its present form, it will be
10719   // load [constant stack offset].  Sinking it will cause us to have to
10720   // materialize the stack addresses in each predecessor in a register only to
10721   // do a shared load from register in the successor.
10722   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10723     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10724       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10725         return false;
10726   
10727   return true;
10728 }
10729
10730
10731 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10732 // operator and they all are only used by the PHI, PHI together their
10733 // inputs, and do the operation once, to the result of the PHI.
10734 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10735   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10736
10737   // Scan the instruction, looking for input operations that can be folded away.
10738   // If all input operands to the phi are the same instruction (e.g. a cast from
10739   // the same type or "+42") we can pull the operation through the PHI, reducing
10740   // code size and simplifying code.
10741   Constant *ConstantOp = 0;
10742   const Type *CastSrcTy = 0;
10743   bool isVolatile = false;
10744   if (isa<CastInst>(FirstInst)) {
10745     CastSrcTy = FirstInst->getOperand(0)->getType();
10746   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10747     // Can fold binop, compare or shift here if the RHS is a constant, 
10748     // otherwise call FoldPHIArgBinOpIntoPHI.
10749     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10750     if (ConstantOp == 0)
10751       return FoldPHIArgBinOpIntoPHI(PN);
10752   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10753     isVolatile = LI->isVolatile();
10754     // We can't sink the load if the loaded value could be modified between the
10755     // load and the PHI.
10756     if (LI->getParent() != PN.getIncomingBlock(0) ||
10757         !isSafeAndProfitableToSinkLoad(LI))
10758       return 0;
10759     
10760     // If the PHI is of volatile loads and the load block has multiple
10761     // successors, sinking it would remove a load of the volatile value from
10762     // the path through the other successor.
10763     if (isVolatile &&
10764         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10765       return 0;
10766     
10767   } else if (isa<GetElementPtrInst>(FirstInst)) {
10768     return FoldPHIArgGEPIntoPHI(PN);
10769   } else {
10770     return 0;  // Cannot fold this operation.
10771   }
10772
10773   // Check to see if all arguments are the same operation.
10774   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10775     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10776     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10777     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10778       return 0;
10779     if (CastSrcTy) {
10780       if (I->getOperand(0)->getType() != CastSrcTy)
10781         return 0;  // Cast operation must match.
10782     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10783       // We can't sink the load if the loaded value could be modified between 
10784       // the load and the PHI.
10785       if (LI->isVolatile() != isVolatile ||
10786           LI->getParent() != PN.getIncomingBlock(i) ||
10787           !isSafeAndProfitableToSinkLoad(LI))
10788         return 0;
10789       
10790       // If the PHI is of volatile loads and the load block has multiple
10791       // successors, sinking it would remove a load of the volatile value from
10792       // the path through the other successor.
10793       if (isVolatile &&
10794           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10795         return 0;
10796       
10797     } else if (I->getOperand(1) != ConstantOp) {
10798       return 0;
10799     }
10800   }
10801
10802   // Okay, they are all the same operation.  Create a new PHI node of the
10803   // correct type, and PHI together all of the LHS's of the instructions.
10804   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10805                                    PN.getName()+".in");
10806   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10807
10808   Value *InVal = FirstInst->getOperand(0);
10809   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10810
10811   // Add all operands to the new PHI.
10812   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10813     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10814     if (NewInVal != InVal)
10815       InVal = 0;
10816     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10817   }
10818
10819   Value *PhiVal;
10820   if (InVal) {
10821     // The new PHI unions all of the same values together.  This is really
10822     // common, so we handle it intelligently here for compile-time speed.
10823     PhiVal = InVal;
10824     delete NewPN;
10825   } else {
10826     InsertNewInstBefore(NewPN, PN);
10827     PhiVal = NewPN;
10828   }
10829
10830   // Insert and return the new operation.
10831   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10832     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10833   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10834     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10835   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10836     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10837                            PhiVal, ConstantOp);
10838   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10839   
10840   // If this was a volatile load that we are merging, make sure to loop through
10841   // and mark all the input loads as non-volatile.  If we don't do this, we will
10842   // insert a new volatile load and the old ones will not be deletable.
10843   if (isVolatile)
10844     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10845       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10846   
10847   return new LoadInst(PhiVal, "", isVolatile);
10848 }
10849
10850 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10851 /// that is dead.
10852 static bool DeadPHICycle(PHINode *PN,
10853                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10854   if (PN->use_empty()) return true;
10855   if (!PN->hasOneUse()) return false;
10856
10857   // Remember this node, and if we find the cycle, return.
10858   if (!PotentiallyDeadPHIs.insert(PN))
10859     return true;
10860   
10861   // Don't scan crazily complex things.
10862   if (PotentiallyDeadPHIs.size() == 16)
10863     return false;
10864
10865   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10866     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10867
10868   return false;
10869 }
10870
10871 /// PHIsEqualValue - Return true if this phi node is always equal to
10872 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10873 ///   z = some value; x = phi (y, z); y = phi (x, z)
10874 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10875                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10876   // See if we already saw this PHI node.
10877   if (!ValueEqualPHIs.insert(PN))
10878     return true;
10879   
10880   // Don't scan crazily complex things.
10881   if (ValueEqualPHIs.size() == 16)
10882     return false;
10883  
10884   // Scan the operands to see if they are either phi nodes or are equal to
10885   // the value.
10886   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10887     Value *Op = PN->getIncomingValue(i);
10888     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10889       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10890         return false;
10891     } else if (Op != NonPhiInVal)
10892       return false;
10893   }
10894   
10895   return true;
10896 }
10897
10898
10899 // PHINode simplification
10900 //
10901 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10902   // If LCSSA is around, don't mess with Phi nodes
10903   if (MustPreserveLCSSA) return 0;
10904   
10905   if (Value *V = PN.hasConstantValue())
10906     return ReplaceInstUsesWith(PN, V);
10907
10908   // If all PHI operands are the same operation, pull them through the PHI,
10909   // reducing code size.
10910   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10911       isa<Instruction>(PN.getIncomingValue(1)) &&
10912       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10913       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10914       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10915       // than themselves more than once.
10916       PN.getIncomingValue(0)->hasOneUse())
10917     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10918       return Result;
10919
10920   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10921   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10922   // PHI)... break the cycle.
10923   if (PN.hasOneUse()) {
10924     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10925     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10926       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10927       PotentiallyDeadPHIs.insert(&PN);
10928       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10929         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10930     }
10931    
10932     // If this phi has a single use, and if that use just computes a value for
10933     // the next iteration of a loop, delete the phi.  This occurs with unused
10934     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10935     // common case here is good because the only other things that catch this
10936     // are induction variable analysis (sometimes) and ADCE, which is only run
10937     // late.
10938     if (PHIUser->hasOneUse() &&
10939         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10940         PHIUser->use_back() == &PN) {
10941       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10942     }
10943   }
10944
10945   // We sometimes end up with phi cycles that non-obviously end up being the
10946   // same value, for example:
10947   //   z = some value; x = phi (y, z); y = phi (x, z)
10948   // where the phi nodes don't necessarily need to be in the same block.  Do a
10949   // quick check to see if the PHI node only contains a single non-phi value, if
10950   // so, scan to see if the phi cycle is actually equal to that value.
10951   {
10952     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10953     // Scan for the first non-phi operand.
10954     while (InValNo != NumOperandVals && 
10955            isa<PHINode>(PN.getIncomingValue(InValNo)))
10956       ++InValNo;
10957
10958     if (InValNo != NumOperandVals) {
10959       Value *NonPhiInVal = PN.getOperand(InValNo);
10960       
10961       // Scan the rest of the operands to see if there are any conflicts, if so
10962       // there is no need to recursively scan other phis.
10963       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10964         Value *OpVal = PN.getIncomingValue(InValNo);
10965         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10966           break;
10967       }
10968       
10969       // If we scanned over all operands, then we have one unique value plus
10970       // phi values.  Scan PHI nodes to see if they all merge in each other or
10971       // the value.
10972       if (InValNo == NumOperandVals) {
10973         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10974         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10975           return ReplaceInstUsesWith(PN, NonPhiInVal);
10976       }
10977     }
10978   }
10979   return 0;
10980 }
10981
10982 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10983                                    Instruction *InsertPoint,
10984                                    InstCombiner *IC) {
10985   unsigned PtrSize = DTy->getScalarSizeInBits();
10986   unsigned VTySize = V->getType()->getScalarSizeInBits();
10987   // We must cast correctly to the pointer type. Ensure that we
10988   // sign extend the integer value if it is smaller as this is
10989   // used for address computation.
10990   Instruction::CastOps opcode = 
10991      (VTySize < PtrSize ? Instruction::SExt :
10992       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10993   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10994 }
10995
10996
10997 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10998   Value *PtrOp = GEP.getOperand(0);
10999   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11000   // If so, eliminate the noop.
11001   if (GEP.getNumOperands() == 1)
11002     return ReplaceInstUsesWith(GEP, PtrOp);
11003
11004   if (isa<UndefValue>(GEP.getOperand(0)))
11005     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11006
11007   bool HasZeroPointerIndex = false;
11008   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11009     HasZeroPointerIndex = C->isNullValue();
11010
11011   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11012     return ReplaceInstUsesWith(GEP, PtrOp);
11013
11014   // Eliminate unneeded casts for indices.
11015   bool MadeChange = false;
11016   
11017   gep_type_iterator GTI = gep_type_begin(GEP);
11018   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11019        i != e; ++i, ++GTI) {
11020     if (TD && isa<SequentialType>(*GTI)) {
11021       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11022         if (CI->getOpcode() == Instruction::ZExt ||
11023             CI->getOpcode() == Instruction::SExt) {
11024           const Type *SrcTy = CI->getOperand(0)->getType();
11025           // We can eliminate a cast from i32 to i64 iff the target 
11026           // is a 32-bit pointer target.
11027           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11028             MadeChange = true;
11029             *i = CI->getOperand(0);
11030           }
11031         }
11032       }
11033       // If we are using a wider index than needed for this platform, shrink it
11034       // to what we need.  If narrower, sign-extend it to what we need.
11035       // If the incoming value needs a cast instruction,
11036       // insert it.  This explicit cast can make subsequent optimizations more
11037       // obvious.
11038       Value *Op = *i;
11039       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11040         if (Constant *C = dyn_cast<Constant>(Op)) {
11041           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
11042           MadeChange = true;
11043         } else {
11044           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11045                                 GEP);
11046           *i = Op;
11047           MadeChange = true;
11048         }
11049       } else if (TD->getTypeSizeInBits(Op->getType()) 
11050                   < TD->getPointerSizeInBits()) {
11051         if (Constant *C = dyn_cast<Constant>(Op)) {
11052           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
11053           MadeChange = true;
11054         } else {
11055           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11056                                 GEP);
11057           *i = Op;
11058           MadeChange = true;
11059         }
11060       }
11061     }
11062   }
11063   if (MadeChange) return &GEP;
11064
11065   // Combine Indices - If the source pointer to this getelementptr instruction
11066   // is a getelementptr instruction, combine the indices of the two
11067   // getelementptr instructions into a single instruction.
11068   //
11069   SmallVector<Value*, 8> SrcGEPOperands;
11070   bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11071   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11072     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11073     if (!Src->isInBounds())
11074       BothInBounds = false;
11075   }
11076
11077   if (!SrcGEPOperands.empty()) {
11078     // Note that if our source is a gep chain itself that we wait for that
11079     // chain to be resolved before we perform this transformation.  This
11080     // avoids us creating a TON of code in some cases.
11081     //
11082     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11083         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11084       return 0;   // Wait until our source is folded to completion.
11085
11086     SmallVector<Value*, 8> Indices;
11087
11088     // Find out whether the last index in the source GEP is a sequential idx.
11089     bool EndsWithSequential = false;
11090     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11091            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11092       EndsWithSequential = !isa<StructType>(*I);
11093
11094     // Can we combine the two pointer arithmetics offsets?
11095     if (EndsWithSequential) {
11096       // Replace: gep (gep %P, long B), long A, ...
11097       // With:    T = long A+B; gep %P, T, ...
11098       //
11099       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11100       if (SO1 == Constant::getNullValue(SO1->getType())) {
11101         Sum = GO1;
11102       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11103         Sum = SO1;
11104       } else {
11105         // If they aren't the same type, convert both to an integer of the
11106         // target's pointer size.
11107         if (SO1->getType() != GO1->getType()) {
11108           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11109             SO1 =
11110                 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
11111           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11112             GO1 =
11113                 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
11114           } else if (TD) {
11115             unsigned PS = TD->getPointerSizeInBits();
11116             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11117               // Convert GO1 to SO1's type.
11118               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11119
11120             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11121               // Convert SO1 to GO1's type.
11122               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11123             } else {
11124               const Type *PT = TD->getIntPtrType();
11125               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11126               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11127             }
11128           }
11129         }
11130         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11131           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), 
11132                                             cast<Constant>(GO1));
11133         else {
11134           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11135           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11136         }
11137       }
11138
11139       // Recycle the GEP we already have if possible.
11140       if (SrcGEPOperands.size() == 2) {
11141         GEP.setOperand(0, SrcGEPOperands[0]);
11142         GEP.setOperand(1, Sum);
11143         return &GEP;
11144       } else {
11145         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11146                        SrcGEPOperands.end()-1);
11147         Indices.push_back(Sum);
11148         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11149       }
11150     } else if (isa<Constant>(*GEP.idx_begin()) &&
11151                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11152                SrcGEPOperands.size() != 1) {
11153       // Otherwise we can do the fold if the first index of the GEP is a zero
11154       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11155                      SrcGEPOperands.end());
11156       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11157     }
11158
11159     if (!Indices.empty()) {
11160       GetElementPtrInst *NewGEP = GetElementPtrInst::Create(SrcGEPOperands[0],
11161                                                             Indices.begin(),
11162                                                             Indices.end(),
11163                                                             GEP.getName());
11164       if (BothInBounds)
11165         cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11166       return NewGEP;
11167     }
11168
11169   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11170     // GEP of global variable.  If all of the indices for this GEP are
11171     // constants, we can promote this to a constexpr instead of an instruction.
11172
11173     // Scan for nonconstants...
11174     SmallVector<Constant*, 8> Indices;
11175     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11176     for (; I != E && isa<Constant>(*I); ++I)
11177       Indices.push_back(cast<Constant>(*I));
11178
11179     if (I == E) {  // If they are all constants...
11180       Constant *CE = ConstantExpr::getGetElementPtr(GV,
11181                                                     &Indices[0],Indices.size());
11182
11183       // Replace all uses of the GEP with the new constexpr...
11184       return ReplaceInstUsesWith(GEP, CE);
11185     }
11186   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11187     if (!isa<PointerType>(X->getType())) {
11188       // Not interesting.  Source pointer must be a cast from pointer.
11189     } else if (HasZeroPointerIndex) {
11190       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11191       // into     : GEP [10 x i8]* X, i32 0, ...
11192       //
11193       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11194       //           into     : GEP i8* X, ...
11195       // 
11196       // This occurs when the program declares an array extern like "int X[];"
11197       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11198       const PointerType *XTy = cast<PointerType>(X->getType());
11199       if (const ArrayType *CATy =
11200           dyn_cast<ArrayType>(CPTy->getElementType())) {
11201         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11202         if (CATy->getElementType() == XTy->getElementType()) {
11203           // -> GEP i8* X, ...
11204           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11205           GetElementPtrInst *NewGEP =
11206             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11207                                       GEP.getName());
11208           if (cast<GEPOperator>(&GEP)->isInBounds())
11209             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11210           return NewGEP;
11211         } else if (const ArrayType *XATy =
11212                  dyn_cast<ArrayType>(XTy->getElementType())) {
11213           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11214           if (CATy->getElementType() == XATy->getElementType()) {
11215             // -> GEP [10 x i8]* X, i32 0, ...
11216             // At this point, we know that the cast source type is a pointer
11217             // to an array of the same type as the destination pointer
11218             // array.  Because the array type is never stepped over (there
11219             // is a leading zero) we can fold the cast into this GEP.
11220             GEP.setOperand(0, X);
11221             return &GEP;
11222           }
11223         }
11224       }
11225     } else if (GEP.getNumOperands() == 2) {
11226       // Transform things like:
11227       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11228       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11229       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11230       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11231       if (TD && isa<ArrayType>(SrcElTy) &&
11232           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11233           TD->getTypeAllocSize(ResElTy)) {
11234         Value *Idx[2];
11235         Idx[0] = Constant::getNullValue(Type::Int32Ty);
11236         Idx[1] = GEP.getOperand(1);
11237         GetElementPtrInst *NewGEP =
11238           GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11239         if (cast<GEPOperator>(&GEP)->isInBounds())
11240           cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11241         Value *V = InsertNewInstBefore(NewGEP, GEP);
11242         // V and GEP are both pointer types --> BitCast
11243         return new BitCastInst(V, GEP.getType());
11244       }
11245       
11246       // Transform things like:
11247       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11248       //   (where tmp = 8*tmp2) into:
11249       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11250       
11251       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11252         uint64_t ArrayEltSize =
11253             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11254         
11255         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11256         // allow either a mul, shift, or constant here.
11257         Value *NewIdx = 0;
11258         ConstantInt *Scale = 0;
11259         if (ArrayEltSize == 1) {
11260           NewIdx = GEP.getOperand(1);
11261           Scale = 
11262                ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11263         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11264           NewIdx = ConstantInt::get(CI->getType(), 1);
11265           Scale = CI;
11266         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11267           if (Inst->getOpcode() == Instruction::Shl &&
11268               isa<ConstantInt>(Inst->getOperand(1))) {
11269             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11270             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11271             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11272                                      1ULL << ShAmtVal);
11273             NewIdx = Inst->getOperand(0);
11274           } else if (Inst->getOpcode() == Instruction::Mul &&
11275                      isa<ConstantInt>(Inst->getOperand(1))) {
11276             Scale = cast<ConstantInt>(Inst->getOperand(1));
11277             NewIdx = Inst->getOperand(0);
11278           }
11279         }
11280         
11281         // If the index will be to exactly the right offset with the scale taken
11282         // out, perform the transformation. Note, we don't know whether Scale is
11283         // signed or not. We'll use unsigned version of division/modulo
11284         // operation after making sure Scale doesn't have the sign bit set.
11285         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11286             Scale->getZExtValue() % ArrayEltSize == 0) {
11287           Scale = ConstantInt::get(Scale->getType(),
11288                                    Scale->getZExtValue() / ArrayEltSize);
11289           if (Scale->getZExtValue() != 1) {
11290             Constant *C =
11291                    ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11292                                                        false /*ZExt*/);
11293             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11294             NewIdx = InsertNewInstBefore(Sc, GEP);
11295           }
11296
11297           // Insert the new GEP instruction.
11298           Value *Idx[2];
11299           Idx[0] = Constant::getNullValue(Type::Int32Ty);
11300           Idx[1] = NewIdx;
11301           Instruction *NewGEP =
11302             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11303           if (cast<GEPOperator>(&GEP)->isInBounds())
11304             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11305           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11306           // The NewGEP must be pointer typed, so must the old one -> BitCast
11307           return new BitCastInst(NewGEP, GEP.getType());
11308         }
11309       }
11310     }
11311   }
11312   
11313   /// See if we can simplify:
11314   ///   X = bitcast A to B*
11315   ///   Y = gep X, <...constant indices...>
11316   /// into a gep of the original struct.  This is important for SROA and alias
11317   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11318   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11319     if (TD &&
11320         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11321       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11322       // a constant back from EmitGEPOffset.
11323       ConstantInt *OffsetV =
11324                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11325       int64_t Offset = OffsetV->getSExtValue();
11326       
11327       // If this GEP instruction doesn't move the pointer, just replace the GEP
11328       // with a bitcast of the real input to the dest type.
11329       if (Offset == 0) {
11330         // If the bitcast is of an allocation, and the allocation will be
11331         // converted to match the type of the cast, don't touch this.
11332         if (isa<AllocationInst>(BCI->getOperand(0))) {
11333           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11334           if (Instruction *I = visitBitCast(*BCI)) {
11335             if (I != BCI) {
11336               I->takeName(BCI);
11337               BCI->getParent()->getInstList().insert(BCI, I);
11338               ReplaceInstUsesWith(*BCI, I);
11339             }
11340             return &GEP;
11341           }
11342         }
11343         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11344       }
11345       
11346       // Otherwise, if the offset is non-zero, we need to find out if there is a
11347       // field at Offset in 'A's type.  If so, we can pull the cast through the
11348       // GEP.
11349       SmallVector<Value*, 8> NewIndices;
11350       const Type *InTy =
11351         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11352       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11353         Instruction *NGEP =
11354            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11355                                      NewIndices.end());
11356         if (NGEP->getType() == GEP.getType()) return NGEP;
11357         if (cast<GEPOperator>(&GEP)->isInBounds())
11358           cast<GEPOperator>(NGEP)->setIsInBounds(true);
11359         InsertNewInstBefore(NGEP, GEP);
11360         NGEP->takeName(&GEP);
11361         return new BitCastInst(NGEP, GEP.getType());
11362       }
11363     }
11364   }    
11365     
11366   return 0;
11367 }
11368
11369 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11370   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11371   if (AI.isArrayAllocation()) {  // Check C != 1
11372     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11373       const Type *NewTy = 
11374         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11375       AllocationInst *New = 0;
11376
11377       // Create and insert the replacement instruction...
11378       if (isa<MallocInst>(AI))
11379         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11380       else {
11381         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11382         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11383       }
11384
11385       InsertNewInstBefore(New, AI);
11386
11387       // Scan to the end of the allocation instructions, to skip over a block of
11388       // allocas if possible...also skip interleaved debug info
11389       //
11390       BasicBlock::iterator It = New;
11391       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11392
11393       // Now that I is pointing to the first non-allocation-inst in the block,
11394       // insert our getelementptr instruction...
11395       //
11396       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
11397       Value *Idx[2];
11398       Idx[0] = NullIdx;
11399       Idx[1] = NullIdx;
11400       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11401                                            New->getName()+".sub", It);
11402       cast<GEPOperator>(V)->setIsInBounds(true);
11403
11404       // Now make everything use the getelementptr instead of the original
11405       // allocation.
11406       return ReplaceInstUsesWith(AI, V);
11407     } else if (isa<UndefValue>(AI.getArraySize())) {
11408       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11409     }
11410   }
11411
11412   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11413     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11414     // Note that we only do this for alloca's, because malloc should allocate
11415     // and return a unique pointer, even for a zero byte allocation.
11416     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11417       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11418
11419     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11420     if (AI.getAlignment() == 0)
11421       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11422   }
11423
11424   return 0;
11425 }
11426
11427 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11428   Value *Op = FI.getOperand(0);
11429
11430   // free undef -> unreachable.
11431   if (isa<UndefValue>(Op)) {
11432     // Insert a new store to null because we cannot modify the CFG here.
11433     new StoreInst(ConstantInt::getTrue(*Context),
11434            UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11435     return EraseInstFromFunction(FI);
11436   }
11437   
11438   // If we have 'free null' delete the instruction.  This can happen in stl code
11439   // when lots of inlining happens.
11440   if (isa<ConstantPointerNull>(Op))
11441     return EraseInstFromFunction(FI);
11442   
11443   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11444   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11445     FI.setOperand(0, CI->getOperand(0));
11446     return &FI;
11447   }
11448   
11449   // Change free (gep X, 0,0,0,0) into free(X)
11450   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11451     if (GEPI->hasAllZeroIndices()) {
11452       AddToWorkList(GEPI);
11453       FI.setOperand(0, GEPI->getOperand(0));
11454       return &FI;
11455     }
11456   }
11457   
11458   // Change free(malloc) into nothing, if the malloc has a single use.
11459   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11460     if (MI->hasOneUse()) {
11461       EraseInstFromFunction(FI);
11462       return EraseInstFromFunction(*MI);
11463     }
11464
11465   return 0;
11466 }
11467
11468
11469 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11470 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11471                                         const TargetData *TD) {
11472   User *CI = cast<User>(LI.getOperand(0));
11473   Value *CastOp = CI->getOperand(0);
11474   LLVMContext *Context = IC.getContext();
11475
11476   if (TD) {
11477     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11478       // Instead of loading constant c string, use corresponding integer value
11479       // directly if string length is small enough.
11480       std::string Str;
11481       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11482         unsigned len = Str.length();
11483         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11484         unsigned numBits = Ty->getPrimitiveSizeInBits();
11485         // Replace LI with immediate integer store.
11486         if ((numBits >> 3) == len + 1) {
11487           APInt StrVal(numBits, 0);
11488           APInt SingleChar(numBits, 0);
11489           if (TD->isLittleEndian()) {
11490             for (signed i = len-1; i >= 0; i--) {
11491               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11492               StrVal = (StrVal << 8) | SingleChar;
11493             }
11494           } else {
11495             for (unsigned i = 0; i < len; i++) {
11496               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11497               StrVal = (StrVal << 8) | SingleChar;
11498             }
11499             // Append NULL at the end.
11500             SingleChar = 0;
11501             StrVal = (StrVal << 8) | SingleChar;
11502           }
11503           Value *NL = ConstantInt::get(*Context, StrVal);
11504           return IC.ReplaceInstUsesWith(LI, NL);
11505         }
11506       }
11507     }
11508   }
11509
11510   const PointerType *DestTy = cast<PointerType>(CI->getType());
11511   const Type *DestPTy = DestTy->getElementType();
11512   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11513
11514     // If the address spaces don't match, don't eliminate the cast.
11515     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11516       return 0;
11517
11518     const Type *SrcPTy = SrcTy->getElementType();
11519
11520     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11521          isa<VectorType>(DestPTy)) {
11522       // If the source is an array, the code below will not succeed.  Check to
11523       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11524       // constants.
11525       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11526         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11527           if (ASrcTy->getNumElements() != 0) {
11528             Value *Idxs[2];
11529             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11530             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11531             SrcTy = cast<PointerType>(CastOp->getType());
11532             SrcPTy = SrcTy->getElementType();
11533           }
11534
11535       if (IC.getTargetData() &&
11536           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11537             isa<VectorType>(SrcPTy)) &&
11538           // Do not allow turning this into a load of an integer, which is then
11539           // casted to a pointer, this pessimizes pointer analysis a lot.
11540           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11541           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11542                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11543
11544         // Okay, we are casting from one integer or pointer type to another of
11545         // the same size.  Instead of casting the pointer before the load, cast
11546         // the result of the loaded value.
11547         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11548                                                              CI->getName(),
11549                                                          LI.isVolatile()),LI);
11550         // Now cast the result of the load.
11551         return new BitCastInst(NewLoad, LI.getType());
11552       }
11553     }
11554   }
11555   return 0;
11556 }
11557
11558 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11559   Value *Op = LI.getOperand(0);
11560
11561   // Attempt to improve the alignment.
11562   if (TD) {
11563     unsigned KnownAlign =
11564       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11565     if (KnownAlign >
11566         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11567                                   LI.getAlignment()))
11568       LI.setAlignment(KnownAlign);
11569   }
11570
11571   // load (cast X) --> cast (load X) iff safe
11572   if (isa<CastInst>(Op))
11573     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11574       return Res;
11575
11576   // None of the following transforms are legal for volatile loads.
11577   if (LI.isVolatile()) return 0;
11578   
11579   // Do really simple store-to-load forwarding and load CSE, to catch cases
11580   // where there are several consequtive memory accesses to the same location,
11581   // separated by a few arithmetic operations.
11582   BasicBlock::iterator BBI = &LI;
11583   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11584     return ReplaceInstUsesWith(LI, AvailableVal);
11585
11586   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11587     const Value *GEPI0 = GEPI->getOperand(0);
11588     // TODO: Consider a target hook for valid address spaces for this xform.
11589     if (isa<ConstantPointerNull>(GEPI0) &&
11590         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11591       // Insert a new store to null instruction before the load to indicate
11592       // that this code is not reachable.  We do this instead of inserting
11593       // an unreachable instruction directly because we cannot modify the
11594       // CFG.
11595       new StoreInst(UndefValue::get(LI.getType()),
11596                     Constant::getNullValue(Op->getType()), &LI);
11597       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11598     }
11599   } 
11600
11601   if (Constant *C = dyn_cast<Constant>(Op)) {
11602     // load null/undef -> undef
11603     // TODO: Consider a target hook for valid address spaces for this xform.
11604     if (isa<UndefValue>(C) || (C->isNullValue() && 
11605         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11606       // Insert a new store to null instruction before the load to indicate that
11607       // this code is not reachable.  We do this instead of inserting an
11608       // unreachable instruction directly because we cannot modify the CFG.
11609       new StoreInst(UndefValue::get(LI.getType()),
11610                     Constant::getNullValue(Op->getType()), &LI);
11611       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11612     }
11613
11614     // Instcombine load (constant global) into the value loaded.
11615     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11616       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11617         return ReplaceInstUsesWith(LI, GV->getInitializer());
11618
11619     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11620     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11621       if (CE->getOpcode() == Instruction::GetElementPtr) {
11622         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11623           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11624             if (Constant *V = 
11625                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11626                                                       *Context))
11627               return ReplaceInstUsesWith(LI, V);
11628         if (CE->getOperand(0)->isNullValue()) {
11629           // Insert a new store to null instruction before the load to indicate
11630           // that this code is not reachable.  We do this instead of inserting
11631           // an unreachable instruction directly because we cannot modify the
11632           // CFG.
11633           new StoreInst(UndefValue::get(LI.getType()),
11634                         Constant::getNullValue(Op->getType()), &LI);
11635           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11636         }
11637
11638       } else if (CE->isCast()) {
11639         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11640           return Res;
11641       }
11642     }
11643   }
11644     
11645   // If this load comes from anywhere in a constant global, and if the global
11646   // is all undef or zero, we know what it loads.
11647   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11648     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11649       if (GV->getInitializer()->isNullValue())
11650         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11651       else if (isa<UndefValue>(GV->getInitializer()))
11652         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11653     }
11654   }
11655
11656   if (Op->hasOneUse()) {
11657     // Change select and PHI nodes to select values instead of addresses: this
11658     // helps alias analysis out a lot, allows many others simplifications, and
11659     // exposes redundancy in the code.
11660     //
11661     // Note that we cannot do the transformation unless we know that the
11662     // introduced loads cannot trap!  Something like this is valid as long as
11663     // the condition is always false: load (select bool %C, int* null, int* %G),
11664     // but it would not be valid if we transformed it to load from null
11665     // unconditionally.
11666     //
11667     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11668       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11669       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11670           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11671         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11672                                      SI->getOperand(1)->getName()+".val"), LI);
11673         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11674                                      SI->getOperand(2)->getName()+".val"), LI);
11675         return SelectInst::Create(SI->getCondition(), V1, V2);
11676       }
11677
11678       // load (select (cond, null, P)) -> load P
11679       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11680         if (C->isNullValue()) {
11681           LI.setOperand(0, SI->getOperand(2));
11682           return &LI;
11683         }
11684
11685       // load (select (cond, P, null)) -> load P
11686       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11687         if (C->isNullValue()) {
11688           LI.setOperand(0, SI->getOperand(1));
11689           return &LI;
11690         }
11691     }
11692   }
11693   return 0;
11694 }
11695
11696 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11697 /// when possible.  This makes it generally easy to do alias analysis and/or
11698 /// SROA/mem2reg of the memory object.
11699 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11700   User *CI = cast<User>(SI.getOperand(1));
11701   Value *CastOp = CI->getOperand(0);
11702
11703   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11704   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11705   if (SrcTy == 0) return 0;
11706   
11707   const Type *SrcPTy = SrcTy->getElementType();
11708
11709   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11710     return 0;
11711   
11712   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11713   /// to its first element.  This allows us to handle things like:
11714   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11715   /// on 32-bit hosts.
11716   SmallVector<Value*, 4> NewGEPIndices;
11717   
11718   // If the source is an array, the code below will not succeed.  Check to
11719   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11720   // constants.
11721   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11722     // Index through pointer.
11723     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11724     NewGEPIndices.push_back(Zero);
11725     
11726     while (1) {
11727       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11728         if (!STy->getNumElements()) /* Struct can be empty {} */
11729           break;
11730         NewGEPIndices.push_back(Zero);
11731         SrcPTy = STy->getElementType(0);
11732       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11733         NewGEPIndices.push_back(Zero);
11734         SrcPTy = ATy->getElementType();
11735       } else {
11736         break;
11737       }
11738     }
11739     
11740     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11741   }
11742
11743   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11744     return 0;
11745   
11746   // If the pointers point into different address spaces or if they point to
11747   // values with different sizes, we can't do the transformation.
11748   if (!IC.getTargetData() ||
11749       SrcTy->getAddressSpace() != 
11750         cast<PointerType>(CI->getType())->getAddressSpace() ||
11751       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11752       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11753     return 0;
11754
11755   // Okay, we are casting from one integer or pointer type to another of
11756   // the same size.  Instead of casting the pointer before 
11757   // the store, cast the value to be stored.
11758   Value *NewCast;
11759   Value *SIOp0 = SI.getOperand(0);
11760   Instruction::CastOps opcode = Instruction::BitCast;
11761   const Type* CastSrcTy = SIOp0->getType();
11762   const Type* CastDstTy = SrcPTy;
11763   if (isa<PointerType>(CastDstTy)) {
11764     if (CastSrcTy->isInteger())
11765       opcode = Instruction::IntToPtr;
11766   } else if (isa<IntegerType>(CastDstTy)) {
11767     if (isa<PointerType>(SIOp0->getType()))
11768       opcode = Instruction::PtrToInt;
11769   }
11770   
11771   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11772   // emit a GEP to index into its first field.
11773   if (!NewGEPIndices.empty()) {
11774     if (Constant *C = dyn_cast<Constant>(CastOp))
11775       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11776                                               NewGEPIndices.size());
11777     else
11778       CastOp = IC.InsertNewInstBefore(
11779               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11780                                         NewGEPIndices.end()), SI);
11781     cast<GEPOperator>(CastOp)->setIsInBounds(true);
11782   }
11783   
11784   if (Constant *C = dyn_cast<Constant>(SIOp0))
11785     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11786   else
11787     NewCast = IC.InsertNewInstBefore(
11788       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11789       SI);
11790   return new StoreInst(NewCast, CastOp);
11791 }
11792
11793 /// equivalentAddressValues - Test if A and B will obviously have the same
11794 /// value. This includes recognizing that %t0 and %t1 will have the same
11795 /// value in code like this:
11796 ///   %t0 = getelementptr \@a, 0, 3
11797 ///   store i32 0, i32* %t0
11798 ///   %t1 = getelementptr \@a, 0, 3
11799 ///   %t2 = load i32* %t1
11800 ///
11801 static bool equivalentAddressValues(Value *A, Value *B) {
11802   // Test if the values are trivially equivalent.
11803   if (A == B) return true;
11804   
11805   // Test if the values come form identical arithmetic instructions.
11806   if (isa<BinaryOperator>(A) ||
11807       isa<CastInst>(A) ||
11808       isa<PHINode>(A) ||
11809       isa<GetElementPtrInst>(A))
11810     if (Instruction *BI = dyn_cast<Instruction>(B))
11811       if (cast<Instruction>(A)->isIdenticalTo(BI))
11812         return true;
11813   
11814   // Otherwise they may not be equivalent.
11815   return false;
11816 }
11817
11818 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11819 // return the llvm.dbg.declare.
11820 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11821   if (!V->hasNUses(2))
11822     return 0;
11823   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11824        UI != E; ++UI) {
11825     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11826       return DI;
11827     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11828       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11829         return DI;
11830       }
11831   }
11832   return 0;
11833 }
11834
11835 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11836   Value *Val = SI.getOperand(0);
11837   Value *Ptr = SI.getOperand(1);
11838
11839   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11840     EraseInstFromFunction(SI);
11841     ++NumCombined;
11842     return 0;
11843   }
11844   
11845   // If the RHS is an alloca with a single use, zapify the store, making the
11846   // alloca dead.
11847   // If the RHS is an alloca with a two uses, the other one being a 
11848   // llvm.dbg.declare, zapify the store and the declare, making the
11849   // alloca dead.  We must do this to prevent declare's from affecting
11850   // codegen.
11851   if (!SI.isVolatile()) {
11852     if (Ptr->hasOneUse()) {
11853       if (isa<AllocaInst>(Ptr)) {
11854         EraseInstFromFunction(SI);
11855         ++NumCombined;
11856         return 0;
11857       }
11858       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11859         if (isa<AllocaInst>(GEP->getOperand(0))) {
11860           if (GEP->getOperand(0)->hasOneUse()) {
11861             EraseInstFromFunction(SI);
11862             ++NumCombined;
11863             return 0;
11864           }
11865           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11866             EraseInstFromFunction(*DI);
11867             EraseInstFromFunction(SI);
11868             ++NumCombined;
11869             return 0;
11870           }
11871         }
11872       }
11873     }
11874     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11875       EraseInstFromFunction(*DI);
11876       EraseInstFromFunction(SI);
11877       ++NumCombined;
11878       return 0;
11879     }
11880   }
11881
11882   // Attempt to improve the alignment.
11883   if (TD) {
11884     unsigned KnownAlign =
11885       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11886     if (KnownAlign >
11887         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11888                                   SI.getAlignment()))
11889       SI.setAlignment(KnownAlign);
11890   }
11891
11892   // Do really simple DSE, to catch cases where there are several consecutive
11893   // stores to the same location, separated by a few arithmetic operations. This
11894   // situation often occurs with bitfield accesses.
11895   BasicBlock::iterator BBI = &SI;
11896   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11897        --ScanInsts) {
11898     --BBI;
11899     // Don't count debug info directives, lest they affect codegen,
11900     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11901     // It is necessary for correctness to skip those that feed into a
11902     // llvm.dbg.declare, as these are not present when debugging is off.
11903     if (isa<DbgInfoIntrinsic>(BBI) ||
11904         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11905       ScanInsts++;
11906       continue;
11907     }    
11908     
11909     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11910       // Prev store isn't volatile, and stores to the same location?
11911       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11912                                                           SI.getOperand(1))) {
11913         ++NumDeadStore;
11914         ++BBI;
11915         EraseInstFromFunction(*PrevSI);
11916         continue;
11917       }
11918       break;
11919     }
11920     
11921     // If this is a load, we have to stop.  However, if the loaded value is from
11922     // the pointer we're loading and is producing the pointer we're storing,
11923     // then *this* store is dead (X = load P; store X -> P).
11924     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11925       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11926           !SI.isVolatile()) {
11927         EraseInstFromFunction(SI);
11928         ++NumCombined;
11929         return 0;
11930       }
11931       // Otherwise, this is a load from some other location.  Stores before it
11932       // may not be dead.
11933       break;
11934     }
11935     
11936     // Don't skip over loads or things that can modify memory.
11937     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11938       break;
11939   }
11940   
11941   
11942   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11943
11944   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11945   if (isa<ConstantPointerNull>(Ptr) &&
11946       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11947     if (!isa<UndefValue>(Val)) {
11948       SI.setOperand(0, UndefValue::get(Val->getType()));
11949       if (Instruction *U = dyn_cast<Instruction>(Val))
11950         AddToWorkList(U);  // Dropped a use.
11951       ++NumCombined;
11952     }
11953     return 0;  // Do not modify these!
11954   }
11955
11956   // store undef, Ptr -> noop
11957   if (isa<UndefValue>(Val)) {
11958     EraseInstFromFunction(SI);
11959     ++NumCombined;
11960     return 0;
11961   }
11962
11963   // If the pointer destination is a cast, see if we can fold the cast into the
11964   // source instead.
11965   if (isa<CastInst>(Ptr))
11966     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11967       return Res;
11968   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11969     if (CE->isCast())
11970       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11971         return Res;
11972
11973   
11974   // If this store is the last instruction in the basic block (possibly
11975   // excepting debug info instructions and the pointer bitcasts that feed
11976   // into them), and if the block ends with an unconditional branch, try
11977   // to move it to the successor block.
11978   BBI = &SI; 
11979   do {
11980     ++BBI;
11981   } while (isa<DbgInfoIntrinsic>(BBI) ||
11982            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11983   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11984     if (BI->isUnconditional())
11985       if (SimplifyStoreAtEndOfBlock(SI))
11986         return 0;  // xform done!
11987   
11988   return 0;
11989 }
11990
11991 /// SimplifyStoreAtEndOfBlock - Turn things like:
11992 ///   if () { *P = v1; } else { *P = v2 }
11993 /// into a phi node with a store in the successor.
11994 ///
11995 /// Simplify things like:
11996 ///   *P = v1; if () { *P = v2; }
11997 /// into a phi node with a store in the successor.
11998 ///
11999 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12000   BasicBlock *StoreBB = SI.getParent();
12001   
12002   // Check to see if the successor block has exactly two incoming edges.  If
12003   // so, see if the other predecessor contains a store to the same location.
12004   // if so, insert a PHI node (if needed) and move the stores down.
12005   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12006   
12007   // Determine whether Dest has exactly two predecessors and, if so, compute
12008   // the other predecessor.
12009   pred_iterator PI = pred_begin(DestBB);
12010   BasicBlock *OtherBB = 0;
12011   if (*PI != StoreBB)
12012     OtherBB = *PI;
12013   ++PI;
12014   if (PI == pred_end(DestBB))
12015     return false;
12016   
12017   if (*PI != StoreBB) {
12018     if (OtherBB)
12019       return false;
12020     OtherBB = *PI;
12021   }
12022   if (++PI != pred_end(DestBB))
12023     return false;
12024
12025   // Bail out if all the relevant blocks aren't distinct (this can happen,
12026   // for example, if SI is in an infinite loop)
12027   if (StoreBB == DestBB || OtherBB == DestBB)
12028     return false;
12029
12030   // Verify that the other block ends in a branch and is not otherwise empty.
12031   BasicBlock::iterator BBI = OtherBB->getTerminator();
12032   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12033   if (!OtherBr || BBI == OtherBB->begin())
12034     return false;
12035   
12036   // If the other block ends in an unconditional branch, check for the 'if then
12037   // else' case.  there is an instruction before the branch.
12038   StoreInst *OtherStore = 0;
12039   if (OtherBr->isUnconditional()) {
12040     --BBI;
12041     // Skip over debugging info.
12042     while (isa<DbgInfoIntrinsic>(BBI) ||
12043            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12044       if (BBI==OtherBB->begin())
12045         return false;
12046       --BBI;
12047     }
12048     // If this isn't a store, or isn't a store to the same location, bail out.
12049     OtherStore = dyn_cast<StoreInst>(BBI);
12050     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12051       return false;
12052   } else {
12053     // Otherwise, the other block ended with a conditional branch. If one of the
12054     // destinations is StoreBB, then we have the if/then case.
12055     if (OtherBr->getSuccessor(0) != StoreBB && 
12056         OtherBr->getSuccessor(1) != StoreBB)
12057       return false;
12058     
12059     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12060     // if/then triangle.  See if there is a store to the same ptr as SI that
12061     // lives in OtherBB.
12062     for (;; --BBI) {
12063       // Check to see if we find the matching store.
12064       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12065         if (OtherStore->getOperand(1) != SI.getOperand(1))
12066           return false;
12067         break;
12068       }
12069       // If we find something that may be using or overwriting the stored
12070       // value, or if we run out of instructions, we can't do the xform.
12071       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12072           BBI == OtherBB->begin())
12073         return false;
12074     }
12075     
12076     // In order to eliminate the store in OtherBr, we have to
12077     // make sure nothing reads or overwrites the stored value in
12078     // StoreBB.
12079     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12080       // FIXME: This should really be AA driven.
12081       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12082         return false;
12083     }
12084   }
12085   
12086   // Insert a PHI node now if we need it.
12087   Value *MergedVal = OtherStore->getOperand(0);
12088   if (MergedVal != SI.getOperand(0)) {
12089     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12090     PN->reserveOperandSpace(2);
12091     PN->addIncoming(SI.getOperand(0), SI.getParent());
12092     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12093     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12094   }
12095   
12096   // Advance to a place where it is safe to insert the new store and
12097   // insert it.
12098   BBI = DestBB->getFirstNonPHI();
12099   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12100                                     OtherStore->isVolatile()), *BBI);
12101   
12102   // Nuke the old stores.
12103   EraseInstFromFunction(SI);
12104   EraseInstFromFunction(*OtherStore);
12105   ++NumCombined;
12106   return true;
12107 }
12108
12109
12110 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12111   // Change br (not X), label True, label False to: br X, label False, True
12112   Value *X = 0;
12113   BasicBlock *TrueDest;
12114   BasicBlock *FalseDest;
12115   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12116       !isa<Constant>(X)) {
12117     // Swap Destinations and condition...
12118     BI.setCondition(X);
12119     BI.setSuccessor(0, FalseDest);
12120     BI.setSuccessor(1, TrueDest);
12121     return &BI;
12122   }
12123
12124   // Cannonicalize fcmp_one -> fcmp_oeq
12125   FCmpInst::Predicate FPred; Value *Y;
12126   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12127                              TrueDest, FalseDest), *Context))
12128     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12129          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12130       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12131       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12132       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12133       NewSCC->takeName(I);
12134       // Swap Destinations and condition...
12135       BI.setCondition(NewSCC);
12136       BI.setSuccessor(0, FalseDest);
12137       BI.setSuccessor(1, TrueDest);
12138       RemoveFromWorkList(I);
12139       I->eraseFromParent();
12140       AddToWorkList(NewSCC);
12141       return &BI;
12142     }
12143
12144   // Cannonicalize icmp_ne -> icmp_eq
12145   ICmpInst::Predicate IPred;
12146   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12147                       TrueDest, FalseDest), *Context))
12148     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12149          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12150          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12151       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12152       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12153       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12154       NewSCC->takeName(I);
12155       // Swap Destinations and condition...
12156       BI.setCondition(NewSCC);
12157       BI.setSuccessor(0, FalseDest);
12158       BI.setSuccessor(1, TrueDest);
12159       RemoveFromWorkList(I);
12160       I->eraseFromParent();;
12161       AddToWorkList(NewSCC);
12162       return &BI;
12163     }
12164
12165   return 0;
12166 }
12167
12168 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12169   Value *Cond = SI.getCondition();
12170   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12171     if (I->getOpcode() == Instruction::Add)
12172       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12173         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12174         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12175           SI.setOperand(i,
12176                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12177                                                 AddRHS));
12178         SI.setOperand(0, I->getOperand(0));
12179         AddToWorkList(I);
12180         return &SI;
12181       }
12182   }
12183   return 0;
12184 }
12185
12186 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12187   Value *Agg = EV.getAggregateOperand();
12188
12189   if (!EV.hasIndices())
12190     return ReplaceInstUsesWith(EV, Agg);
12191
12192   if (Constant *C = dyn_cast<Constant>(Agg)) {
12193     if (isa<UndefValue>(C))
12194       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12195       
12196     if (isa<ConstantAggregateZero>(C))
12197       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12198
12199     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12200       // Extract the element indexed by the first index out of the constant
12201       Value *V = C->getOperand(*EV.idx_begin());
12202       if (EV.getNumIndices() > 1)
12203         // Extract the remaining indices out of the constant indexed by the
12204         // first index
12205         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12206       else
12207         return ReplaceInstUsesWith(EV, V);
12208     }
12209     return 0; // Can't handle other constants
12210   } 
12211   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12212     // We're extracting from an insertvalue instruction, compare the indices
12213     const unsigned *exti, *exte, *insi, *inse;
12214     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12215          exte = EV.idx_end(), inse = IV->idx_end();
12216          exti != exte && insi != inse;
12217          ++exti, ++insi) {
12218       if (*insi != *exti)
12219         // The insert and extract both reference distinctly different elements.
12220         // This means the extract is not influenced by the insert, and we can
12221         // replace the aggregate operand of the extract with the aggregate
12222         // operand of the insert. i.e., replace
12223         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12224         // %E = extractvalue { i32, { i32 } } %I, 0
12225         // with
12226         // %E = extractvalue { i32, { i32 } } %A, 0
12227         return ExtractValueInst::Create(IV->getAggregateOperand(),
12228                                         EV.idx_begin(), EV.idx_end());
12229     }
12230     if (exti == exte && insi == inse)
12231       // Both iterators are at the end: Index lists are identical. Replace
12232       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12233       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12234       // with "i32 42"
12235       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12236     if (exti == exte) {
12237       // The extract list is a prefix of the insert list. i.e. replace
12238       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12239       // %E = extractvalue { i32, { i32 } } %I, 1
12240       // with
12241       // %X = extractvalue { i32, { i32 } } %A, 1
12242       // %E = insertvalue { i32 } %X, i32 42, 0
12243       // by switching the order of the insert and extract (though the
12244       // insertvalue should be left in, since it may have other uses).
12245       Value *NewEV = InsertNewInstBefore(
12246         ExtractValueInst::Create(IV->getAggregateOperand(),
12247                                  EV.idx_begin(), EV.idx_end()),
12248         EV);
12249       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12250                                      insi, inse);
12251     }
12252     if (insi == inse)
12253       // The insert list is a prefix of the extract list
12254       // We can simply remove the common indices from the extract and make it
12255       // operate on the inserted value instead of the insertvalue result.
12256       // i.e., replace
12257       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12258       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12259       // with
12260       // %E extractvalue { i32 } { i32 42 }, 0
12261       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12262                                       exti, exte);
12263   }
12264   // Can't simplify extracts from other values. Note that nested extracts are
12265   // already simplified implicitely by the above (extract ( extract (insert) )
12266   // will be translated into extract ( insert ( extract ) ) first and then just
12267   // the value inserted, if appropriate).
12268   return 0;
12269 }
12270
12271 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12272 /// is to leave as a vector operation.
12273 static bool CheapToScalarize(Value *V, bool isConstant) {
12274   if (isa<ConstantAggregateZero>(V)) 
12275     return true;
12276   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12277     if (isConstant) return true;
12278     // If all elts are the same, we can extract.
12279     Constant *Op0 = C->getOperand(0);
12280     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12281       if (C->getOperand(i) != Op0)
12282         return false;
12283     return true;
12284   }
12285   Instruction *I = dyn_cast<Instruction>(V);
12286   if (!I) return false;
12287   
12288   // Insert element gets simplified to the inserted element or is deleted if
12289   // this is constant idx extract element and its a constant idx insertelt.
12290   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12291       isa<ConstantInt>(I->getOperand(2)))
12292     return true;
12293   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12294     return true;
12295   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12296     if (BO->hasOneUse() &&
12297         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12298          CheapToScalarize(BO->getOperand(1), isConstant)))
12299       return true;
12300   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12301     if (CI->hasOneUse() &&
12302         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12303          CheapToScalarize(CI->getOperand(1), isConstant)))
12304       return true;
12305   
12306   return false;
12307 }
12308
12309 /// Read and decode a shufflevector mask.
12310 ///
12311 /// It turns undef elements into values that are larger than the number of
12312 /// elements in the input.
12313 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12314   unsigned NElts = SVI->getType()->getNumElements();
12315   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12316     return std::vector<unsigned>(NElts, 0);
12317   if (isa<UndefValue>(SVI->getOperand(2)))
12318     return std::vector<unsigned>(NElts, 2*NElts);
12319
12320   std::vector<unsigned> Result;
12321   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12322   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12323     if (isa<UndefValue>(*i))
12324       Result.push_back(NElts*2);  // undef -> 8
12325     else
12326       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12327   return Result;
12328 }
12329
12330 /// FindScalarElement - Given a vector and an element number, see if the scalar
12331 /// value is already around as a register, for example if it were inserted then
12332 /// extracted from the vector.
12333 static Value *FindScalarElement(Value *V, unsigned EltNo,
12334                                 LLVMContext *Context) {
12335   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12336   const VectorType *PTy = cast<VectorType>(V->getType());
12337   unsigned Width = PTy->getNumElements();
12338   if (EltNo >= Width)  // Out of range access.
12339     return UndefValue::get(PTy->getElementType());
12340   
12341   if (isa<UndefValue>(V))
12342     return UndefValue::get(PTy->getElementType());
12343   else if (isa<ConstantAggregateZero>(V))
12344     return Constant::getNullValue(PTy->getElementType());
12345   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12346     return CP->getOperand(EltNo);
12347   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12348     // If this is an insert to a variable element, we don't know what it is.
12349     if (!isa<ConstantInt>(III->getOperand(2))) 
12350       return 0;
12351     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12352     
12353     // If this is an insert to the element we are looking for, return the
12354     // inserted value.
12355     if (EltNo == IIElt) 
12356       return III->getOperand(1);
12357     
12358     // Otherwise, the insertelement doesn't modify the value, recurse on its
12359     // vector input.
12360     return FindScalarElement(III->getOperand(0), EltNo, Context);
12361   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12362     unsigned LHSWidth =
12363       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12364     unsigned InEl = getShuffleMask(SVI)[EltNo];
12365     if (InEl < LHSWidth)
12366       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12367     else if (InEl < LHSWidth*2)
12368       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12369     else
12370       return UndefValue::get(PTy->getElementType());
12371   }
12372   
12373   // Otherwise, we don't know.
12374   return 0;
12375 }
12376
12377 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12378   // If vector val is undef, replace extract with scalar undef.
12379   if (isa<UndefValue>(EI.getOperand(0)))
12380     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12381
12382   // If vector val is constant 0, replace extract with scalar 0.
12383   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12384     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12385   
12386   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12387     // If vector val is constant with all elements the same, replace EI with
12388     // that element. When the elements are not identical, we cannot replace yet
12389     // (we do that below, but only when the index is constant).
12390     Constant *op0 = C->getOperand(0);
12391     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12392       if (C->getOperand(i) != op0) {
12393         op0 = 0; 
12394         break;
12395       }
12396     if (op0)
12397       return ReplaceInstUsesWith(EI, op0);
12398   }
12399   
12400   // If extracting a specified index from the vector, see if we can recursively
12401   // find a previously computed scalar that was inserted into the vector.
12402   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12403     unsigned IndexVal = IdxC->getZExtValue();
12404     unsigned VectorWidth = 
12405       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12406       
12407     // If this is extracting an invalid index, turn this into undef, to avoid
12408     // crashing the code below.
12409     if (IndexVal >= VectorWidth)
12410       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12411     
12412     // This instruction only demands the single element from the input vector.
12413     // If the input vector has a single use, simplify it based on this use
12414     // property.
12415     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12416       APInt UndefElts(VectorWidth, 0);
12417       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12418       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12419                                                 DemandedMask, UndefElts)) {
12420         EI.setOperand(0, V);
12421         return &EI;
12422       }
12423     }
12424     
12425     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12426       return ReplaceInstUsesWith(EI, Elt);
12427     
12428     // If the this extractelement is directly using a bitcast from a vector of
12429     // the same number of elements, see if we can find the source element from
12430     // it.  In this case, we will end up needing to bitcast the scalars.
12431     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12432       if (const VectorType *VT = 
12433               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12434         if (VT->getNumElements() == VectorWidth)
12435           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12436                                              IndexVal, Context))
12437             return new BitCastInst(Elt, EI.getType());
12438     }
12439   }
12440   
12441   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12442     if (I->hasOneUse()) {
12443       // Push extractelement into predecessor operation if legal and
12444       // profitable to do so
12445       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12446         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12447         if (CheapToScalarize(BO, isConstantElt)) {
12448           ExtractElementInst *newEI0 = 
12449             ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
12450                                    EI.getName()+".lhs");
12451           ExtractElementInst *newEI1 =
12452             ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
12453                                    EI.getName()+".rhs");
12454           InsertNewInstBefore(newEI0, EI);
12455           InsertNewInstBefore(newEI1, EI);
12456           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12457         }
12458       } else if (isa<LoadInst>(I)) {
12459         unsigned AS = 
12460           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12461         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12462                                   PointerType::get(EI.getType(), AS),EI);
12463         GetElementPtrInst *GEP =
12464           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12465         cast<GEPOperator>(GEP)->setIsInBounds(true);
12466         InsertNewInstBefore(GEP, EI);
12467         return new LoadInst(GEP);
12468       }
12469     }
12470     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12471       // Extracting the inserted element?
12472       if (IE->getOperand(2) == EI.getOperand(1))
12473         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12474       // If the inserted and extracted elements are constants, they must not
12475       // be the same value, extract from the pre-inserted value instead.
12476       if (isa<Constant>(IE->getOperand(2)) &&
12477           isa<Constant>(EI.getOperand(1))) {
12478         AddUsesToWorkList(EI);
12479         EI.setOperand(0, IE->getOperand(0));
12480         return &EI;
12481       }
12482     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12483       // If this is extracting an element from a shufflevector, figure out where
12484       // it came from and extract from the appropriate input element instead.
12485       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12486         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12487         Value *Src;
12488         unsigned LHSWidth =
12489           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12490
12491         if (SrcIdx < LHSWidth)
12492           Src = SVI->getOperand(0);
12493         else if (SrcIdx < LHSWidth*2) {
12494           SrcIdx -= LHSWidth;
12495           Src = SVI->getOperand(1);
12496         } else {
12497           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12498         }
12499         return ExtractElementInst::Create(Src,
12500                          ConstantInt::get(Type::Int32Ty, SrcIdx, false));
12501       }
12502     }
12503     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12504   }
12505   return 0;
12506 }
12507
12508 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12509 /// elements from either LHS or RHS, return the shuffle mask and true. 
12510 /// Otherwise, return false.
12511 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12512                                          std::vector<Constant*> &Mask,
12513                                          LLVMContext *Context) {
12514   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12515          "Invalid CollectSingleShuffleElements");
12516   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12517
12518   if (isa<UndefValue>(V)) {
12519     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12520     return true;
12521   } else if (V == LHS) {
12522     for (unsigned i = 0; i != NumElts; ++i)
12523       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12524     return true;
12525   } else if (V == RHS) {
12526     for (unsigned i = 0; i != NumElts; ++i)
12527       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12528     return true;
12529   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12530     // If this is an insert of an extract from some other vector, include it.
12531     Value *VecOp    = IEI->getOperand(0);
12532     Value *ScalarOp = IEI->getOperand(1);
12533     Value *IdxOp    = IEI->getOperand(2);
12534     
12535     if (!isa<ConstantInt>(IdxOp))
12536       return false;
12537     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12538     
12539     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12540       // Okay, we can handle this if the vector we are insertinting into is
12541       // transitively ok.
12542       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12543         // If so, update the mask to reflect the inserted undef.
12544         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12545         return true;
12546       }      
12547     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12548       if (isa<ConstantInt>(EI->getOperand(1)) &&
12549           EI->getOperand(0)->getType() == V->getType()) {
12550         unsigned ExtractedIdx =
12551           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12552         
12553         // This must be extracting from either LHS or RHS.
12554         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12555           // Okay, we can handle this if the vector we are insertinting into is
12556           // transitively ok.
12557           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12558             // If so, update the mask to reflect the inserted value.
12559             if (EI->getOperand(0) == LHS) {
12560               Mask[InsertedIdx % NumElts] = 
12561                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12562             } else {
12563               assert(EI->getOperand(0) == RHS);
12564               Mask[InsertedIdx % NumElts] = 
12565                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12566               
12567             }
12568             return true;
12569           }
12570         }
12571       }
12572     }
12573   }
12574   // TODO: Handle shufflevector here!
12575   
12576   return false;
12577 }
12578
12579 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12580 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12581 /// that computes V and the LHS value of the shuffle.
12582 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12583                                      Value *&RHS, LLVMContext *Context) {
12584   assert(isa<VectorType>(V->getType()) && 
12585          (RHS == 0 || V->getType() == RHS->getType()) &&
12586          "Invalid shuffle!");
12587   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12588
12589   if (isa<UndefValue>(V)) {
12590     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12591     return V;
12592   } else if (isa<ConstantAggregateZero>(V)) {
12593     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12594     return V;
12595   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12596     // If this is an insert of an extract from some other vector, include it.
12597     Value *VecOp    = IEI->getOperand(0);
12598     Value *ScalarOp = IEI->getOperand(1);
12599     Value *IdxOp    = IEI->getOperand(2);
12600     
12601     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12602       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12603           EI->getOperand(0)->getType() == V->getType()) {
12604         unsigned ExtractedIdx =
12605           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12606         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12607         
12608         // Either the extracted from or inserted into vector must be RHSVec,
12609         // otherwise we'd end up with a shuffle of three inputs.
12610         if (EI->getOperand(0) == RHS || RHS == 0) {
12611           RHS = EI->getOperand(0);
12612           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12613           Mask[InsertedIdx % NumElts] = 
12614             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12615           return V;
12616         }
12617         
12618         if (VecOp == RHS) {
12619           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12620                                             RHS, Context);
12621           // Everything but the extracted element is replaced with the RHS.
12622           for (unsigned i = 0; i != NumElts; ++i) {
12623             if (i != InsertedIdx)
12624               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12625           }
12626           return V;
12627         }
12628         
12629         // If this insertelement is a chain that comes from exactly these two
12630         // vectors, return the vector and the effective shuffle.
12631         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12632                                          Context))
12633           return EI->getOperand(0);
12634         
12635       }
12636     }
12637   }
12638   // TODO: Handle shufflevector here!
12639   
12640   // Otherwise, can't do anything fancy.  Return an identity vector.
12641   for (unsigned i = 0; i != NumElts; ++i)
12642     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12643   return V;
12644 }
12645
12646 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12647   Value *VecOp    = IE.getOperand(0);
12648   Value *ScalarOp = IE.getOperand(1);
12649   Value *IdxOp    = IE.getOperand(2);
12650   
12651   // Inserting an undef or into an undefined place, remove this.
12652   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12653     ReplaceInstUsesWith(IE, VecOp);
12654   
12655   // If the inserted element was extracted from some other vector, and if the 
12656   // indexes are constant, try to turn this into a shufflevector operation.
12657   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12658     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12659         EI->getOperand(0)->getType() == IE.getType()) {
12660       unsigned NumVectorElts = IE.getType()->getNumElements();
12661       unsigned ExtractedIdx =
12662         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12663       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12664       
12665       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12666         return ReplaceInstUsesWith(IE, VecOp);
12667       
12668       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12669         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12670       
12671       // If we are extracting a value from a vector, then inserting it right
12672       // back into the same place, just use the input vector.
12673       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12674         return ReplaceInstUsesWith(IE, VecOp);      
12675       
12676       // We could theoretically do this for ANY input.  However, doing so could
12677       // turn chains of insertelement instructions into a chain of shufflevector
12678       // instructions, and right now we do not merge shufflevectors.  As such,
12679       // only do this in a situation where it is clear that there is benefit.
12680       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12681         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12682         // the values of VecOp, except then one read from EIOp0.
12683         // Build a new shuffle mask.
12684         std::vector<Constant*> Mask;
12685         if (isa<UndefValue>(VecOp))
12686           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12687         else {
12688           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12689           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12690                                                        NumVectorElts));
12691         } 
12692         Mask[InsertedIdx] = 
12693                            ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12694         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12695                                      ConstantVector::get(Mask));
12696       }
12697       
12698       // If this insertelement isn't used by some other insertelement, turn it
12699       // (and any insertelements it points to), into one big shuffle.
12700       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12701         std::vector<Constant*> Mask;
12702         Value *RHS = 0;
12703         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12704         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12705         // We now have a shuffle of LHS, RHS, Mask.
12706         return new ShuffleVectorInst(LHS, RHS,
12707                                      ConstantVector::get(Mask));
12708       }
12709     }
12710   }
12711
12712   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12713   APInt UndefElts(VWidth, 0);
12714   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12715   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12716     return &IE;
12717
12718   return 0;
12719 }
12720
12721
12722 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12723   Value *LHS = SVI.getOperand(0);
12724   Value *RHS = SVI.getOperand(1);
12725   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12726
12727   bool MadeChange = false;
12728
12729   // Undefined shuffle mask -> undefined value.
12730   if (isa<UndefValue>(SVI.getOperand(2)))
12731     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12732
12733   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12734
12735   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12736     return 0;
12737
12738   APInt UndefElts(VWidth, 0);
12739   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12740   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12741     LHS = SVI.getOperand(0);
12742     RHS = SVI.getOperand(1);
12743     MadeChange = true;
12744   }
12745   
12746   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12747   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12748   if (LHS == RHS || isa<UndefValue>(LHS)) {
12749     if (isa<UndefValue>(LHS) && LHS == RHS) {
12750       // shuffle(undef,undef,mask) -> undef.
12751       return ReplaceInstUsesWith(SVI, LHS);
12752     }
12753     
12754     // Remap any references to RHS to use LHS.
12755     std::vector<Constant*> Elts;
12756     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12757       if (Mask[i] >= 2*e)
12758         Elts.push_back(UndefValue::get(Type::Int32Ty));
12759       else {
12760         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12761             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12762           Mask[i] = 2*e;     // Turn into undef.
12763           Elts.push_back(UndefValue::get(Type::Int32Ty));
12764         } else {
12765           Mask[i] = Mask[i] % e;  // Force to LHS.
12766           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12767         }
12768       }
12769     }
12770     SVI.setOperand(0, SVI.getOperand(1));
12771     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12772     SVI.setOperand(2, ConstantVector::get(Elts));
12773     LHS = SVI.getOperand(0);
12774     RHS = SVI.getOperand(1);
12775     MadeChange = true;
12776   }
12777   
12778   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12779   bool isLHSID = true, isRHSID = true;
12780     
12781   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12782     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12783     // Is this an identity shuffle of the LHS value?
12784     isLHSID &= (Mask[i] == i);
12785       
12786     // Is this an identity shuffle of the RHS value?
12787     isRHSID &= (Mask[i]-e == i);
12788   }
12789
12790   // Eliminate identity shuffles.
12791   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12792   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12793   
12794   // If the LHS is a shufflevector itself, see if we can combine it with this
12795   // one without producing an unusual shuffle.  Here we are really conservative:
12796   // we are absolutely afraid of producing a shuffle mask not in the input
12797   // program, because the code gen may not be smart enough to turn a merged
12798   // shuffle into two specific shuffles: it may produce worse code.  As such,
12799   // we only merge two shuffles if the result is one of the two input shuffle
12800   // masks.  In this case, merging the shuffles just removes one instruction,
12801   // which we know is safe.  This is good for things like turning:
12802   // (splat(splat)) -> splat.
12803   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12804     if (isa<UndefValue>(RHS)) {
12805       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12806
12807       std::vector<unsigned> NewMask;
12808       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12809         if (Mask[i] >= 2*e)
12810           NewMask.push_back(2*e);
12811         else
12812           NewMask.push_back(LHSMask[Mask[i]]);
12813       
12814       // If the result mask is equal to the src shuffle or this shuffle mask, do
12815       // the replacement.
12816       if (NewMask == LHSMask || NewMask == Mask) {
12817         unsigned LHSInNElts =
12818           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12819         std::vector<Constant*> Elts;
12820         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12821           if (NewMask[i] >= LHSInNElts*2) {
12822             Elts.push_back(UndefValue::get(Type::Int32Ty));
12823           } else {
12824             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12825           }
12826         }
12827         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12828                                      LHSSVI->getOperand(1),
12829                                      ConstantVector::get(Elts));
12830       }
12831     }
12832   }
12833
12834   return MadeChange ? &SVI : 0;
12835 }
12836
12837
12838
12839
12840 /// TryToSinkInstruction - Try to move the specified instruction from its
12841 /// current block into the beginning of DestBlock, which can only happen if it's
12842 /// safe to move the instruction past all of the instructions between it and the
12843 /// end of its block.
12844 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12845   assert(I->hasOneUse() && "Invariants didn't hold!");
12846
12847   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12848   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12849     return false;
12850
12851   // Do not sink alloca instructions out of the entry block.
12852   if (isa<AllocaInst>(I) && I->getParent() ==
12853         &DestBlock->getParent()->getEntryBlock())
12854     return false;
12855
12856   // We can only sink load instructions if there is nothing between the load and
12857   // the end of block that could change the value.
12858   if (I->mayReadFromMemory()) {
12859     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12860          Scan != E; ++Scan)
12861       if (Scan->mayWriteToMemory())
12862         return false;
12863   }
12864
12865   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12866
12867   CopyPrecedingStopPoint(I, InsertPos);
12868   I->moveBefore(InsertPos);
12869   ++NumSunkInst;
12870   return true;
12871 }
12872
12873
12874 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12875 /// all reachable code to the worklist.
12876 ///
12877 /// This has a couple of tricks to make the code faster and more powerful.  In
12878 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12879 /// them to the worklist (this significantly speeds up instcombine on code where
12880 /// many instructions are dead or constant).  Additionally, if we find a branch
12881 /// whose condition is a known constant, we only visit the reachable successors.
12882 ///
12883 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12884                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12885                                        InstCombiner &IC,
12886                                        const TargetData *TD) {
12887   SmallVector<BasicBlock*, 256> Worklist;
12888   Worklist.push_back(BB);
12889
12890   while (!Worklist.empty()) {
12891     BB = Worklist.back();
12892     Worklist.pop_back();
12893     
12894     // We have now visited this block!  If we've already been here, ignore it.
12895     if (!Visited.insert(BB)) continue;
12896
12897     DbgInfoIntrinsic *DBI_Prev = NULL;
12898     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12899       Instruction *Inst = BBI++;
12900       
12901       // DCE instruction if trivially dead.
12902       if (isInstructionTriviallyDead(Inst)) {
12903         ++NumDeadInst;
12904         DOUT << "IC: DCE: " << *Inst;
12905         Inst->eraseFromParent();
12906         continue;
12907       }
12908       
12909       // ConstantProp instruction if trivially constant.
12910       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12911         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12912         Inst->replaceAllUsesWith(C);
12913         ++NumConstProp;
12914         Inst->eraseFromParent();
12915         continue;
12916       }
12917      
12918       // If there are two consecutive llvm.dbg.stoppoint calls then
12919       // it is likely that the optimizer deleted code in between these
12920       // two intrinsics. 
12921       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12922       if (DBI_Next) {
12923         if (DBI_Prev
12924             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12925             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12926           IC.RemoveFromWorkList(DBI_Prev);
12927           DBI_Prev->eraseFromParent();
12928         }
12929         DBI_Prev = DBI_Next;
12930       } else {
12931         DBI_Prev = 0;
12932       }
12933
12934       IC.AddToWorkList(Inst);
12935     }
12936
12937     // Recursively visit successors.  If this is a branch or switch on a
12938     // constant, only visit the reachable successor.
12939     TerminatorInst *TI = BB->getTerminator();
12940     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12941       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12942         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12943         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12944         Worklist.push_back(ReachableBB);
12945         continue;
12946       }
12947     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12948       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12949         // See if this is an explicit destination.
12950         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12951           if (SI->getCaseValue(i) == Cond) {
12952             BasicBlock *ReachableBB = SI->getSuccessor(i);
12953             Worklist.push_back(ReachableBB);
12954             continue;
12955           }
12956         
12957         // Otherwise it is the default destination.
12958         Worklist.push_back(SI->getSuccessor(0));
12959         continue;
12960       }
12961     }
12962     
12963     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12964       Worklist.push_back(TI->getSuccessor(i));
12965   }
12966 }
12967
12968 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12969   bool Changed = false;
12970   TD = getAnalysisIfAvailable<TargetData>();
12971   
12972   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12973         << F.getNameStr() << "\n");
12974
12975   {
12976     // Do a depth-first traversal of the function, populate the worklist with
12977     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12978     // track of which blocks we visit.
12979     SmallPtrSet<BasicBlock*, 64> Visited;
12980     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12981
12982     // Do a quick scan over the function.  If we find any blocks that are
12983     // unreachable, remove any instructions inside of them.  This prevents
12984     // the instcombine code from having to deal with some bad special cases.
12985     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12986       if (!Visited.count(BB)) {
12987         Instruction *Term = BB->getTerminator();
12988         while (Term != BB->begin()) {   // Remove instrs bottom-up
12989           BasicBlock::iterator I = Term; --I;
12990
12991           DOUT << "IC: DCE: " << *I;
12992           // A debug intrinsic shouldn't force another iteration if we weren't
12993           // going to do one without it.
12994           if (!isa<DbgInfoIntrinsic>(I)) {
12995             ++NumDeadInst;
12996             Changed = true;
12997           }
12998           if (!I->use_empty())
12999             I->replaceAllUsesWith(UndefValue::get(I->getType()));
13000           I->eraseFromParent();
13001         }
13002       }
13003   }
13004
13005   while (!Worklist.empty()) {
13006     Instruction *I = RemoveOneFromWorkList();
13007     if (I == 0) continue;  // skip null values.
13008
13009     // Check to see if we can DCE the instruction.
13010     if (isInstructionTriviallyDead(I)) {
13011       // Add operands to the worklist.
13012       if (I->getNumOperands() < 4)
13013         AddUsesToWorkList(*I);
13014       ++NumDeadInst;
13015
13016       DOUT << "IC: DCE: " << *I;
13017
13018       I->eraseFromParent();
13019       RemoveFromWorkList(I);
13020       Changed = true;
13021       continue;
13022     }
13023
13024     // Instruction isn't dead, see if we can constant propagate it.
13025     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13026       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13027
13028       // Add operands to the worklist.
13029       AddUsesToWorkList(*I);
13030       ReplaceInstUsesWith(*I, C);
13031
13032       ++NumConstProp;
13033       I->eraseFromParent();
13034       RemoveFromWorkList(I);
13035       Changed = true;
13036       continue;
13037     }
13038
13039     if (TD) {
13040       // See if we can constant fold its operands.
13041       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13042         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13043           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13044                                   F.getContext(), TD))
13045             if (NewC != CE) {
13046               i->set(NewC);
13047               Changed = true;
13048             }
13049     }
13050
13051     // See if we can trivially sink this instruction to a successor basic block.
13052     if (I->hasOneUse()) {
13053       BasicBlock *BB = I->getParent();
13054       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13055       if (UserParent != BB) {
13056         bool UserIsSuccessor = false;
13057         // See if the user is one of our successors.
13058         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13059           if (*SI == UserParent) {
13060             UserIsSuccessor = true;
13061             break;
13062           }
13063
13064         // If the user is one of our immediate successors, and if that successor
13065         // only has us as a predecessors (we'd have to split the critical edge
13066         // otherwise), we can keep going.
13067         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13068             next(pred_begin(UserParent)) == pred_end(UserParent))
13069           // Okay, the CFG is simple enough, try to sink this instruction.
13070           Changed |= TryToSinkInstruction(I, UserParent);
13071       }
13072     }
13073
13074     // Now that we have an instruction, try combining it to simplify it...
13075 #ifndef NDEBUG
13076     std::string OrigI;
13077 #endif
13078     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13079     if (Instruction *Result = visit(*I)) {
13080       ++NumCombined;
13081       // Should we replace the old instruction with a new one?
13082       if (Result != I) {
13083         DOUT << "IC: Old = " << *I
13084              << "    New = " << *Result;
13085
13086         // Everything uses the new instruction now.
13087         I->replaceAllUsesWith(Result);
13088
13089         // Push the new instruction and any users onto the worklist.
13090         AddToWorkList(Result);
13091         AddUsersToWorkList(*Result);
13092
13093         // Move the name to the new instruction first.
13094         Result->takeName(I);
13095
13096         // Insert the new instruction into the basic block...
13097         BasicBlock *InstParent = I->getParent();
13098         BasicBlock::iterator InsertPos = I;
13099
13100         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13101           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13102             ++InsertPos;
13103
13104         InstParent->getInstList().insert(InsertPos, Result);
13105
13106         // Make sure that we reprocess all operands now that we reduced their
13107         // use counts.
13108         AddUsesToWorkList(*I);
13109
13110         // Instructions can end up on the worklist more than once.  Make sure
13111         // we do not process an instruction that has been deleted.
13112         RemoveFromWorkList(I);
13113
13114         // Erase the old instruction.
13115         InstParent->getInstList().erase(I);
13116       } else {
13117 #ifndef NDEBUG
13118         DOUT << "IC: Mod = " << OrigI
13119              << "    New = " << *I;
13120 #endif
13121
13122         // If the instruction was modified, it's possible that it is now dead.
13123         // if so, remove it.
13124         if (isInstructionTriviallyDead(I)) {
13125           // Make sure we process all operands now that we are reducing their
13126           // use counts.
13127           AddUsesToWorkList(*I);
13128
13129           // Instructions may end up in the worklist more than once.  Erase all
13130           // occurrences of this instruction.
13131           RemoveFromWorkList(I);
13132           I->eraseFromParent();
13133         } else {
13134           AddToWorkList(I);
13135           AddUsersToWorkList(*I);
13136         }
13137       }
13138       Changed = true;
13139     }
13140   }
13141
13142   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13143     
13144   // Do an explicit clear, this shrinks the map if needed.
13145   WorklistMap.clear();
13146   return Changed;
13147 }
13148
13149
13150 bool InstCombiner::runOnFunction(Function &F) {
13151   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13152   Context = &F.getContext();
13153   
13154   bool EverMadeChange = false;
13155
13156   // Iterate while there is work to do.
13157   unsigned Iteration = 0;
13158   while (DoOneIteration(F, Iteration++))
13159     EverMadeChange = true;
13160   return EverMadeChange;
13161 }
13162
13163 FunctionPass *llvm::createInstructionCombiningPass() {
13164   return new InstCombiner();
13165 }