Fix a comment (bytes -> bits), reformat a comment
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     SmallVector<Instruction*, 256> Worklist;
78     DenseMap<Instruction*, unsigned> WorklistMap;
79     TargetData *TD;
80     bool MustPreserveLCSSA;
81   public:
82     static char ID; // Pass identification, replacement for typeid
83     InstCombiner() : FunctionPass(&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(*i))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           *i = UndefValue::get(Op->getType());
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitSub(BinaryOperator &I);
171     Instruction *visitMul(BinaryOperator &I);
172     Instruction *visitURem(BinaryOperator &I);
173     Instruction *visitSRem(BinaryOperator &I);
174     Instruction *visitFRem(BinaryOperator &I);
175     bool SimplifyDivRemOfSelect(BinaryOperator &I);
176     Instruction *commonRemTransforms(BinaryOperator &I);
177     Instruction *commonIRemTransforms(BinaryOperator &I);
178     Instruction *commonDivTransforms(BinaryOperator &I);
179     Instruction *commonIDivTransforms(BinaryOperator &I);
180     Instruction *visitUDiv(BinaryOperator &I);
181     Instruction *visitSDiv(BinaryOperator &I);
182     Instruction *visitFDiv(BinaryOperator &I);
183     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
184     Instruction *visitAnd(BinaryOperator &I);
185     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
186     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
187                                      Value *A, Value *B, Value *C);
188     Instruction *visitOr (BinaryOperator &I);
189     Instruction *visitXor(BinaryOperator &I);
190     Instruction *visitShl(BinaryOperator &I);
191     Instruction *visitAShr(BinaryOperator &I);
192     Instruction *visitLShr(BinaryOperator &I);
193     Instruction *commonShiftTransforms(BinaryOperator &I);
194     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195                                       Constant *RHSC);
196     Instruction *visitFCmpInst(FCmpInst &I);
197     Instruction *visitICmpInst(ICmpInst &I);
198     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
199     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200                                                 Instruction *LHS,
201                                                 ConstantInt *RHS);
202     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203                                 ConstantInt *DivRHS);
204
205     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206                              ICmpInst::Predicate Cond, Instruction &I);
207     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
208                                      BinaryOperator &I);
209     Instruction *commonCastTransforms(CastInst &CI);
210     Instruction *commonIntCastTransforms(CastInst &CI);
211     Instruction *commonPointerCastTransforms(CastInst &CI);
212     Instruction *visitTrunc(TruncInst &CI);
213     Instruction *visitZExt(ZExtInst &CI);
214     Instruction *visitSExt(SExtInst &CI);
215     Instruction *visitFPTrunc(FPTruncInst &CI);
216     Instruction *visitFPExt(CastInst &CI);
217     Instruction *visitFPToUI(FPToUIInst &FI);
218     Instruction *visitFPToSI(FPToSIInst &FI);
219     Instruction *visitUIToFP(CastInst &CI);
220     Instruction *visitSIToFP(CastInst &CI);
221     Instruction *visitPtrToInt(CastInst &CI);
222     Instruction *visitIntToPtr(IntToPtrInst &CI);
223     Instruction *visitBitCast(BitCastInst &CI);
224     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225                                 Instruction *FI);
226     Instruction *visitSelectInst(SelectInst &SI);
227     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
228     Instruction *visitCallInst(CallInst &CI);
229     Instruction *visitInvokeInst(InvokeInst &II);
230     Instruction *visitPHINode(PHINode &PN);
231     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
232     Instruction *visitAllocationInst(AllocationInst &AI);
233     Instruction *visitFreeInst(FreeInst &FI);
234     Instruction *visitLoadInst(LoadInst &LI);
235     Instruction *visitStoreInst(StoreInst &SI);
236     Instruction *visitBranchInst(BranchInst &BI);
237     Instruction *visitSwitchInst(SwitchInst &SI);
238     Instruction *visitInsertElementInst(InsertElementInst &IE);
239     Instruction *visitExtractElementInst(ExtractElementInst &EI);
240     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
241     Instruction *visitExtractValueInst(ExtractValueInst &EV);
242
243     // visitInstruction - Specify what to return for unhandled instructions...
244     Instruction *visitInstruction(Instruction &I) { return 0; }
245
246   private:
247     Instruction *visitCallSite(CallSite CS);
248     bool transformConstExprCastCall(CallSite CS);
249     Instruction *transformCallThroughTrampoline(CallSite CS);
250     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251                                    bool DoXform = true);
252     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
253
254   public:
255     // InsertNewInstBefore - insert an instruction New before instruction Old
256     // in the program.  Add the new instruction to the worklist.
257     //
258     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
259       assert(New && New->getParent() == 0 &&
260              "New instruction already inserted into a basic block!");
261       BasicBlock *BB = Old.getParent();
262       BB->getInstList().insert(&Old, New);  // Insert inst
263       AddToWorkList(New);
264       return New;
265     }
266
267     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268     /// This also adds the cast to the worklist.  Finally, this returns the
269     /// cast.
270     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
271                             Instruction &Pos) {
272       if (V->getType() == Ty) return V;
273
274       if (Constant *CV = dyn_cast<Constant>(V))
275         return ConstantExpr::getCast(opc, CV, Ty);
276       
277       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
278       AddToWorkList(C);
279       return C;
280     }
281         
282     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
284     }
285
286
287     // ReplaceInstUsesWith - This method is to be used when an instruction is
288     // found to be dead, replacable with another preexisting expression.  Here
289     // we add all uses of I to the worklist, replace all uses of I with the new
290     // value, then return I, so that the inst combiner will know that I was
291     // modified.
292     //
293     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
294       AddUsersToWorkList(I);         // Add all modified instrs to worklist
295       if (&I != V) {
296         I.replaceAllUsesWith(V);
297         return &I;
298       } else {
299         // If we are replacing the instruction with itself, this must be in a
300         // segment of unreachable code, so just clobber the instruction.
301         I.replaceAllUsesWith(UndefValue::get(I.getType()));
302         return &I;
303       }
304     }
305
306     // EraseInstFromFunction - When dealing with an instruction that has side
307     // effects or produces a void value, we can't rely on DCE to delete the
308     // instruction.  Instead, visit methods should return the value returned by
309     // this function.
310     Instruction *EraseInstFromFunction(Instruction &I) {
311       assert(I.use_empty() && "Cannot erase instruction that is used!");
312       AddUsesToWorkList(I);
313       RemoveFromWorkList(&I);
314       I.eraseFromParent();
315       return 0;  // Don't do anything with FI
316     }
317         
318     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
319                            APInt &KnownOne, unsigned Depth = 0) const {
320       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
321     }
322     
323     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
324                            unsigned Depth = 0) const {
325       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
326     }
327     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
328       return llvm::ComputeNumSignBits(Op, TD, Depth);
329     }
330
331   private:
332
333     /// SimplifyCommutative - This performs a few simplifications for 
334     /// commutative operators.
335     bool SimplifyCommutative(BinaryOperator &I);
336
337     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338     /// most-complex to least-complex order.
339     bool SimplifyCompare(CmpInst &I);
340
341     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
342     /// based on the demanded bits.
343     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
344                                    APInt& KnownZero, APInt& KnownOne,
345                                    unsigned Depth);
346     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
347                               APInt& KnownZero, APInt& KnownOne,
348                               unsigned Depth=0);
349         
350     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
351     /// SimplifyDemandedBits knows about.  See if the instruction has any
352     /// properties that allow us to simplify its operands.
353     bool SimplifyDemandedInstructionBits(Instruction &Inst);
354         
355     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
356                                       uint64_t &UndefElts, unsigned Depth = 0);
357       
358     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
359     // PHI node as operand #0, see if we can fold the instruction into the PHI
360     // (which is only possible if all operands to the PHI are constants).
361     Instruction *FoldOpIntoPhi(Instruction &I);
362
363     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
364     // operator and they all are only used by the PHI, PHI together their
365     // inputs, and do the operation once, to the result of the PHI.
366     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
367     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
368     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
369
370     
371     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
372                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
373     
374     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
375                               bool isSub, Instruction &I);
376     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
377                                  bool isSigned, bool Inside, Instruction &IB);
378     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
379     Instruction *MatchBSwap(BinaryOperator &I);
380     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
381     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
382     Instruction *SimplifyMemSet(MemSetInst *MI);
383
384
385     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
386
387     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
388                                     unsigned CastOpc, int &NumCastsRemoved);
389     unsigned GetOrEnforceKnownAlignment(Value *V,
390                                         unsigned PrefAlign = 0);
391
392   };
393 }
394
395 char InstCombiner::ID = 0;
396 static RegisterPass<InstCombiner>
397 X("instcombine", "Combine redundant instructions");
398
399 // getComplexity:  Assign a complexity or rank value to LLVM Values...
400 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
401 static unsigned getComplexity(Value *V) {
402   if (isa<Instruction>(V)) {
403     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
404       return 3;
405     return 4;
406   }
407   if (isa<Argument>(V)) return 3;
408   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
409 }
410
411 // isOnlyUse - Return true if this instruction will be deleted if we stop using
412 // it.
413 static bool isOnlyUse(Value *V) {
414   return V->hasOneUse() || isa<Constant>(V);
415 }
416
417 // getPromotedType - Return the specified type promoted as it would be to pass
418 // though a va_arg area...
419 static const Type *getPromotedType(const Type *Ty) {
420   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
421     if (ITy->getBitWidth() < 32)
422       return Type::Int32Ty;
423   }
424   return Ty;
425 }
426
427 /// getBitCastOperand - If the specified operand is a CastInst, a constant
428 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
429 /// operand value, otherwise return null.
430 static Value *getBitCastOperand(Value *V) {
431   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
432     // BitCastInst?
433     return I->getOperand(0);
434   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
435     // GetElementPtrInst?
436     if (GEP->hasAllZeroIndices())
437       return GEP->getOperand(0);
438   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
439     if (CE->getOpcode() == Instruction::BitCast)
440       // BitCast ConstantExp?
441       return CE->getOperand(0);
442     else if (CE->getOpcode() == Instruction::GetElementPtr) {
443       // GetElementPtr ConstantExp?
444       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
445            I != E; ++I) {
446         ConstantInt *CI = dyn_cast<ConstantInt>(I);
447         if (!CI || !CI->isZero())
448           // Any non-zero indices? Not cast-like.
449           return 0;
450       }
451       // All-zero indices? This is just like casting.
452       return CE->getOperand(0);
453     }
454   }
455   return 0;
456 }
457
458 /// This function is a wrapper around CastInst::isEliminableCastPair. It
459 /// simply extracts arguments and returns what that function returns.
460 static Instruction::CastOps 
461 isEliminableCastPair(
462   const CastInst *CI, ///< The first cast instruction
463   unsigned opcode,       ///< The opcode of the second cast instruction
464   const Type *DstTy,     ///< The target type for the second cast instruction
465   TargetData *TD         ///< The target data for pointer size
466 ) {
467   
468   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
469   const Type *MidTy = CI->getType();                  // B from above
470
471   // Get the opcodes of the two Cast instructions
472   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
473   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
474
475   return Instruction::CastOps(
476       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
477                                      DstTy, TD->getIntPtrType()));
478 }
479
480 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
481 /// in any code being generated.  It does not require codegen if V is simple
482 /// enough or if the cast can be folded into other casts.
483 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
484                               const Type *Ty, TargetData *TD) {
485   if (V->getType() == Ty || isa<Constant>(V)) return false;
486   
487   // If this is another cast that can be eliminated, it isn't codegen either.
488   if (const CastInst *CI = dyn_cast<CastInst>(V))
489     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
490       return false;
491   return true;
492 }
493
494 // SimplifyCommutative - This performs a few simplifications for commutative
495 // operators:
496 //
497 //  1. Order operands such that they are listed from right (least complex) to
498 //     left (most complex).  This puts constants before unary operators before
499 //     binary operators.
500 //
501 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
502 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
503 //
504 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
505   bool Changed = false;
506   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
507     Changed = !I.swapOperands();
508
509   if (!I.isAssociative()) return Changed;
510   Instruction::BinaryOps Opcode = I.getOpcode();
511   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
512     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
513       if (isa<Constant>(I.getOperand(1))) {
514         Constant *Folded = ConstantExpr::get(I.getOpcode(),
515                                              cast<Constant>(I.getOperand(1)),
516                                              cast<Constant>(Op->getOperand(1)));
517         I.setOperand(0, Op->getOperand(0));
518         I.setOperand(1, Folded);
519         return true;
520       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
521         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
522             isOnlyUse(Op) && isOnlyUse(Op1)) {
523           Constant *C1 = cast<Constant>(Op->getOperand(1));
524           Constant *C2 = cast<Constant>(Op1->getOperand(1));
525
526           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
527           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
528           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
529                                                     Op1->getOperand(0),
530                                                     Op1->getName(), &I);
531           AddToWorkList(New);
532           I.setOperand(0, New);
533           I.setOperand(1, Folded);
534           return true;
535         }
536     }
537   return Changed;
538 }
539
540 /// SimplifyCompare - For a CmpInst this function just orders the operands
541 /// so that theyare listed from right (least complex) to left (most complex).
542 /// This puts constants before unary operators before binary operators.
543 bool InstCombiner::SimplifyCompare(CmpInst &I) {
544   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
545     return false;
546   I.swapOperands();
547   // Compare instructions are not associative so there's nothing else we can do.
548   return true;
549 }
550
551 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
552 // if the LHS is a constant zero (which is the 'negate' form).
553 //
554 static inline Value *dyn_castNegVal(Value *V) {
555   if (BinaryOperator::isNeg(V))
556     return BinaryOperator::getNegArgument(V);
557
558   // Constants can be considered to be negated values if they can be folded.
559   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
560     return ConstantExpr::getNeg(C);
561
562   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
563     if (C->getType()->getElementType()->isInteger())
564       return ConstantExpr::getNeg(C);
565
566   return 0;
567 }
568
569 static inline Value *dyn_castNotVal(Value *V) {
570   if (BinaryOperator::isNot(V))
571     return BinaryOperator::getNotArgument(V);
572
573   // Constants can be considered to be not'ed values...
574   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
575     return ConstantInt::get(~C->getValue());
576   return 0;
577 }
578
579 // dyn_castFoldableMul - If this value is a multiply that can be folded into
580 // other computations (because it has a constant operand), return the
581 // non-constant operand of the multiply, and set CST to point to the multiplier.
582 // Otherwise, return null.
583 //
584 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
585   if (V->hasOneUse() && V->getType()->isInteger())
586     if (Instruction *I = dyn_cast<Instruction>(V)) {
587       if (I->getOpcode() == Instruction::Mul)
588         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
589           return I->getOperand(0);
590       if (I->getOpcode() == Instruction::Shl)
591         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
592           // The multiplier is really 1 << CST.
593           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
594           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
595           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
596           return I->getOperand(0);
597         }
598     }
599   return 0;
600 }
601
602 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
603 /// expression, return it.
604 static User *dyn_castGetElementPtr(Value *V) {
605   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
606   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
607     if (CE->getOpcode() == Instruction::GetElementPtr)
608       return cast<User>(V);
609   return false;
610 }
611
612 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
613 /// opcode value. Otherwise return UserOp1.
614 static unsigned getOpcode(const Value *V) {
615   if (const Instruction *I = dyn_cast<Instruction>(V))
616     return I->getOpcode();
617   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
618     return CE->getOpcode();
619   // Use UserOp1 to mean there's no opcode.
620   return Instruction::UserOp1;
621 }
622
623 /// AddOne - Add one to a ConstantInt
624 static ConstantInt *AddOne(ConstantInt *C) {
625   APInt Val(C->getValue());
626   return ConstantInt::get(++Val);
627 }
628 /// SubOne - Subtract one from a ConstantInt
629 static ConstantInt *SubOne(ConstantInt *C) {
630   APInt Val(C->getValue());
631   return ConstantInt::get(--Val);
632 }
633 /// Add - Add two ConstantInts together
634 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
635   return ConstantInt::get(C1->getValue() + C2->getValue());
636 }
637 /// And - Bitwise AND two ConstantInts together
638 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
639   return ConstantInt::get(C1->getValue() & C2->getValue());
640 }
641 /// Subtract - Subtract one ConstantInt from another
642 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
643   return ConstantInt::get(C1->getValue() - C2->getValue());
644 }
645 /// Multiply - Multiply two ConstantInts together
646 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
647   return ConstantInt::get(C1->getValue() * C2->getValue());
648 }
649 /// MultiplyOverflows - True if the multiply can not be expressed in an int
650 /// this size.
651 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
652   uint32_t W = C1->getBitWidth();
653   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
654   if (sign) {
655     LHSExt.sext(W * 2);
656     RHSExt.sext(W * 2);
657   } else {
658     LHSExt.zext(W * 2);
659     RHSExt.zext(W * 2);
660   }
661
662   APInt MulExt = LHSExt * RHSExt;
663
664   if (sign) {
665     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667     return MulExt.slt(Min) || MulExt.sgt(Max);
668   } else 
669     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
670 }
671
672
673 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
674 /// specified instruction is a constant integer.  If so, check to see if there
675 /// are any bits set in the constant that are not demanded.  If so, shrink the
676 /// constant and return true.
677 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
678                                    APInt Demanded) {
679   assert(I && "No instruction?");
680   assert(OpNo < I->getNumOperands() && "Operand index too large");
681
682   // If the operand is not a constant integer, nothing to do.
683   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684   if (!OpC) return false;
685
686   // If there are no bits set that aren't demanded, nothing to do.
687   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688   if ((~Demanded & OpC->getValue()) == 0)
689     return false;
690
691   // This instruction is producing bits that are not demanded. Shrink the RHS.
692   Demanded &= OpC->getValue();
693   I->setOperand(OpNo, ConstantInt::get(Demanded));
694   return true;
695 }
696
697 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
698 // set of known zero and one bits, compute the maximum and minimum values that
699 // could have the specified known zero and known one bits, returning them in
700 // min/max.
701 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
702                                                    const APInt& KnownZero,
703                                                    const APInt& KnownOne,
704                                                    APInt& Min, APInt& Max) {
705   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
706   assert(KnownZero.getBitWidth() == BitWidth && 
707          KnownOne.getBitWidth() == BitWidth &&
708          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
709          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
710   APInt UnknownBits = ~(KnownZero|KnownOne);
711
712   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
713   // bit if it is unknown.
714   Min = KnownOne;
715   Max = KnownOne|UnknownBits;
716   
717   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
718     Min.set(BitWidth-1);
719     Max.clear(BitWidth-1);
720   }
721 }
722
723 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
724 // a set of known zero and one bits, compute the maximum and minimum values that
725 // could have the specified known zero and known one bits, returning them in
726 // min/max.
727 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
728                                                      const APInt &KnownZero,
729                                                      const APInt &KnownOne,
730                                                      APInt &Min, APInt &Max) {
731   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
732   assert(KnownZero.getBitWidth() == BitWidth && 
733          KnownOne.getBitWidth() == BitWidth &&
734          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
735          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
736   APInt UnknownBits = ~(KnownZero|KnownOne);
737   
738   // The minimum value is when the unknown bits are all zeros.
739   Min = KnownOne;
740   // The maximum value is when the unknown bits are all ones.
741   Max = KnownOne|UnknownBits;
742 }
743
744 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
745 /// SimplifyDemandedBits knows about.  See if the instruction has any
746 /// properties that allow us to simplify its operands.
747 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
748   unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
749   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
750   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
751   
752   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
753                                      KnownZero, KnownOne, 0);
754   if (V == 0) return false;
755   if (V == &Inst) return true;
756   ReplaceInstUsesWith(Inst, V);
757   return true;
758 }
759
760 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
761 /// specified instruction operand if possible, updating it in place.  It returns
762 /// true if it made any change and false otherwise.
763 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
764                                         APInt &KnownZero, APInt &KnownOne,
765                                         unsigned Depth) {
766   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
767                                           KnownZero, KnownOne, Depth);
768   if (NewVal == 0) return false;
769   U.set(NewVal);
770   return true;
771 }
772
773
774 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
775 /// value based on the demanded bits.  When this function is called, it is known
776 /// that only the bits set in DemandedMask of the result of V are ever used
777 /// downstream. Consequently, depending on the mask and V, it may be possible
778 /// to replace V with a constant or one of its operands. In such cases, this
779 /// function does the replacement and returns true. In all other cases, it
780 /// returns false after analyzing the expression and setting KnownOne and known
781 /// to be one in the expression.  KnownZero contains all the bits that are known
782 /// to be zero in the expression. These are provided to potentially allow the
783 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
784 /// the expression. KnownOne and KnownZero always follow the invariant that 
785 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
786 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
787 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
788 /// and KnownOne must all be the same.
789 ///
790 /// This returns null if it did not change anything and it permits no
791 /// simplification.  This returns V itself if it did some simplification of V's
792 /// operands based on the information about what bits are demanded. This returns
793 /// some other non-null value if it found out that V is equal to another value
794 /// in the context where the specified bits are demanded, but not for all users.
795 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
796                                              APInt &KnownZero, APInt &KnownOne,
797                                              unsigned Depth) {
798   assert(V != 0 && "Null pointer of Value???");
799   assert(Depth <= 6 && "Limit Search Depth");
800   uint32_t BitWidth = DemandedMask.getBitWidth();
801   const IntegerType *VTy = cast<IntegerType>(V->getType());
802   assert(VTy->getBitWidth() == BitWidth && 
803          KnownZero.getBitWidth() == BitWidth && 
804          KnownOne.getBitWidth() == BitWidth &&
805          "Value *V, DemandedMask, KnownZero and KnownOne \
806           must have same BitWidth");
807   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808     // We know all of the bits for a constant!
809     KnownOne = CI->getValue() & DemandedMask;
810     KnownZero = ~KnownOne & DemandedMask;
811     return 0;
812   }
813   
814   KnownZero.clear();
815   KnownOne.clear();
816   if (DemandedMask == 0) {   // Not demanding any bits from V.
817     if (isa<UndefValue>(V))
818       return 0;
819     return UndefValue::get(VTy);
820   }
821   
822   if (Depth == 6)        // Limit search depth.
823     return 0;
824   
825   Instruction *I = dyn_cast<Instruction>(V);
826   if (!I) return 0;        // Only analyze instructions.
827   
828   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
829   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
830
831   // If there are multiple uses of this value and we aren't at the root, then
832   // we can't do any simplifications of the operands, because DemandedMask
833   // only reflects the bits demanded by *one* of the users.
834   if (Depth != 0 && !I->hasOneUse()) {
835     // Despite the fact that we can't simplify this instruction in all User's
836     // context, we can at least compute the knownzero/knownone bits, and we can
837     // do simplifications that apply to *just* the one user if we know that
838     // this instruction has a simpler value in that context.
839     if (I->getOpcode() == Instruction::And) {
840       // If either the LHS or the RHS are Zero, the result is zero.
841       ComputeMaskedBits(I->getOperand(1), DemandedMask,
842                         RHSKnownZero, RHSKnownOne, Depth+1);
843       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
844                         LHSKnownZero, LHSKnownOne, Depth+1);
845       
846       // If all of the demanded bits are known 1 on one side, return the other.
847       // These bits cannot contribute to the result of the 'and' in this
848       // context.
849       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
850           (DemandedMask & ~LHSKnownZero))
851         return I->getOperand(0);
852       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
853           (DemandedMask & ~RHSKnownZero))
854         return I->getOperand(1);
855       
856       // If all of the demanded bits in the inputs are known zeros, return zero.
857       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
858         return Constant::getNullValue(VTy);
859       
860     } else if (I->getOpcode() == Instruction::Or) {
861       // We can simplify (X|Y) -> X or Y in the user's context if we know that
862       // only bits from X or Y are demanded.
863       
864       // If either the LHS or the RHS are One, the result is One.
865       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
866                         RHSKnownZero, RHSKnownOne, Depth+1);
867       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
868                         LHSKnownZero, LHSKnownOne, Depth+1);
869       
870       // If all of the demanded bits are known zero on one side, return the
871       // other.  These bits cannot contribute to the result of the 'or' in this
872       // context.
873       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
874           (DemandedMask & ~LHSKnownOne))
875         return I->getOperand(0);
876       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
877           (DemandedMask & ~RHSKnownOne))
878         return I->getOperand(1);
879       
880       // If all of the potentially set bits on one side are known to be set on
881       // the other side, just use the 'other' side.
882       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
883           (DemandedMask & (~RHSKnownZero)))
884         return I->getOperand(0);
885       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
886           (DemandedMask & (~LHSKnownZero)))
887         return I->getOperand(1);
888     }
889     
890     // Compute the KnownZero/KnownOne bits to simplify things downstream.
891     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
892     return 0;
893   }
894   
895   // If this is the root being simplified, allow it to have multiple uses,
896   // just set the DemandedMask to all bits so that we can try to simplify the
897   // operands.  This allows visitTruncInst (for example) to simplify the
898   // operand of a trunc without duplicating all the logic below.
899   if (Depth == 0 && !V->hasOneUse())
900     DemandedMask = APInt::getAllOnesValue(BitWidth);
901   
902   switch (I->getOpcode()) {
903   default:
904     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
905     break;
906   case Instruction::And:
907     // If either the LHS or the RHS are Zero, the result is zero.
908     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
909                              RHSKnownZero, RHSKnownOne, Depth+1) ||
910         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
911                              LHSKnownZero, LHSKnownOne, Depth+1))
912       return I;
913     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
914     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
915
916     // If all of the demanded bits are known 1 on one side, return the other.
917     // These bits cannot contribute to the result of the 'and'.
918     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
919         (DemandedMask & ~LHSKnownZero))
920       return I->getOperand(0);
921     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
922         (DemandedMask & ~RHSKnownZero))
923       return I->getOperand(1);
924     
925     // If all of the demanded bits in the inputs are known zeros, return zero.
926     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
927       return Constant::getNullValue(VTy);
928       
929     // If the RHS is a constant, see if we can simplify it.
930     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
931       return I;
932       
933     // Output known-1 bits are only known if set in both the LHS & RHS.
934     RHSKnownOne &= LHSKnownOne;
935     // Output known-0 are known to be clear if zero in either the LHS | RHS.
936     RHSKnownZero |= LHSKnownZero;
937     break;
938   case Instruction::Or:
939     // If either the LHS or the RHS are One, the result is One.
940     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
941                              RHSKnownZero, RHSKnownOne, Depth+1) ||
942         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
943                              LHSKnownZero, LHSKnownOne, Depth+1))
944       return I;
945     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
946     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
947     
948     // If all of the demanded bits are known zero on one side, return the other.
949     // These bits cannot contribute to the result of the 'or'.
950     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
951         (DemandedMask & ~LHSKnownOne))
952       return I->getOperand(0);
953     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
954         (DemandedMask & ~RHSKnownOne))
955       return I->getOperand(1);
956
957     // If all of the potentially set bits on one side are known to be set on
958     // the other side, just use the 'other' side.
959     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
960         (DemandedMask & (~RHSKnownZero)))
961       return I->getOperand(0);
962     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
963         (DemandedMask & (~LHSKnownZero)))
964       return I->getOperand(1);
965         
966     // If the RHS is a constant, see if we can simplify it.
967     if (ShrinkDemandedConstant(I, 1, DemandedMask))
968       return I;
969           
970     // Output known-0 bits are only known if clear in both the LHS & RHS.
971     RHSKnownZero &= LHSKnownZero;
972     // Output known-1 are known to be set if set in either the LHS | RHS.
973     RHSKnownOne |= LHSKnownOne;
974     break;
975   case Instruction::Xor: {
976     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
977                              RHSKnownZero, RHSKnownOne, Depth+1) ||
978         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
979                              LHSKnownZero, LHSKnownOne, Depth+1))
980       return I;
981     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
982     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
983     
984     // If all of the demanded bits are known zero on one side, return the other.
985     // These bits cannot contribute to the result of the 'xor'.
986     if ((DemandedMask & RHSKnownZero) == DemandedMask)
987       return I->getOperand(0);
988     if ((DemandedMask & LHSKnownZero) == DemandedMask)
989       return I->getOperand(1);
990     
991     // Output known-0 bits are known if clear or set in both the LHS & RHS.
992     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
993                          (RHSKnownOne & LHSKnownOne);
994     // Output known-1 are known to be set if set in only one of the LHS, RHS.
995     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
996                         (RHSKnownOne & LHSKnownZero);
997     
998     // If all of the demanded bits are known to be zero on one side or the
999     // other, turn this into an *inclusive* or.
1000     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1001     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1002       Instruction *Or =
1003         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1004                                  I->getName());
1005       return InsertNewInstBefore(Or, *I);
1006     }
1007     
1008     // If all of the demanded bits on one side are known, and all of the set
1009     // bits on that side are also known to be set on the other side, turn this
1010     // into an AND, as we know the bits will be cleared.
1011     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1012     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1013       // all known
1014       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1015         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1016         Instruction *And = 
1017           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1018         return InsertNewInstBefore(And, *I);
1019       }
1020     }
1021     
1022     // If the RHS is a constant, see if we can simplify it.
1023     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1024     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1025       return I;
1026     
1027     RHSKnownZero = KnownZeroOut;
1028     RHSKnownOne  = KnownOneOut;
1029     break;
1030   }
1031   case Instruction::Select:
1032     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1033                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1034         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1035                              LHSKnownZero, LHSKnownOne, Depth+1))
1036       return I;
1037     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1038     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1039     
1040     // If the operands are constants, see if we can simplify them.
1041     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1042         ShrinkDemandedConstant(I, 2, DemandedMask))
1043       return I;
1044     
1045     // Only known if known in both the LHS and RHS.
1046     RHSKnownOne &= LHSKnownOne;
1047     RHSKnownZero &= LHSKnownZero;
1048     break;
1049   case Instruction::Trunc: {
1050     unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1051     DemandedMask.zext(truncBf);
1052     RHSKnownZero.zext(truncBf);
1053     RHSKnownOne.zext(truncBf);
1054     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1055                              RHSKnownZero, RHSKnownOne, Depth+1))
1056       return I;
1057     DemandedMask.trunc(BitWidth);
1058     RHSKnownZero.trunc(BitWidth);
1059     RHSKnownOne.trunc(BitWidth);
1060     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1061     break;
1062   }
1063   case Instruction::BitCast:
1064     if (!I->getOperand(0)->getType()->isInteger())
1065       return false;  // vector->int or fp->int?
1066     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1067                              RHSKnownZero, RHSKnownOne, Depth+1))
1068       return I;
1069     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1070     break;
1071   case Instruction::ZExt: {
1072     // Compute the bits in the result that are not present in the input.
1073     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1074     
1075     DemandedMask.trunc(SrcBitWidth);
1076     RHSKnownZero.trunc(SrcBitWidth);
1077     RHSKnownOne.trunc(SrcBitWidth);
1078     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1079                              RHSKnownZero, RHSKnownOne, Depth+1))
1080       return I;
1081     DemandedMask.zext(BitWidth);
1082     RHSKnownZero.zext(BitWidth);
1083     RHSKnownOne.zext(BitWidth);
1084     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1085     // The top bits are known to be zero.
1086     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1087     break;
1088   }
1089   case Instruction::SExt: {
1090     // Compute the bits in the result that are not present in the input.
1091     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1092     
1093     APInt InputDemandedBits = DemandedMask & 
1094                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1095
1096     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1097     // If any of the sign extended bits are demanded, we know that the sign
1098     // bit is demanded.
1099     if ((NewBits & DemandedMask) != 0)
1100       InputDemandedBits.set(SrcBitWidth-1);
1101       
1102     InputDemandedBits.trunc(SrcBitWidth);
1103     RHSKnownZero.trunc(SrcBitWidth);
1104     RHSKnownOne.trunc(SrcBitWidth);
1105     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1106                              RHSKnownZero, RHSKnownOne, Depth+1))
1107       return I;
1108     InputDemandedBits.zext(BitWidth);
1109     RHSKnownZero.zext(BitWidth);
1110     RHSKnownOne.zext(BitWidth);
1111     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1112       
1113     // If the sign bit of the input is known set or clear, then we know the
1114     // top bits of the result.
1115
1116     // If the input sign bit is known zero, or if the NewBits are not demanded
1117     // convert this into a zero extension.
1118     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1119       // Convert to ZExt cast
1120       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1121       return InsertNewInstBefore(NewCast, *I);
1122     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1123       RHSKnownOne |= NewBits;
1124     }
1125     break;
1126   }
1127   case Instruction::Add: {
1128     // Figure out what the input bits are.  If the top bits of the and result
1129     // are not demanded, then the add doesn't demand them from its input
1130     // either.
1131     unsigned NLZ = DemandedMask.countLeadingZeros();
1132       
1133     // If there is a constant on the RHS, there are a variety of xformations
1134     // we can do.
1135     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1136       // If null, this should be simplified elsewhere.  Some of the xforms here
1137       // won't work if the RHS is zero.
1138       if (RHS->isZero())
1139         break;
1140       
1141       // If the top bit of the output is demanded, demand everything from the
1142       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1143       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1144
1145       // Find information about known zero/one bits in the input.
1146       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1147                                LHSKnownZero, LHSKnownOne, Depth+1))
1148         return I;
1149
1150       // If the RHS of the add has bits set that can't affect the input, reduce
1151       // the constant.
1152       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1153         return I;
1154       
1155       // Avoid excess work.
1156       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1157         break;
1158       
1159       // Turn it into OR if input bits are zero.
1160       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1161         Instruction *Or =
1162           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1163                                    I->getName());
1164         return InsertNewInstBefore(Or, *I);
1165       }
1166       
1167       // We can say something about the output known-zero and known-one bits,
1168       // depending on potential carries from the input constant and the
1169       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1170       // bits set and the RHS constant is 0x01001, then we know we have a known
1171       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1172       
1173       // To compute this, we first compute the potential carry bits.  These are
1174       // the bits which may be modified.  I'm not aware of a better way to do
1175       // this scan.
1176       const APInt &RHSVal = RHS->getValue();
1177       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1178       
1179       // Now that we know which bits have carries, compute the known-1/0 sets.
1180       
1181       // Bits are known one if they are known zero in one operand and one in the
1182       // other, and there is no input carry.
1183       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1184                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1185       
1186       // Bits are known zero if they are known zero in both operands and there
1187       // is no input carry.
1188       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1189     } else {
1190       // If the high-bits of this ADD are not demanded, then it does not demand
1191       // the high bits of its LHS or RHS.
1192       if (DemandedMask[BitWidth-1] == 0) {
1193         // Right fill the mask of bits for this ADD to demand the most
1194         // significant bit and all those below it.
1195         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1196         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1197                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1198             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1199                                  LHSKnownZero, LHSKnownOne, Depth+1))
1200           return I;
1201       }
1202     }
1203     break;
1204   }
1205   case Instruction::Sub:
1206     // If the high-bits of this SUB are not demanded, then it does not demand
1207     // the high bits of its LHS or RHS.
1208     if (DemandedMask[BitWidth-1] == 0) {
1209       // Right fill the mask of bits for this SUB to demand the most
1210       // significant bit and all those below it.
1211       uint32_t NLZ = DemandedMask.countLeadingZeros();
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     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1220     // the known zeros and ones.
1221     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1222     break;
1223   case Instruction::Shl:
1224     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1225       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1226       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1227       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1228                                RHSKnownZero, RHSKnownOne, Depth+1))
1229         return I;
1230       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1231       RHSKnownZero <<= ShiftAmt;
1232       RHSKnownOne  <<= ShiftAmt;
1233       // low bits known zero.
1234       if (ShiftAmt)
1235         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1236     }
1237     break;
1238   case Instruction::LShr:
1239     // For a logical shift right
1240     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1241       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1242       
1243       // Unsigned shift right.
1244       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1245       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1246                                RHSKnownZero, RHSKnownOne, Depth+1))
1247         return I;
1248       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1249       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1250       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1251       if (ShiftAmt) {
1252         // Compute the new bits that are at the top now.
1253         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1254         RHSKnownZero |= HighBits;  // high bits known zero.
1255       }
1256     }
1257     break;
1258   case Instruction::AShr:
1259     // If this is an arithmetic shift right and only the low-bit is set, we can
1260     // always convert this into a logical shr, even if the shift amount is
1261     // variable.  The low bit of the shift cannot be an input sign bit unless
1262     // the shift amount is >= the size of the datatype, which is undefined.
1263     if (DemandedMask == 1) {
1264       // Perform the logical shift right.
1265       Instruction *NewVal = BinaryOperator::CreateLShr(
1266                         I->getOperand(0), I->getOperand(1), I->getName());
1267       return InsertNewInstBefore(NewVal, *I);
1268     }    
1269
1270     // If the sign bit is the only bit demanded by this ashr, then there is no
1271     // need to do it, the shift doesn't change the high bit.
1272     if (DemandedMask.isSignBit())
1273       return I->getOperand(0);
1274     
1275     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1276       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1277       
1278       // Signed shift right.
1279       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1280       // If any of the "high bits" are demanded, we should set the sign bit as
1281       // demanded.
1282       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1283         DemandedMaskIn.set(BitWidth-1);
1284       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1285                                RHSKnownZero, RHSKnownOne, Depth+1))
1286         return I;
1287       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1288       // Compute the new bits that are at the top now.
1289       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1290       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1291       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1292         
1293       // Handle the sign bits.
1294       APInt SignBit(APInt::getSignBit(BitWidth));
1295       // Adjust to where it is now in the mask.
1296       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1297         
1298       // If the input sign bit is known to be zero, or if none of the top bits
1299       // are demanded, turn this into an unsigned shift right.
1300       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1301           (HighBits & ~DemandedMask) == HighBits) {
1302         // Perform the logical shift right.
1303         Instruction *NewVal = BinaryOperator::CreateLShr(
1304                           I->getOperand(0), SA, I->getName());
1305         return InsertNewInstBefore(NewVal, *I);
1306       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1307         RHSKnownOne |= HighBits;
1308       }
1309     }
1310     break;
1311   case Instruction::SRem:
1312     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1313       APInt RA = Rem->getValue().abs();
1314       if (RA.isPowerOf2()) {
1315         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1316           return I->getOperand(0);
1317
1318         APInt LowBits = RA - 1;
1319         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1320         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1321                                  LHSKnownZero, LHSKnownOne, Depth+1))
1322           return I;
1323
1324         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1325           LHSKnownZero |= ~LowBits;
1326
1327         KnownZero |= LHSKnownZero & DemandedMask;
1328
1329         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1330       }
1331     }
1332     break;
1333   case Instruction::URem: {
1334     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1335     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1336     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1337                              KnownZero2, KnownOne2, Depth+1) ||
1338         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1339                              KnownZero2, KnownOne2, Depth+1))
1340       return I;
1341
1342     unsigned Leaders = KnownZero2.countLeadingOnes();
1343     Leaders = std::max(Leaders,
1344                        KnownZero2.countLeadingOnes());
1345     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1346     break;
1347   }
1348   case Instruction::Call:
1349     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1350       switch (II->getIntrinsicID()) {
1351       default: break;
1352       case Intrinsic::bswap: {
1353         // If the only bits demanded come from one byte of the bswap result,
1354         // just shift the input byte into position to eliminate the bswap.
1355         unsigned NLZ = DemandedMask.countLeadingZeros();
1356         unsigned NTZ = DemandedMask.countTrailingZeros();
1357           
1358         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1359         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1360         // have 14 leading zeros, round to 8.
1361         NLZ &= ~7;
1362         NTZ &= ~7;
1363         // If we need exactly one byte, we can do this transformation.
1364         if (BitWidth-NLZ-NTZ == 8) {
1365           unsigned ResultBit = NTZ;
1366           unsigned InputBit = BitWidth-NTZ-8;
1367           
1368           // Replace this with either a left or right shift to get the byte into
1369           // the right place.
1370           Instruction *NewVal;
1371           if (InputBit > ResultBit)
1372             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1373                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1374           else
1375             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1376                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1377           NewVal->takeName(I);
1378           return InsertNewInstBefore(NewVal, *I);
1379         }
1380           
1381         // TODO: Could compute known zero/one bits based on the input.
1382         break;
1383       }
1384       }
1385     }
1386     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1387     break;
1388   }
1389   
1390   // If the client is only demanding bits that we know, return the known
1391   // constant.
1392   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1393     return ConstantInt::get(RHSKnownOne);
1394   return false;
1395 }
1396
1397
1398 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1399 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1400 /// actually used by the caller.  This method analyzes which elements of the
1401 /// operand are undef and returns that information in UndefElts.
1402 ///
1403 /// If the information about demanded elements can be used to simplify the
1404 /// operation, the operation is simplified, then the resultant value is
1405 /// returned.  This returns null if no change was made.
1406 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1407                                                 uint64_t &UndefElts,
1408                                                 unsigned Depth) {
1409   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1410   assert(VWidth <= 64 && "Vector too wide to analyze!");
1411   uint64_t EltMask = ~0ULL >> (64-VWidth);
1412   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1413
1414   if (isa<UndefValue>(V)) {
1415     // If the entire vector is undefined, just return this info.
1416     UndefElts = EltMask;
1417     return 0;
1418   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1419     UndefElts = EltMask;
1420     return UndefValue::get(V->getType());
1421   }
1422
1423   UndefElts = 0;
1424   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1425     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1426     Constant *Undef = UndefValue::get(EltTy);
1427
1428     std::vector<Constant*> Elts;
1429     for (unsigned i = 0; i != VWidth; ++i)
1430       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1431         Elts.push_back(Undef);
1432         UndefElts |= (1ULL << i);
1433       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1434         Elts.push_back(Undef);
1435         UndefElts |= (1ULL << i);
1436       } else {                               // Otherwise, defined.
1437         Elts.push_back(CP->getOperand(i));
1438       }
1439
1440     // If we changed the constant, return it.
1441     Constant *NewCP = ConstantVector::get(Elts);
1442     return NewCP != CP ? NewCP : 0;
1443   } else if (isa<ConstantAggregateZero>(V)) {
1444     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1445     // set to undef.
1446     
1447     // Check if this is identity. If so, return 0 since we are not simplifying
1448     // anything.
1449     if (DemandedElts == ((1ULL << VWidth) -1))
1450       return 0;
1451     
1452     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1453     Constant *Zero = Constant::getNullValue(EltTy);
1454     Constant *Undef = UndefValue::get(EltTy);
1455     std::vector<Constant*> Elts;
1456     for (unsigned i = 0; i != VWidth; ++i)
1457       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1458     UndefElts = DemandedElts ^ EltMask;
1459     return ConstantVector::get(Elts);
1460   }
1461   
1462   // Limit search depth.
1463   if (Depth == 10)
1464     return false;
1465
1466   // If multiple users are using the root value, procede with
1467   // simplification conservatively assuming that all elements
1468   // are needed.
1469   if (!V->hasOneUse()) {
1470     // Quit if we find multiple users of a non-root value though.
1471     // They'll be handled when it's their turn to be visited by
1472     // the main instcombine process.
1473     if (Depth != 0)
1474       // TODO: Just compute the UndefElts information recursively.
1475       return false;
1476
1477     // Conservatively assume that all elements are needed.
1478     DemandedElts = EltMask;
1479   }
1480   
1481   Instruction *I = dyn_cast<Instruction>(V);
1482   if (!I) return false;        // Only analyze instructions.
1483   
1484   bool MadeChange = false;
1485   uint64_t UndefElts2;
1486   Value *TmpV;
1487   switch (I->getOpcode()) {
1488   default: break;
1489     
1490   case Instruction::InsertElement: {
1491     // If this is a variable index, we don't know which element it overwrites.
1492     // demand exactly the same input as we produce.
1493     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1494     if (Idx == 0) {
1495       // Note that we can't propagate undef elt info, because we don't know
1496       // which elt is getting updated.
1497       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1498                                         UndefElts2, Depth+1);
1499       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1500       break;
1501     }
1502     
1503     // If this is inserting an element that isn't demanded, remove this
1504     // insertelement.
1505     unsigned IdxNo = Idx->getZExtValue();
1506     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1507       return AddSoonDeadInstToWorklist(*I, 0);
1508     
1509     // Otherwise, the element inserted overwrites whatever was there, so the
1510     // input demanded set is simpler than the output set.
1511     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1512                                       DemandedElts & ~(1ULL << IdxNo),
1513                                       UndefElts, Depth+1);
1514     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1515
1516     // The inserted element is defined.
1517     UndefElts &= ~(1ULL << IdxNo);
1518     break;
1519   }
1520   case Instruction::ShuffleVector: {
1521     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1522     uint64_t LHSVWidth =
1523       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1524     uint64_t LeftDemanded = 0, RightDemanded = 0;
1525     for (unsigned i = 0; i < VWidth; i++) {
1526       if (DemandedElts & (1ULL << i)) {
1527         unsigned MaskVal = Shuffle->getMaskValue(i);
1528         if (MaskVal != -1u) {
1529           assert(MaskVal < LHSVWidth * 2 &&
1530                  "shufflevector mask index out of range!");
1531           if (MaskVal < LHSVWidth)
1532             LeftDemanded |= 1ULL << MaskVal;
1533           else
1534             RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
1535         }
1536       }
1537     }
1538
1539     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1540                                       UndefElts2, Depth+1);
1541     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1542
1543     uint64_t UndefElts3;
1544     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1545                                       UndefElts3, Depth+1);
1546     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1547
1548     bool NewUndefElts = false;
1549     for (unsigned i = 0; i < VWidth; i++) {
1550       unsigned MaskVal = Shuffle->getMaskValue(i);
1551       if (MaskVal == -1u) {
1552         uint64_t NewBit = 1ULL << i;
1553         UndefElts |= NewBit;
1554       } else if (MaskVal < LHSVWidth) {
1555         uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1556         NewUndefElts |= NewBit;
1557         UndefElts |= NewBit;
1558       } else {
1559         uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
1560         NewUndefElts |= NewBit;
1561         UndefElts |= NewBit;
1562       }
1563     }
1564
1565     if (NewUndefElts) {
1566       // Add additional discovered undefs.
1567       std::vector<Constant*> Elts;
1568       for (unsigned i = 0; i < VWidth; ++i) {
1569         if (UndefElts & (1ULL << i))
1570           Elts.push_back(UndefValue::get(Type::Int32Ty));
1571         else
1572           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1573                                           Shuffle->getMaskValue(i)));
1574       }
1575       I->setOperand(2, ConstantVector::get(Elts));
1576       MadeChange = true;
1577     }
1578     break;
1579   }
1580   case Instruction::BitCast: {
1581     // Vector->vector casts only.
1582     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1583     if (!VTy) break;
1584     unsigned InVWidth = VTy->getNumElements();
1585     uint64_t InputDemandedElts = 0;
1586     unsigned Ratio;
1587
1588     if (VWidth == InVWidth) {
1589       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1590       // elements as are demanded of us.
1591       Ratio = 1;
1592       InputDemandedElts = DemandedElts;
1593     } else if (VWidth > InVWidth) {
1594       // Untested so far.
1595       break;
1596       
1597       // If there are more elements in the result than there are in the source,
1598       // then an input element is live if any of the corresponding output
1599       // elements are live.
1600       Ratio = VWidth/InVWidth;
1601       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1602         if (DemandedElts & (1ULL << OutIdx))
1603           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1604       }
1605     } else {
1606       // Untested so far.
1607       break;
1608       
1609       // If there are more elements in the source than there are in the result,
1610       // then an input element is live if the corresponding output element is
1611       // live.
1612       Ratio = InVWidth/VWidth;
1613       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1614         if (DemandedElts & (1ULL << InIdx/Ratio))
1615           InputDemandedElts |= 1ULL << InIdx;
1616     }
1617     
1618     // div/rem demand all inputs, because they don't want divide by zero.
1619     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1620                                       UndefElts2, Depth+1);
1621     if (TmpV) {
1622       I->setOperand(0, TmpV);
1623       MadeChange = true;
1624     }
1625     
1626     UndefElts = UndefElts2;
1627     if (VWidth > InVWidth) {
1628       assert(0 && "Unimp");
1629       // If there are more elements in the result than there are in the source,
1630       // then an output element is undef if the corresponding input element is
1631       // undef.
1632       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1633         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1634           UndefElts |= 1ULL << OutIdx;
1635     } else if (VWidth < InVWidth) {
1636       assert(0 && "Unimp");
1637       // If there are more elements in the source than there are in the result,
1638       // then a result element is undef if all of the corresponding input
1639       // elements are undef.
1640       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1641       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1642         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1643           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1644     }
1645     break;
1646   }
1647   case Instruction::And:
1648   case Instruction::Or:
1649   case Instruction::Xor:
1650   case Instruction::Add:
1651   case Instruction::Sub:
1652   case Instruction::Mul:
1653     // div/rem demand all inputs, because they don't want divide by zero.
1654     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1655                                       UndefElts, Depth+1);
1656     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1657     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1658                                       UndefElts2, Depth+1);
1659     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1660       
1661     // Output elements are undefined if both are undefined.  Consider things
1662     // like undef&0.  The result is known zero, not undef.
1663     UndefElts &= UndefElts2;
1664     break;
1665     
1666   case Instruction::Call: {
1667     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1668     if (!II) break;
1669     switch (II->getIntrinsicID()) {
1670     default: break;
1671       
1672     // Binary vector operations that work column-wise.  A dest element is a
1673     // function of the corresponding input elements from the two inputs.
1674     case Intrinsic::x86_sse_sub_ss:
1675     case Intrinsic::x86_sse_mul_ss:
1676     case Intrinsic::x86_sse_min_ss:
1677     case Intrinsic::x86_sse_max_ss:
1678     case Intrinsic::x86_sse2_sub_sd:
1679     case Intrinsic::x86_sse2_mul_sd:
1680     case Intrinsic::x86_sse2_min_sd:
1681     case Intrinsic::x86_sse2_max_sd:
1682       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1683                                         UndefElts, Depth+1);
1684       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1685       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1686                                         UndefElts2, Depth+1);
1687       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1688
1689       // If only the low elt is demanded and this is a scalarizable intrinsic,
1690       // scalarize it now.
1691       if (DemandedElts == 1) {
1692         switch (II->getIntrinsicID()) {
1693         default: break;
1694         case Intrinsic::x86_sse_sub_ss:
1695         case Intrinsic::x86_sse_mul_ss:
1696         case Intrinsic::x86_sse2_sub_sd:
1697         case Intrinsic::x86_sse2_mul_sd:
1698           // TODO: Lower MIN/MAX/ABS/etc
1699           Value *LHS = II->getOperand(1);
1700           Value *RHS = II->getOperand(2);
1701           // Extract the element as scalars.
1702           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1703           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1704           
1705           switch (II->getIntrinsicID()) {
1706           default: assert(0 && "Case stmts out of sync!");
1707           case Intrinsic::x86_sse_sub_ss:
1708           case Intrinsic::x86_sse2_sub_sd:
1709             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1710                                                         II->getName()), *II);
1711             break;
1712           case Intrinsic::x86_sse_mul_ss:
1713           case Intrinsic::x86_sse2_mul_sd:
1714             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1715                                                          II->getName()), *II);
1716             break;
1717           }
1718           
1719           Instruction *New =
1720             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1721                                       II->getName());
1722           InsertNewInstBefore(New, *II);
1723           AddSoonDeadInstToWorklist(*II, 0);
1724           return New;
1725         }            
1726       }
1727         
1728       // Output elements are undefined if both are undefined.  Consider things
1729       // like undef&0.  The result is known zero, not undef.
1730       UndefElts &= UndefElts2;
1731       break;
1732     }
1733     break;
1734   }
1735   }
1736   return MadeChange ? I : 0;
1737 }
1738
1739
1740 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1741 /// function is designed to check a chain of associative operators for a
1742 /// potential to apply a certain optimization.  Since the optimization may be
1743 /// applicable if the expression was reassociated, this checks the chain, then
1744 /// reassociates the expression as necessary to expose the optimization
1745 /// opportunity.  This makes use of a special Functor, which must define
1746 /// 'shouldApply' and 'apply' methods.
1747 ///
1748 template<typename Functor>
1749 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1750   unsigned Opcode = Root.getOpcode();
1751   Value *LHS = Root.getOperand(0);
1752
1753   // Quick check, see if the immediate LHS matches...
1754   if (F.shouldApply(LHS))
1755     return F.apply(Root);
1756
1757   // Otherwise, if the LHS is not of the same opcode as the root, return.
1758   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1759   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1760     // Should we apply this transform to the RHS?
1761     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1762
1763     // If not to the RHS, check to see if we should apply to the LHS...
1764     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1765       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1766       ShouldApply = true;
1767     }
1768
1769     // If the functor wants to apply the optimization to the RHS of LHSI,
1770     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1771     if (ShouldApply) {
1772       // Now all of the instructions are in the current basic block, go ahead
1773       // and perform the reassociation.
1774       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1775
1776       // First move the selected RHS to the LHS of the root...
1777       Root.setOperand(0, LHSI->getOperand(1));
1778
1779       // Make what used to be the LHS of the root be the user of the root...
1780       Value *ExtraOperand = TmpLHSI->getOperand(1);
1781       if (&Root == TmpLHSI) {
1782         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1783         return 0;
1784       }
1785       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1786       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1787       BasicBlock::iterator ARI = &Root; ++ARI;
1788       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1789       ARI = Root;
1790
1791       // Now propagate the ExtraOperand down the chain of instructions until we
1792       // get to LHSI.
1793       while (TmpLHSI != LHSI) {
1794         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1795         // Move the instruction to immediately before the chain we are
1796         // constructing to avoid breaking dominance properties.
1797         NextLHSI->moveBefore(ARI);
1798         ARI = NextLHSI;
1799
1800         Value *NextOp = NextLHSI->getOperand(1);
1801         NextLHSI->setOperand(1, ExtraOperand);
1802         TmpLHSI = NextLHSI;
1803         ExtraOperand = NextOp;
1804       }
1805
1806       // Now that the instructions are reassociated, have the functor perform
1807       // the transformation...
1808       return F.apply(Root);
1809     }
1810
1811     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1812   }
1813   return 0;
1814 }
1815
1816 namespace {
1817
1818 // AddRHS - Implements: X + X --> X << 1
1819 struct AddRHS {
1820   Value *RHS;
1821   AddRHS(Value *rhs) : RHS(rhs) {}
1822   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1823   Instruction *apply(BinaryOperator &Add) const {
1824     return BinaryOperator::CreateShl(Add.getOperand(0),
1825                                      ConstantInt::get(Add.getType(), 1));
1826   }
1827 };
1828
1829 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1830 //                 iff C1&C2 == 0
1831 struct AddMaskingAnd {
1832   Constant *C2;
1833   AddMaskingAnd(Constant *c) : C2(c) {}
1834   bool shouldApply(Value *LHS) const {
1835     ConstantInt *C1;
1836     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1837            ConstantExpr::getAnd(C1, C2)->isNullValue();
1838   }
1839   Instruction *apply(BinaryOperator &Add) const {
1840     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1841   }
1842 };
1843
1844 }
1845
1846 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1847                                              InstCombiner *IC) {
1848   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1849     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1850   }
1851
1852   // Figure out if the constant is the left or the right argument.
1853   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1854   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1855
1856   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1857     if (ConstIsRHS)
1858       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1859     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1860   }
1861
1862   Value *Op0 = SO, *Op1 = ConstOperand;
1863   if (!ConstIsRHS)
1864     std::swap(Op0, Op1);
1865   Instruction *New;
1866   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1867     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1868   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1869     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1870                           SO->getName()+".cmp");
1871   else {
1872     assert(0 && "Unknown binary instruction type!");
1873     abort();
1874   }
1875   return IC->InsertNewInstBefore(New, I);
1876 }
1877
1878 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1879 // constant as the other operand, try to fold the binary operator into the
1880 // select arguments.  This also works for Cast instructions, which obviously do
1881 // not have a second operand.
1882 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1883                                      InstCombiner *IC) {
1884   // Don't modify shared select instructions
1885   if (!SI->hasOneUse()) return 0;
1886   Value *TV = SI->getOperand(1);
1887   Value *FV = SI->getOperand(2);
1888
1889   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1890     // Bool selects with constant operands can be folded to logical ops.
1891     if (SI->getType() == Type::Int1Ty) return 0;
1892
1893     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1894     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1895
1896     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1897                               SelectFalseVal);
1898   }
1899   return 0;
1900 }
1901
1902
1903 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1904 /// node as operand #0, see if we can fold the instruction into the PHI (which
1905 /// is only possible if all operands to the PHI are constants).
1906 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1907   PHINode *PN = cast<PHINode>(I.getOperand(0));
1908   unsigned NumPHIValues = PN->getNumIncomingValues();
1909   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1910
1911   // Check to see if all of the operands of the PHI are constants.  If there is
1912   // one non-constant value, remember the BB it is.  If there is more than one
1913   // or if *it* is a PHI, bail out.
1914   BasicBlock *NonConstBB = 0;
1915   for (unsigned i = 0; i != NumPHIValues; ++i)
1916     if (!isa<Constant>(PN->getIncomingValue(i))) {
1917       if (NonConstBB) return 0;  // More than one non-const value.
1918       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1919       NonConstBB = PN->getIncomingBlock(i);
1920       
1921       // If the incoming non-constant value is in I's block, we have an infinite
1922       // loop.
1923       if (NonConstBB == I.getParent())
1924         return 0;
1925     }
1926   
1927   // If there is exactly one non-constant value, we can insert a copy of the
1928   // operation in that block.  However, if this is a critical edge, we would be
1929   // inserting the computation one some other paths (e.g. inside a loop).  Only
1930   // do this if the pred block is unconditionally branching into the phi block.
1931   if (NonConstBB) {
1932     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1933     if (!BI || !BI->isUnconditional()) return 0;
1934   }
1935
1936   // Okay, we can do the transformation: create the new PHI node.
1937   PHINode *NewPN = PHINode::Create(I.getType(), "");
1938   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1939   InsertNewInstBefore(NewPN, *PN);
1940   NewPN->takeName(PN);
1941
1942   // Next, add all of the operands to the PHI.
1943   if (I.getNumOperands() == 2) {
1944     Constant *C = cast<Constant>(I.getOperand(1));
1945     for (unsigned i = 0; i != NumPHIValues; ++i) {
1946       Value *InV = 0;
1947       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1948         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1949           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1950         else
1951           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1952       } else {
1953         assert(PN->getIncomingBlock(i) == NonConstBB);
1954         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1955           InV = BinaryOperator::Create(BO->getOpcode(),
1956                                        PN->getIncomingValue(i), C, "phitmp",
1957                                        NonConstBB->getTerminator());
1958         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1959           InV = CmpInst::Create(CI->getOpcode(), 
1960                                 CI->getPredicate(),
1961                                 PN->getIncomingValue(i), C, "phitmp",
1962                                 NonConstBB->getTerminator());
1963         else
1964           assert(0 && "Unknown binop!");
1965         
1966         AddToWorkList(cast<Instruction>(InV));
1967       }
1968       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1969     }
1970   } else { 
1971     CastInst *CI = cast<CastInst>(&I);
1972     const Type *RetTy = CI->getType();
1973     for (unsigned i = 0; i != NumPHIValues; ++i) {
1974       Value *InV;
1975       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1976         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1977       } else {
1978         assert(PN->getIncomingBlock(i) == NonConstBB);
1979         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1980                                I.getType(), "phitmp", 
1981                                NonConstBB->getTerminator());
1982         AddToWorkList(cast<Instruction>(InV));
1983       }
1984       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1985     }
1986   }
1987   return ReplaceInstUsesWith(I, NewPN);
1988 }
1989
1990
1991 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1992 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1993 /// This basically requires proving that the add in the original type would not
1994 /// overflow to change the sign bit or have a carry out.
1995 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1996   // There are different heuristics we can use for this.  Here are some simple
1997   // ones.
1998   
1999   // Add has the property that adding any two 2's complement numbers can only 
2000   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2001   // have at least two sign bits, we know that the addition of the two values will
2002   // sign extend fine.
2003   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2004     return true;
2005   
2006   
2007   // If one of the operands only has one non-zero bit, and if the other operand
2008   // has a known-zero bit in a more significant place than it (not including the
2009   // sign bit) the ripple may go up to and fill the zero, but won't change the
2010   // sign.  For example, (X & ~4) + 1.
2011   
2012   // TODO: Implement.
2013   
2014   return false;
2015 }
2016
2017
2018 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2019   bool Changed = SimplifyCommutative(I);
2020   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2021
2022   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2023     // X + undef -> undef
2024     if (isa<UndefValue>(RHS))
2025       return ReplaceInstUsesWith(I, RHS);
2026
2027     // X + 0 --> X
2028     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2029       if (RHSC->isNullValue())
2030         return ReplaceInstUsesWith(I, LHS);
2031     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2032       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2033                               (I.getType())->getValueAPF()))
2034         return ReplaceInstUsesWith(I, LHS);
2035     }
2036
2037     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2038       // X + (signbit) --> X ^ signbit
2039       const APInt& Val = CI->getValue();
2040       uint32_t BitWidth = Val.getBitWidth();
2041       if (Val == APInt::getSignBit(BitWidth))
2042         return BinaryOperator::CreateXor(LHS, RHS);
2043       
2044       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2045       // (X & 254)+1 -> (X&254)|1
2046       if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2047         return &I;
2048
2049       // zext(i1) - 1  ->  select i1, 0, -1
2050       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2051         if (CI->isAllOnesValue() &&
2052             ZI->getOperand(0)->getType() == Type::Int1Ty)
2053           return SelectInst::Create(ZI->getOperand(0),
2054                                     Constant::getNullValue(I.getType()),
2055                                     ConstantInt::getAllOnesValue(I.getType()));
2056     }
2057
2058     if (isa<PHINode>(LHS))
2059       if (Instruction *NV = FoldOpIntoPhi(I))
2060         return NV;
2061     
2062     ConstantInt *XorRHS = 0;
2063     Value *XorLHS = 0;
2064     if (isa<ConstantInt>(RHSC) &&
2065         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2066       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2067       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2068       
2069       uint32_t Size = TySizeBits / 2;
2070       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2071       APInt CFF80Val(-C0080Val);
2072       do {
2073         if (TySizeBits > Size) {
2074           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2075           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2076           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2077               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2078             // This is a sign extend if the top bits are known zero.
2079             if (!MaskedValueIsZero(XorLHS, 
2080                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2081               Size = 0;  // Not a sign ext, but can't be any others either.
2082             break;
2083           }
2084         }
2085         Size >>= 1;
2086         C0080Val = APIntOps::lshr(C0080Val, Size);
2087         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2088       } while (Size >= 1);
2089       
2090       // FIXME: This shouldn't be necessary. When the backends can handle types
2091       // with funny bit widths then this switch statement should be removed. It
2092       // is just here to get the size of the "middle" type back up to something
2093       // that the back ends can handle.
2094       const Type *MiddleType = 0;
2095       switch (Size) {
2096         default: break;
2097         case 32: MiddleType = Type::Int32Ty; break;
2098         case 16: MiddleType = Type::Int16Ty; break;
2099         case  8: MiddleType = Type::Int8Ty; break;
2100       }
2101       if (MiddleType) {
2102         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2103         InsertNewInstBefore(NewTrunc, I);
2104         return new SExtInst(NewTrunc, I.getType(), I.getName());
2105       }
2106     }
2107   }
2108
2109   if (I.getType() == Type::Int1Ty)
2110     return BinaryOperator::CreateXor(LHS, RHS);
2111
2112   // X + X --> X << 1
2113   if (I.getType()->isInteger()) {
2114     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2115
2116     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2117       if (RHSI->getOpcode() == Instruction::Sub)
2118         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2119           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2120     }
2121     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2122       if (LHSI->getOpcode() == Instruction::Sub)
2123         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2124           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2125     }
2126   }
2127
2128   // -A + B  -->  B - A
2129   // -A + -B  -->  -(A + B)
2130   if (Value *LHSV = dyn_castNegVal(LHS)) {
2131     if (LHS->getType()->isIntOrIntVector()) {
2132       if (Value *RHSV = dyn_castNegVal(RHS)) {
2133         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2134         InsertNewInstBefore(NewAdd, I);
2135         return BinaryOperator::CreateNeg(NewAdd);
2136       }
2137     }
2138     
2139     return BinaryOperator::CreateSub(RHS, LHSV);
2140   }
2141
2142   // A + -B  -->  A - B
2143   if (!isa<Constant>(RHS))
2144     if (Value *V = dyn_castNegVal(RHS))
2145       return BinaryOperator::CreateSub(LHS, V);
2146
2147
2148   ConstantInt *C2;
2149   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2150     if (X == RHS)   // X*C + X --> X * (C+1)
2151       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2152
2153     // X*C1 + X*C2 --> X * (C1+C2)
2154     ConstantInt *C1;
2155     if (X == dyn_castFoldableMul(RHS, C1))
2156       return BinaryOperator::CreateMul(X, Add(C1, C2));
2157   }
2158
2159   // X + X*C --> X * (C+1)
2160   if (dyn_castFoldableMul(RHS, C2) == LHS)
2161     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2162
2163   // X + ~X --> -1   since   ~X = -X-1
2164   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2165     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2166   
2167
2168   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2169   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2170     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2171       return R;
2172   
2173   // A+B --> A|B iff A and B have no bits set in common.
2174   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2175     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2176     APInt LHSKnownOne(IT->getBitWidth(), 0);
2177     APInt LHSKnownZero(IT->getBitWidth(), 0);
2178     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2179     if (LHSKnownZero != 0) {
2180       APInt RHSKnownOne(IT->getBitWidth(), 0);
2181       APInt RHSKnownZero(IT->getBitWidth(), 0);
2182       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2183       
2184       // No bits in common -> bitwise or.
2185       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2186         return BinaryOperator::CreateOr(LHS, RHS);
2187     }
2188   }
2189
2190   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2191   if (I.getType()->isIntOrIntVector()) {
2192     Value *W, *X, *Y, *Z;
2193     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2194         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2195       if (W != Y) {
2196         if (W == Z) {
2197           std::swap(Y, Z);
2198         } else if (Y == X) {
2199           std::swap(W, X);
2200         } else if (X == Z) {
2201           std::swap(Y, Z);
2202           std::swap(W, X);
2203         }
2204       }
2205
2206       if (W == Y) {
2207         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2208                                                             LHS->getName()), I);
2209         return BinaryOperator::CreateMul(W, NewAdd);
2210       }
2211     }
2212   }
2213
2214   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2215     Value *X = 0;
2216     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2217       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2218
2219     // (X & FF00) + xx00  -> (X+xx00) & FF00
2220     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2221       Constant *Anded = And(CRHS, C2);
2222       if (Anded == CRHS) {
2223         // See if all bits from the first bit set in the Add RHS up are included
2224         // in the mask.  First, get the rightmost bit.
2225         const APInt& AddRHSV = CRHS->getValue();
2226
2227         // Form a mask of all bits from the lowest bit added through the top.
2228         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2229
2230         // See if the and mask includes all of these bits.
2231         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2232
2233         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2234           // Okay, the xform is safe.  Insert the new add pronto.
2235           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2236                                                             LHS->getName()), I);
2237           return BinaryOperator::CreateAnd(NewAdd, C2);
2238         }
2239       }
2240     }
2241
2242     // Try to fold constant add into select arguments.
2243     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2244       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2245         return R;
2246   }
2247
2248   // add (cast *A to intptrtype) B -> 
2249   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2250   {
2251     CastInst *CI = dyn_cast<CastInst>(LHS);
2252     Value *Other = RHS;
2253     if (!CI) {
2254       CI = dyn_cast<CastInst>(RHS);
2255       Other = LHS;
2256     }
2257     if (CI && CI->getType()->isSized() && 
2258         (CI->getType()->getPrimitiveSizeInBits() == 
2259          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2260         && isa<PointerType>(CI->getOperand(0)->getType())) {
2261       unsigned AS =
2262         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2263       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2264                                       PointerType::get(Type::Int8Ty, AS), I);
2265       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2266       return new PtrToIntInst(I2, CI->getType());
2267     }
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()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2286         // Fold the add into the true select value.
2287         return SelectInst::Create(SI->getCondition(), N, A);
2288       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2289         // Fold the add into the false select value.
2290         return SelectInst::Create(SI->getCondition(), A, N);
2291     }
2292   }
2293   
2294   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2295   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2296     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2297       return ReplaceInstUsesWith(I, LHS);
2298
2299   // Check for (add (sext x), y), see if we can merge this into an
2300   // integer add followed by a sext.
2301   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2302     // (add (sext x), cst) --> (sext (add x, cst'))
2303     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2304       Constant *CI = 
2305         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2306       if (LHSConv->hasOneUse() &&
2307           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2308           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2309         // Insert the new, smaller add.
2310         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2311                                                         CI, "addconv");
2312         InsertNewInstBefore(NewAdd, I);
2313         return new SExtInst(NewAdd, I.getType());
2314       }
2315     }
2316     
2317     // (add (sext x), (sext y)) --> (sext (add int x, y))
2318     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2319       // Only do this if x/y have the same type, if at last one of them has a
2320       // single use (so we don't increase the number of sexts), and if the
2321       // integer add will not overflow.
2322       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2323           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2324           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2325                                    RHSConv->getOperand(0))) {
2326         // Insert the new integer add.
2327         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2328                                                         RHSConv->getOperand(0),
2329                                                         "addconv");
2330         InsertNewInstBefore(NewAdd, I);
2331         return new SExtInst(NewAdd, I.getType());
2332       }
2333     }
2334   }
2335   
2336   // Check for (add double (sitofp x), y), see if we can merge this into an
2337   // integer add followed by a promotion.
2338   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2339     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2340     // ... if the constant fits in the integer value.  This is useful for things
2341     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2342     // requires a constant pool load, and generally allows the add to be better
2343     // instcombined.
2344     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2345       Constant *CI = 
2346       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2347       if (LHSConv->hasOneUse() &&
2348           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2349           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2350         // Insert the new integer add.
2351         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2352                                                         CI, "addconv");
2353         InsertNewInstBefore(NewAdd, I);
2354         return new SIToFPInst(NewAdd, I.getType());
2355       }
2356     }
2357     
2358     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2359     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2360       // Only do this if x/y have the same type, if at last one of them has a
2361       // single use (so we don't increase the number of int->fp conversions),
2362       // and if the integer add will not overflow.
2363       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2364           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2365           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2366                                    RHSConv->getOperand(0))) {
2367         // Insert the new integer add.
2368         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2369                                                         RHSConv->getOperand(0),
2370                                                         "addconv");
2371         InsertNewInstBefore(NewAdd, I);
2372         return new SIToFPInst(NewAdd, I.getType());
2373       }
2374     }
2375   }
2376   
2377   return Changed ? &I : 0;
2378 }
2379
2380 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2381   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2382
2383   if (Op0 == Op1 &&                        // sub X, X  -> 0
2384       !I.getType()->isFPOrFPVector())
2385     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2386
2387   // If this is a 'B = x-(-A)', change to B = x+A...
2388   if (Value *V = dyn_castNegVal(Op1))
2389     return BinaryOperator::CreateAdd(Op0, V);
2390
2391   if (isa<UndefValue>(Op0))
2392     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2393   if (isa<UndefValue>(Op1))
2394     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2395
2396   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2397     // Replace (-1 - A) with (~A)...
2398     if (C->isAllOnesValue())
2399       return BinaryOperator::CreateNot(Op1);
2400
2401     // C - ~X == X + (1+C)
2402     Value *X = 0;
2403     if (match(Op1, m_Not(m_Value(X))))
2404       return BinaryOperator::CreateAdd(X, AddOne(C));
2405
2406     // -(X >>u 31) -> (X >>s 31)
2407     // -(X >>s 31) -> (X >>u 31)
2408     if (C->isZero()) {
2409       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2410         if (SI->getOpcode() == Instruction::LShr) {
2411           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2412             // Check to see if we are shifting out everything but the sign bit.
2413             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2414                 SI->getType()->getPrimitiveSizeInBits()-1) {
2415               // Ok, the transformation is safe.  Insert AShr.
2416               return BinaryOperator::Create(Instruction::AShr, 
2417                                           SI->getOperand(0), CU, SI->getName());
2418             }
2419           }
2420         }
2421         else if (SI->getOpcode() == Instruction::AShr) {
2422           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2423             // Check to see if we are shifting out everything but the sign bit.
2424             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2425                 SI->getType()->getPrimitiveSizeInBits()-1) {
2426               // Ok, the transformation is safe.  Insert LShr. 
2427               return BinaryOperator::CreateLShr(
2428                                           SI->getOperand(0), CU, SI->getName());
2429             }
2430           }
2431         }
2432       }
2433     }
2434
2435     // Try to fold constant sub into select arguments.
2436     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2437       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2438         return R;
2439   }
2440
2441   if (I.getType() == Type::Int1Ty)
2442     return BinaryOperator::CreateXor(Op0, Op1);
2443
2444   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2445     if (Op1I->getOpcode() == Instruction::Add &&
2446         !Op0->getType()->isFPOrFPVector()) {
2447       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2448         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2449       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2450         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2451       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2452         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2453           // C1-(X+C2) --> (C1-C2)-X
2454           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2455                                            Op1I->getOperand(0));
2456       }
2457     }
2458
2459     if (Op1I->hasOneUse()) {
2460       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2461       // is not used by anyone else...
2462       //
2463       if (Op1I->getOpcode() == Instruction::Sub &&
2464           !Op1I->getType()->isFPOrFPVector()) {
2465         // Swap the two operands of the subexpr...
2466         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2467         Op1I->setOperand(0, IIOp1);
2468         Op1I->setOperand(1, IIOp0);
2469
2470         // Create the new top level add instruction...
2471         return BinaryOperator::CreateAdd(Op0, Op1);
2472       }
2473
2474       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2475       //
2476       if (Op1I->getOpcode() == Instruction::And &&
2477           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2478         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2479
2480         Value *NewNot =
2481           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2482         return BinaryOperator::CreateAnd(Op0, NewNot);
2483       }
2484
2485       // 0 - (X sdiv C)  -> (X sdiv -C)
2486       if (Op1I->getOpcode() == Instruction::SDiv)
2487         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2488           if (CSI->isZero())
2489             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2490               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2491                                                ConstantExpr::getNeg(DivRHS));
2492
2493       // X - X*C --> X * (1-C)
2494       ConstantInt *C2 = 0;
2495       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2496         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2497         return BinaryOperator::CreateMul(Op0, CP1);
2498       }
2499     }
2500   }
2501
2502   if (!Op0->getType()->isFPOrFPVector())
2503     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2504       if (Op0I->getOpcode() == Instruction::Add) {
2505         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2506           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2507         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2508           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2509       } else if (Op0I->getOpcode() == Instruction::Sub) {
2510         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2511           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2512       }
2513     }
2514
2515   ConstantInt *C1;
2516   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2517     if (X == Op1)  // X*C - X --> X * (C-1)
2518       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2519
2520     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2521     if (X == dyn_castFoldableMul(Op1, C2))
2522       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2523   }
2524   return 0;
2525 }
2526
2527 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2528 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2529 /// TrueIfSigned if the result of the comparison is true when the input value is
2530 /// signed.
2531 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2532                            bool &TrueIfSigned) {
2533   switch (pred) {
2534   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2535     TrueIfSigned = true;
2536     return RHS->isZero();
2537   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2538     TrueIfSigned = true;
2539     return RHS->isAllOnesValue();
2540   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2541     TrueIfSigned = false;
2542     return RHS->isAllOnesValue();
2543   case ICmpInst::ICMP_UGT:
2544     // True if LHS u> RHS and RHS == high-bit-mask - 1
2545     TrueIfSigned = true;
2546     return RHS->getValue() ==
2547       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2548   case ICmpInst::ICMP_UGE: 
2549     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2550     TrueIfSigned = true;
2551     return RHS->getValue().isSignBit();
2552   default:
2553     return false;
2554   }
2555 }
2556
2557 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2558   bool Changed = SimplifyCommutative(I);
2559   Value *Op0 = I.getOperand(0);
2560
2561   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2562     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2563
2564   // Simplify mul instructions with a constant RHS...
2565   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2566     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2567
2568       // ((X << C1)*C2) == (X * (C2 << C1))
2569       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2570         if (SI->getOpcode() == Instruction::Shl)
2571           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2572             return BinaryOperator::CreateMul(SI->getOperand(0),
2573                                              ConstantExpr::getShl(CI, ShOp));
2574
2575       if (CI->isZero())
2576         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2577       if (CI->equalsInt(1))                  // X * 1  == X
2578         return ReplaceInstUsesWith(I, Op0);
2579       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2580         return BinaryOperator::CreateNeg(Op0, I.getName());
2581
2582       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2583       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2584         return BinaryOperator::CreateShl(Op0,
2585                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2586       }
2587     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2588       if (Op1F->isNullValue())
2589         return ReplaceInstUsesWith(I, Op1);
2590
2591       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2592       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2593       if (Op1F->isExactlyValue(1.0))
2594         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2595     } else if (isa<VectorType>(Op1->getType())) {
2596       if (isa<ConstantAggregateZero>(Op1))
2597         return ReplaceInstUsesWith(I, Op1);
2598
2599       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2600         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2601           return BinaryOperator::CreateNeg(Op0, I.getName());
2602
2603         // As above, vector X*splat(1.0) -> X in all defined cases.
2604         if (Constant *Splat = Op1V->getSplatValue()) {
2605           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2606             if (F->isExactlyValue(1.0))
2607               return ReplaceInstUsesWith(I, Op0);
2608           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2609             if (CI->equalsInt(1))
2610               return ReplaceInstUsesWith(I, Op0);
2611         }
2612       }
2613     }
2614     
2615     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2616       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2617           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2618         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2619         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2620                                                      Op1, "tmp");
2621         InsertNewInstBefore(Add, I);
2622         Value *C1C2 = ConstantExpr::getMul(Op1, 
2623                                            cast<Constant>(Op0I->getOperand(1)));
2624         return BinaryOperator::CreateAdd(Add, C1C2);
2625         
2626       }
2627
2628     // Try to fold constant mul into select arguments.
2629     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2630       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2631         return R;
2632
2633     if (isa<PHINode>(Op0))
2634       if (Instruction *NV = FoldOpIntoPhi(I))
2635         return NV;
2636   }
2637
2638   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2639     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2640       return BinaryOperator::CreateMul(Op0v, Op1v);
2641
2642   // (X / Y) *  Y = X - (X % Y)
2643   // (X / Y) * -Y = (X % Y) - X
2644   {
2645     Value *Op1 = I.getOperand(1);
2646     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2647     if (!BO ||
2648         (BO->getOpcode() != Instruction::UDiv && 
2649          BO->getOpcode() != Instruction::SDiv)) {
2650       Op1 = Op0;
2651       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2652     }
2653     Value *Neg = dyn_castNegVal(Op1);
2654     if (BO && BO->hasOneUse() &&
2655         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2656         (BO->getOpcode() == Instruction::UDiv ||
2657          BO->getOpcode() == Instruction::SDiv)) {
2658       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2659
2660       Instruction *Rem;
2661       if (BO->getOpcode() == Instruction::UDiv)
2662         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2663       else
2664         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2665
2666       InsertNewInstBefore(Rem, I);
2667       Rem->takeName(BO);
2668
2669       if (Op1BO == Op1)
2670         return BinaryOperator::CreateSub(Op0BO, Rem);
2671       else
2672         return BinaryOperator::CreateSub(Rem, Op0BO);
2673     }
2674   }
2675
2676   if (I.getType() == Type::Int1Ty)
2677     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2678
2679   // If one of the operands of the multiply is a cast from a boolean value, then
2680   // we know the bool is either zero or one, so this is a 'masking' multiply.
2681   // See if we can simplify things based on how the boolean was originally
2682   // formed.
2683   CastInst *BoolCast = 0;
2684   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2685     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2686       BoolCast = CI;
2687   if (!BoolCast)
2688     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2689       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2690         BoolCast = CI;
2691   if (BoolCast) {
2692     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2693       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2694       const Type *SCOpTy = SCIOp0->getType();
2695       bool TIS = false;
2696       
2697       // If the icmp is true iff the sign bit of X is set, then convert this
2698       // multiply into a shift/and combination.
2699       if (isa<ConstantInt>(SCIOp1) &&
2700           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2701           TIS) {
2702         // Shift the X value right to turn it into "all signbits".
2703         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2704                                           SCOpTy->getPrimitiveSizeInBits()-1);
2705         Value *V =
2706           InsertNewInstBefore(
2707             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2708                                             BoolCast->getOperand(0)->getName()+
2709                                             ".mask"), I);
2710
2711         // If the multiply type is not the same as the source type, sign extend
2712         // or truncate to the multiply type.
2713         if (I.getType() != V->getType()) {
2714           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2715           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2716           Instruction::CastOps opcode = 
2717             (SrcBits == DstBits ? Instruction::BitCast : 
2718              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2719           V = InsertCastBefore(opcode, V, I.getType(), I);
2720         }
2721
2722         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2723         return BinaryOperator::CreateAnd(V, OtherOp);
2724       }
2725     }
2726   }
2727
2728   return Changed ? &I : 0;
2729 }
2730
2731 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2732 /// instruction.
2733 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2734   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2735   
2736   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2737   int NonNullOperand = -1;
2738   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2739     if (ST->isNullValue())
2740       NonNullOperand = 2;
2741   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2742   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2743     if (ST->isNullValue())
2744       NonNullOperand = 1;
2745   
2746   if (NonNullOperand == -1)
2747     return false;
2748   
2749   Value *SelectCond = SI->getOperand(0);
2750   
2751   // Change the div/rem to use 'Y' instead of the select.
2752   I.setOperand(1, SI->getOperand(NonNullOperand));
2753   
2754   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2755   // problem.  However, the select, or the condition of the select may have
2756   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2757   // propagate the known value for the select into other uses of it, and
2758   // propagate a known value of the condition into its other users.
2759   
2760   // If the select and condition only have a single use, don't bother with this,
2761   // early exit.
2762   if (SI->use_empty() && SelectCond->hasOneUse())
2763     return true;
2764   
2765   // Scan the current block backward, looking for other uses of SI.
2766   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2767   
2768   while (BBI != BBFront) {
2769     --BBI;
2770     // If we found a call to a function, we can't assume it will return, so
2771     // information from below it cannot be propagated above it.
2772     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2773       break;
2774     
2775     // Replace uses of the select or its condition with the known values.
2776     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2777          I != E; ++I) {
2778       if (*I == SI) {
2779         *I = SI->getOperand(NonNullOperand);
2780         AddToWorkList(BBI);
2781       } else if (*I == SelectCond) {
2782         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2783                                    ConstantInt::getFalse();
2784         AddToWorkList(BBI);
2785       }
2786     }
2787     
2788     // If we past the instruction, quit looking for it.
2789     if (&*BBI == SI)
2790       SI = 0;
2791     if (&*BBI == SelectCond)
2792       SelectCond = 0;
2793     
2794     // If we ran out of things to eliminate, break out of the loop.
2795     if (SelectCond == 0 && SI == 0)
2796       break;
2797     
2798   }
2799   return true;
2800 }
2801
2802
2803 /// This function implements the transforms on div instructions that work
2804 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2805 /// used by the visitors to those instructions.
2806 /// @brief Transforms common to all three div instructions
2807 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2808   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2809
2810   // undef / X -> 0        for integer.
2811   // undef / X -> undef    for FP (the undef could be a snan).
2812   if (isa<UndefValue>(Op0)) {
2813     if (Op0->getType()->isFPOrFPVector())
2814       return ReplaceInstUsesWith(I, Op0);
2815     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2816   }
2817
2818   // X / undef -> undef
2819   if (isa<UndefValue>(Op1))
2820     return ReplaceInstUsesWith(I, Op1);
2821
2822   return 0;
2823 }
2824
2825 /// This function implements the transforms common to both integer division
2826 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2827 /// division instructions.
2828 /// @brief Common integer divide transforms
2829 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2830   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2831
2832   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2833   if (Op0 == Op1) {
2834     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2835       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2836       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2837       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2838     }
2839
2840     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2841     return ReplaceInstUsesWith(I, CI);
2842   }
2843   
2844   if (Instruction *Common = commonDivTransforms(I))
2845     return Common;
2846   
2847   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2848   // This does not apply for fdiv.
2849   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2850     return &I;
2851
2852   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2853     // div X, 1 == X
2854     if (RHS->equalsInt(1))
2855       return ReplaceInstUsesWith(I, Op0);
2856
2857     // (X / C1) / C2  -> X / (C1*C2)
2858     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2859       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2860         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2861           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2862             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2863           else 
2864             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2865                                           Multiply(RHS, LHSRHS));
2866         }
2867
2868     if (!RHS->isZero()) { // avoid X udiv 0
2869       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2870         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2871           return R;
2872       if (isa<PHINode>(Op0))
2873         if (Instruction *NV = FoldOpIntoPhi(I))
2874           return NV;
2875     }
2876   }
2877
2878   // 0 / X == 0, we don't need to preserve faults!
2879   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2880     if (LHS->equalsInt(0))
2881       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2882
2883   // It can't be division by zero, hence it must be division by one.
2884   if (I.getType() == Type::Int1Ty)
2885     return ReplaceInstUsesWith(I, Op0);
2886
2887   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2888     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2889       // div X, 1 == X
2890       if (X->isOne())
2891         return ReplaceInstUsesWith(I, Op0);
2892   }
2893
2894   return 0;
2895 }
2896
2897 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2898   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2899
2900   // Handle the integer div common cases
2901   if (Instruction *Common = commonIDivTransforms(I))
2902     return Common;
2903
2904   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2905     // X udiv C^2 -> X >> C
2906     // Check to see if this is an unsigned division with an exact power of 2,
2907     // if so, convert to a right shift.
2908     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2909       return BinaryOperator::CreateLShr(Op0, 
2910                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2911
2912     // X udiv C, where C >= signbit
2913     if (C->getValue().isNegative()) {
2914       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2915                                       I);
2916       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2917                                 ConstantInt::get(I.getType(), 1));
2918     }
2919   }
2920
2921   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2922   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2923     if (RHSI->getOpcode() == Instruction::Shl &&
2924         isa<ConstantInt>(RHSI->getOperand(0))) {
2925       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2926       if (C1.isPowerOf2()) {
2927         Value *N = RHSI->getOperand(1);
2928         const Type *NTy = N->getType();
2929         if (uint32_t C2 = C1.logBase2()) {
2930           Constant *C2V = ConstantInt::get(NTy, C2);
2931           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2932         }
2933         return BinaryOperator::CreateLShr(Op0, N);
2934       }
2935     }
2936   }
2937   
2938   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2939   // where C1&C2 are powers of two.
2940   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2941     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2942       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2943         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2944         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2945           // Compute the shift amounts
2946           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2947           // Construct the "on true" case of the select
2948           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2949           Instruction *TSI = BinaryOperator::CreateLShr(
2950                                                  Op0, TC, SI->getName()+".t");
2951           TSI = InsertNewInstBefore(TSI, I);
2952   
2953           // Construct the "on false" case of the select
2954           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2955           Instruction *FSI = BinaryOperator::CreateLShr(
2956                                                  Op0, FC, SI->getName()+".f");
2957           FSI = InsertNewInstBefore(FSI, I);
2958
2959           // construct the select instruction and return it.
2960           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2961         }
2962       }
2963   return 0;
2964 }
2965
2966 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2967   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2968
2969   // Handle the integer div common cases
2970   if (Instruction *Common = commonIDivTransforms(I))
2971     return Common;
2972
2973   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2974     // sdiv X, -1 == -X
2975     if (RHS->isAllOnesValue())
2976       return BinaryOperator::CreateNeg(Op0);
2977   }
2978
2979   // If the sign bits of both operands are zero (i.e. we can prove they are
2980   // unsigned inputs), turn this into a udiv.
2981   if (I.getType()->isInteger()) {
2982     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2983     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2984       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2985       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2986     }
2987   }      
2988   
2989   return 0;
2990 }
2991
2992 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2993   return commonDivTransforms(I);
2994 }
2995
2996 /// This function implements the transforms on rem instructions that work
2997 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2998 /// is used by the visitors to those instructions.
2999 /// @brief Transforms common to all three rem instructions
3000 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3001   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3002
3003   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3004     if (I.getType()->isFPOrFPVector())
3005       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3006     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3007   }
3008   if (isa<UndefValue>(Op1))
3009     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3010
3011   // Handle cases involving: rem X, (select Cond, Y, Z)
3012   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3013     return &I;
3014
3015   return 0;
3016 }
3017
3018 /// This function implements the transforms common to both integer remainder
3019 /// instructions (urem and srem). It is called by the visitors to those integer
3020 /// remainder instructions.
3021 /// @brief Common integer remainder transforms
3022 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3023   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3024
3025   if (Instruction *common = commonRemTransforms(I))
3026     return common;
3027
3028   // 0 % X == 0 for integer, we don't need to preserve faults!
3029   if (Constant *LHS = dyn_cast<Constant>(Op0))
3030     if (LHS->isNullValue())
3031       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3032
3033   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3034     // X % 0 == undef, we don't need to preserve faults!
3035     if (RHS->equalsInt(0))
3036       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3037     
3038     if (RHS->equalsInt(1))  // X % 1 == 0
3039       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3040
3041     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3042       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3043         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3044           return R;
3045       } else if (isa<PHINode>(Op0I)) {
3046         if (Instruction *NV = FoldOpIntoPhi(I))
3047           return NV;
3048       }
3049
3050       // See if we can fold away this rem instruction.
3051       if (SimplifyDemandedInstructionBits(I))
3052         return &I;
3053     }
3054   }
3055
3056   return 0;
3057 }
3058
3059 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3060   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3061
3062   if (Instruction *common = commonIRemTransforms(I))
3063     return common;
3064   
3065   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3066     // X urem C^2 -> X and C
3067     // Check to see if this is an unsigned remainder with an exact power of 2,
3068     // if so, convert to a bitwise and.
3069     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3070       if (C->getValue().isPowerOf2())
3071         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3072   }
3073
3074   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3075     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3076     if (RHSI->getOpcode() == Instruction::Shl &&
3077         isa<ConstantInt>(RHSI->getOperand(0))) {
3078       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3079         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3080         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3081                                                                    "tmp"), I);
3082         return BinaryOperator::CreateAnd(Op0, Add);
3083       }
3084     }
3085   }
3086
3087   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3088   // where C1&C2 are powers of two.
3089   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3090     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3091       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3092         // STO == 0 and SFO == 0 handled above.
3093         if ((STO->getValue().isPowerOf2()) && 
3094             (SFO->getValue().isPowerOf2())) {
3095           Value *TrueAnd = InsertNewInstBefore(
3096             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3097           Value *FalseAnd = InsertNewInstBefore(
3098             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3099           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3100         }
3101       }
3102   }
3103   
3104   return 0;
3105 }
3106
3107 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3108   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3109
3110   // Handle the integer rem common cases
3111   if (Instruction *common = commonIRemTransforms(I))
3112     return common;
3113   
3114   if (Value *RHSNeg = dyn_castNegVal(Op1))
3115     if (!isa<Constant>(RHSNeg) ||
3116         (isa<ConstantInt>(RHSNeg) &&
3117          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3118       // X % -Y -> X % Y
3119       AddUsesToWorkList(I);
3120       I.setOperand(1, RHSNeg);
3121       return &I;
3122     }
3123
3124   // If the sign bits of both operands are zero (i.e. we can prove they are
3125   // unsigned inputs), turn this into a urem.
3126   if (I.getType()->isInteger()) {
3127     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3128     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3129       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3130       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3131     }
3132   }
3133
3134   // If it's a constant vector, flip any negative values positive.
3135   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3136     unsigned VWidth = RHSV->getNumOperands();
3137
3138     bool hasNegative = false;
3139     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3140       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3141         if (RHS->getValue().isNegative())
3142           hasNegative = true;
3143
3144     if (hasNegative) {
3145       std::vector<Constant *> Elts(VWidth);
3146       for (unsigned i = 0; i != VWidth; ++i) {
3147         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3148           if (RHS->getValue().isNegative())
3149             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3150           else
3151             Elts[i] = RHS;
3152         }
3153       }
3154
3155       Constant *NewRHSV = ConstantVector::get(Elts);
3156       if (NewRHSV != RHSV) {
3157         AddUsesToWorkList(I);
3158         I.setOperand(1, NewRHSV);
3159         return &I;
3160       }
3161     }
3162   }
3163
3164   return 0;
3165 }
3166
3167 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3168   return commonRemTransforms(I);
3169 }
3170
3171 // isOneBitSet - Return true if there is exactly one bit set in the specified
3172 // constant.
3173 static bool isOneBitSet(const ConstantInt *CI) {
3174   return CI->getValue().isPowerOf2();
3175 }
3176
3177 // isHighOnes - Return true if the constant is of the form 1+0+.
3178 // This is the same as lowones(~X).
3179 static bool isHighOnes(const ConstantInt *CI) {
3180   return (~CI->getValue() + 1).isPowerOf2();
3181 }
3182
3183 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3184 /// are carefully arranged to allow folding of expressions such as:
3185 ///
3186 ///      (A < B) | (A > B) --> (A != B)
3187 ///
3188 /// Note that this is only valid if the first and second predicates have the
3189 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3190 ///
3191 /// Three bits are used to represent the condition, as follows:
3192 ///   0  A > B
3193 ///   1  A == B
3194 ///   2  A < B
3195 ///
3196 /// <=>  Value  Definition
3197 /// 000     0   Always false
3198 /// 001     1   A >  B
3199 /// 010     2   A == B
3200 /// 011     3   A >= B
3201 /// 100     4   A <  B
3202 /// 101     5   A != B
3203 /// 110     6   A <= B
3204 /// 111     7   Always true
3205 ///  
3206 static unsigned getICmpCode(const ICmpInst *ICI) {
3207   switch (ICI->getPredicate()) {
3208     // False -> 0
3209   case ICmpInst::ICMP_UGT: return 1;  // 001
3210   case ICmpInst::ICMP_SGT: return 1;  // 001
3211   case ICmpInst::ICMP_EQ:  return 2;  // 010
3212   case ICmpInst::ICMP_UGE: return 3;  // 011
3213   case ICmpInst::ICMP_SGE: return 3;  // 011
3214   case ICmpInst::ICMP_ULT: return 4;  // 100
3215   case ICmpInst::ICMP_SLT: return 4;  // 100
3216   case ICmpInst::ICMP_NE:  return 5;  // 101
3217   case ICmpInst::ICMP_ULE: return 6;  // 110
3218   case ICmpInst::ICMP_SLE: return 6;  // 110
3219     // True -> 7
3220   default:
3221     assert(0 && "Invalid ICmp predicate!");
3222     return 0;
3223   }
3224 }
3225
3226 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3227 /// predicate into a three bit mask. It also returns whether it is an ordered
3228 /// predicate by reference.
3229 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3230   isOrdered = false;
3231   switch (CC) {
3232   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3233   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3234   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3235   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3236   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3237   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3238   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3239   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3240   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3241   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3242   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3243   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3244   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3245   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3246     // True -> 7
3247   default:
3248     // Not expecting FCMP_FALSE and FCMP_TRUE;
3249     assert(0 && "Unexpected FCmp predicate!");
3250     return 0;
3251   }
3252 }
3253
3254 /// getICmpValue - This is the complement of getICmpCode, which turns an
3255 /// opcode and two operands into either a constant true or false, or a brand 
3256 /// new ICmp instruction. The sign is passed in to determine which kind
3257 /// of predicate to use in the new icmp instruction.
3258 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3259   switch (code) {
3260   default: assert(0 && "Illegal ICmp code!");
3261   case  0: return ConstantInt::getFalse();
3262   case  1: 
3263     if (sign)
3264       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3265     else
3266       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3267   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3268   case  3: 
3269     if (sign)
3270       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3271     else
3272       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3273   case  4: 
3274     if (sign)
3275       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3276     else
3277       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3278   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3279   case  6: 
3280     if (sign)
3281       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3282     else
3283       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3284   case  7: return ConstantInt::getTrue();
3285   }
3286 }
3287
3288 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3289 /// opcode and two operands into either a FCmp instruction. isordered is passed
3290 /// in to determine which kind of predicate to use in the new fcmp instruction.
3291 static Value *getFCmpValue(bool isordered, unsigned code,
3292                            Value *LHS, Value *RHS) {
3293   switch (code) {
3294   default: assert(0 && "Illegal FCmp code!");
3295   case  0:
3296     if (isordered)
3297       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3298     else
3299       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3300   case  1: 
3301     if (isordered)
3302       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3303     else
3304       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3305   case  2: 
3306     if (isordered)
3307       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3308     else
3309       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3310   case  3: 
3311     if (isordered)
3312       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3313     else
3314       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3315   case  4: 
3316     if (isordered)
3317       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3318     else
3319       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3320   case  5: 
3321     if (isordered)
3322       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3323     else
3324       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3325   case  6: 
3326     if (isordered)
3327       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3328     else
3329       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3330   case  7: return ConstantInt::getTrue();
3331   }
3332 }
3333
3334 /// PredicatesFoldable - Return true if both predicates match sign or if at
3335 /// least one of them is an equality comparison (which is signless).
3336 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3337   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3338          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3339          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3340 }
3341
3342 namespace { 
3343 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3344 struct FoldICmpLogical {
3345   InstCombiner &IC;
3346   Value *LHS, *RHS;
3347   ICmpInst::Predicate pred;
3348   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3349     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3350       pred(ICI->getPredicate()) {}
3351   bool shouldApply(Value *V) const {
3352     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3353       if (PredicatesFoldable(pred, ICI->getPredicate()))
3354         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3355                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3356     return false;
3357   }
3358   Instruction *apply(Instruction &Log) const {
3359     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3360     if (ICI->getOperand(0) != LHS) {
3361       assert(ICI->getOperand(1) == LHS);
3362       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3363     }
3364
3365     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3366     unsigned LHSCode = getICmpCode(ICI);
3367     unsigned RHSCode = getICmpCode(RHSICI);
3368     unsigned Code;
3369     switch (Log.getOpcode()) {
3370     case Instruction::And: Code = LHSCode & RHSCode; break;
3371     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3372     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3373     default: assert(0 && "Illegal logical opcode!"); return 0;
3374     }
3375
3376     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3377                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3378       
3379     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3380     if (Instruction *I = dyn_cast<Instruction>(RV))
3381       return I;
3382     // Otherwise, it's a constant boolean value...
3383     return IC.ReplaceInstUsesWith(Log, RV);
3384   }
3385 };
3386 } // end anonymous namespace
3387
3388 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3389 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3390 // guaranteed to be a binary operator.
3391 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3392                                     ConstantInt *OpRHS,
3393                                     ConstantInt *AndRHS,
3394                                     BinaryOperator &TheAnd) {
3395   Value *X = Op->getOperand(0);
3396   Constant *Together = 0;
3397   if (!Op->isShift())
3398     Together = And(AndRHS, OpRHS);
3399
3400   switch (Op->getOpcode()) {
3401   case Instruction::Xor:
3402     if (Op->hasOneUse()) {
3403       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3404       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3405       InsertNewInstBefore(And, TheAnd);
3406       And->takeName(Op);
3407       return BinaryOperator::CreateXor(And, Together);
3408     }
3409     break;
3410   case Instruction::Or:
3411     if (Together == AndRHS) // (X | C) & C --> C
3412       return ReplaceInstUsesWith(TheAnd, AndRHS);
3413
3414     if (Op->hasOneUse() && Together != OpRHS) {
3415       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3416       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3417       InsertNewInstBefore(Or, TheAnd);
3418       Or->takeName(Op);
3419       return BinaryOperator::CreateAnd(Or, AndRHS);
3420     }
3421     break;
3422   case Instruction::Add:
3423     if (Op->hasOneUse()) {
3424       // Adding a one to a single bit bit-field should be turned into an XOR
3425       // of the bit.  First thing to check is to see if this AND is with a
3426       // single bit constant.
3427       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3428
3429       // If there is only one bit set...
3430       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3431         // Ok, at this point, we know that we are masking the result of the
3432         // ADD down to exactly one bit.  If the constant we are adding has
3433         // no bits set below this bit, then we can eliminate the ADD.
3434         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3435
3436         // Check to see if any bits below the one bit set in AndRHSV are set.
3437         if ((AddRHS & (AndRHSV-1)) == 0) {
3438           // If not, the only thing that can effect the output of the AND is
3439           // the bit specified by AndRHSV.  If that bit is set, the effect of
3440           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3441           // no effect.
3442           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3443             TheAnd.setOperand(0, X);
3444             return &TheAnd;
3445           } else {
3446             // Pull the XOR out of the AND.
3447             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3448             InsertNewInstBefore(NewAnd, TheAnd);
3449             NewAnd->takeName(Op);
3450             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3451           }
3452         }
3453       }
3454     }
3455     break;
3456
3457   case Instruction::Shl: {
3458     // We know that the AND will not produce any of the bits shifted in, so if
3459     // the anded constant includes them, clear them now!
3460     //
3461     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3462     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3463     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3464     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3465
3466     if (CI->getValue() == ShlMask) { 
3467     // Masking out bits that the shift already masks
3468       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3469     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3470       TheAnd.setOperand(1, CI);
3471       return &TheAnd;
3472     }
3473     break;
3474   }
3475   case Instruction::LShr:
3476   {
3477     // We know that the AND will not produce any of the bits shifted in, so if
3478     // the anded constant includes them, clear them now!  This only applies to
3479     // unsigned shifts, because a signed shr may bring in set bits!
3480     //
3481     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3482     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3483     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3484     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3485
3486     if (CI->getValue() == ShrMask) {   
3487     // Masking out bits that the shift already masks.
3488       return ReplaceInstUsesWith(TheAnd, Op);
3489     } else if (CI != AndRHS) {
3490       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3491       return &TheAnd;
3492     }
3493     break;
3494   }
3495   case Instruction::AShr:
3496     // Signed shr.
3497     // See if this is shifting in some sign extension, then masking it out
3498     // with an and.
3499     if (Op->hasOneUse()) {
3500       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3501       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3502       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3503       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3504       if (C == AndRHS) {          // Masking out bits shifted in.
3505         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3506         // Make the argument unsigned.
3507         Value *ShVal = Op->getOperand(0);
3508         ShVal = InsertNewInstBefore(
3509             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3510                                    Op->getName()), TheAnd);
3511         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3512       }
3513     }
3514     break;
3515   }
3516   return 0;
3517 }
3518
3519
3520 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3521 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3522 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3523 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3524 /// insert new instructions.
3525 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3526                                            bool isSigned, bool Inside, 
3527                                            Instruction &IB) {
3528   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3529             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3530          "Lo is not <= Hi in range emission code!");
3531     
3532   if (Inside) {
3533     if (Lo == Hi)  // Trivially false.
3534       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3535
3536     // V >= Min && V < Hi --> V < Hi
3537     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3538       ICmpInst::Predicate pred = (isSigned ? 
3539         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3540       return new ICmpInst(pred, V, Hi);
3541     }
3542
3543     // Emit V-Lo <u Hi-Lo
3544     Constant *NegLo = ConstantExpr::getNeg(Lo);
3545     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3546     InsertNewInstBefore(Add, IB);
3547     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3548     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3549   }
3550
3551   if (Lo == Hi)  // Trivially true.
3552     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3553
3554   // V < Min || V >= Hi -> V > Hi-1
3555   Hi = SubOne(cast<ConstantInt>(Hi));
3556   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3557     ICmpInst::Predicate pred = (isSigned ? 
3558         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3559     return new ICmpInst(pred, V, Hi);
3560   }
3561
3562   // Emit V-Lo >u Hi-1-Lo
3563   // Note that Hi has already had one subtracted from it, above.
3564   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3565   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3566   InsertNewInstBefore(Add, IB);
3567   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3568   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3569 }
3570
3571 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3572 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3573 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3574 // not, since all 1s are not contiguous.
3575 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3576   const APInt& V = Val->getValue();
3577   uint32_t BitWidth = Val->getType()->getBitWidth();
3578   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3579
3580   // look for the first zero bit after the run of ones
3581   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3582   // look for the first non-zero bit
3583   ME = V.getActiveBits(); 
3584   return true;
3585 }
3586
3587 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3588 /// where isSub determines whether the operator is a sub.  If we can fold one of
3589 /// the following xforms:
3590 /// 
3591 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3592 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3593 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3594 ///
3595 /// return (A +/- B).
3596 ///
3597 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3598                                         ConstantInt *Mask, bool isSub,
3599                                         Instruction &I) {
3600   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3601   if (!LHSI || LHSI->getNumOperands() != 2 ||
3602       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3603
3604   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3605
3606   switch (LHSI->getOpcode()) {
3607   default: return 0;
3608   case Instruction::And:
3609     if (And(N, Mask) == Mask) {
3610       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3611       if ((Mask->getValue().countLeadingZeros() + 
3612            Mask->getValue().countPopulation()) == 
3613           Mask->getValue().getBitWidth())
3614         break;
3615
3616       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3617       // part, we don't need any explicit masks to take them out of A.  If that
3618       // is all N is, ignore it.
3619       uint32_t MB = 0, ME = 0;
3620       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3621         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3622         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3623         if (MaskedValueIsZero(RHS, Mask))
3624           break;
3625       }
3626     }
3627     return 0;
3628   case Instruction::Or:
3629   case Instruction::Xor:
3630     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3631     if ((Mask->getValue().countLeadingZeros() + 
3632          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3633         && And(N, Mask)->isZero())
3634       break;
3635     return 0;
3636   }
3637   
3638   Instruction *New;
3639   if (isSub)
3640     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3641   else
3642     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3643   return InsertNewInstBefore(New, I);
3644 }
3645
3646 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3647 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3648                                           ICmpInst *LHS, ICmpInst *RHS) {
3649   Value *Val, *Val2;
3650   ConstantInt *LHSCst, *RHSCst;
3651   ICmpInst::Predicate LHSCC, RHSCC;
3652   
3653   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3654   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3655       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3656     return 0;
3657   
3658   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3659   // where C is a power of 2
3660   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3661       LHSCst->getValue().isPowerOf2()) {
3662     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3663     InsertNewInstBefore(NewOr, I);
3664     return new ICmpInst(LHSCC, NewOr, LHSCst);
3665   }
3666   
3667   // From here on, we only handle:
3668   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3669   if (Val != Val2) return 0;
3670   
3671   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3672   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3673       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3674       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3675       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3676     return 0;
3677   
3678   // We can't fold (ugt x, C) & (sgt x, C2).
3679   if (!PredicatesFoldable(LHSCC, RHSCC))
3680     return 0;
3681     
3682   // Ensure that the larger constant is on the RHS.
3683   bool ShouldSwap;
3684   if (ICmpInst::isSignedPredicate(LHSCC) ||
3685       (ICmpInst::isEquality(LHSCC) && 
3686        ICmpInst::isSignedPredicate(RHSCC)))
3687     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3688   else
3689     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3690     
3691   if (ShouldSwap) {
3692     std::swap(LHS, RHS);
3693     std::swap(LHSCst, RHSCst);
3694     std::swap(LHSCC, RHSCC);
3695   }
3696
3697   // At this point, we know we have have two icmp instructions
3698   // comparing a value against two constants and and'ing the result
3699   // together.  Because of the above check, we know that we only have
3700   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3701   // (from the FoldICmpLogical check above), that the two constants 
3702   // are not equal and that the larger constant is on the RHS
3703   assert(LHSCst != RHSCst && "Compares not folded above?");
3704
3705   switch (LHSCC) {
3706   default: assert(0 && "Unknown integer condition code!");
3707   case ICmpInst::ICMP_EQ:
3708     switch (RHSCC) {
3709     default: assert(0 && "Unknown integer condition code!");
3710     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3711     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3712     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3713       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3714     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3715     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3716     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3717       return ReplaceInstUsesWith(I, LHS);
3718     }
3719   case ICmpInst::ICMP_NE:
3720     switch (RHSCC) {
3721     default: assert(0 && "Unknown integer condition code!");
3722     case ICmpInst::ICMP_ULT:
3723       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3724         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3725       break;                        // (X != 13 & X u< 15) -> no change
3726     case ICmpInst::ICMP_SLT:
3727       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3728         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3729       break;                        // (X != 13 & X s< 15) -> no change
3730     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3731     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3732     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3733       return ReplaceInstUsesWith(I, RHS);
3734     case ICmpInst::ICMP_NE:
3735       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3736         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3737         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3738                                                      Val->getName()+".off");
3739         InsertNewInstBefore(Add, I);
3740         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3741                             ConstantInt::get(Add->getType(), 1));
3742       }
3743       break;                        // (X != 13 & X != 15) -> no change
3744     }
3745     break;
3746   case ICmpInst::ICMP_ULT:
3747     switch (RHSCC) {
3748     default: assert(0 && "Unknown integer condition code!");
3749     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3750     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3751       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3752     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3753       break;
3754     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3755     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3756       return ReplaceInstUsesWith(I, LHS);
3757     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3758       break;
3759     }
3760     break;
3761   case ICmpInst::ICMP_SLT:
3762     switch (RHSCC) {
3763     default: assert(0 && "Unknown integer condition code!");
3764     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3765     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3766       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3767     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3768       break;
3769     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3770     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3771       return ReplaceInstUsesWith(I, LHS);
3772     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3773       break;
3774     }
3775     break;
3776   case ICmpInst::ICMP_UGT:
3777     switch (RHSCC) {
3778     default: assert(0 && "Unknown integer condition code!");
3779     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3780     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3781       return ReplaceInstUsesWith(I, RHS);
3782     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3783       break;
3784     case ICmpInst::ICMP_NE:
3785       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3786         return new ICmpInst(LHSCC, Val, RHSCst);
3787       break;                        // (X u> 13 & X != 15) -> no change
3788     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3789       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3790     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3791       break;
3792     }
3793     break;
3794   case ICmpInst::ICMP_SGT:
3795     switch (RHSCC) {
3796     default: assert(0 && "Unknown integer condition code!");
3797     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3798     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3799       return ReplaceInstUsesWith(I, RHS);
3800     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3801       break;
3802     case ICmpInst::ICMP_NE:
3803       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3804         return new ICmpInst(LHSCC, Val, RHSCst);
3805       break;                        // (X s> 13 & X != 15) -> no change
3806     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3807       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3808     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3809       break;
3810     }
3811     break;
3812   }
3813  
3814   return 0;
3815 }
3816
3817
3818 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3819   bool Changed = SimplifyCommutative(I);
3820   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3821
3822   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3823     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3824
3825   // and X, X = X
3826   if (Op0 == Op1)
3827     return ReplaceInstUsesWith(I, Op1);
3828
3829   // See if we can simplify any instructions used by the instruction whose sole 
3830   // purpose is to compute bits we don't care about.
3831   if (!isa<VectorType>(I.getType())) {
3832     if (SimplifyDemandedInstructionBits(I))
3833       return &I;
3834   } else {
3835     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3836       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3837         return ReplaceInstUsesWith(I, I.getOperand(0));
3838     } else if (isa<ConstantAggregateZero>(Op1)) {
3839       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3840     }
3841   }
3842   
3843   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3844     const APInt& AndRHSMask = AndRHS->getValue();
3845     APInt NotAndRHS(~AndRHSMask);
3846
3847     // Optimize a variety of ((val OP C1) & C2) combinations...
3848     if (isa<BinaryOperator>(Op0)) {
3849       Instruction *Op0I = cast<Instruction>(Op0);
3850       Value *Op0LHS = Op0I->getOperand(0);
3851       Value *Op0RHS = Op0I->getOperand(1);
3852       switch (Op0I->getOpcode()) {
3853       case Instruction::Xor:
3854       case Instruction::Or:
3855         // If the mask is only needed on one incoming arm, push it up.
3856         if (Op0I->hasOneUse()) {
3857           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3858             // Not masking anything out for the LHS, move to RHS.
3859             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3860                                                    Op0RHS->getName()+".masked");
3861             InsertNewInstBefore(NewRHS, I);
3862             return BinaryOperator::Create(
3863                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3864           }
3865           if (!isa<Constant>(Op0RHS) &&
3866               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3867             // Not masking anything out for the RHS, move to LHS.
3868             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3869                                                    Op0LHS->getName()+".masked");
3870             InsertNewInstBefore(NewLHS, I);
3871             return BinaryOperator::Create(
3872                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3873           }
3874         }
3875
3876         break;
3877       case Instruction::Add:
3878         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3879         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3880         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3881         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3882           return BinaryOperator::CreateAnd(V, AndRHS);
3883         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3884           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3885         break;
3886
3887       case Instruction::Sub:
3888         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3889         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3890         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3891         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3892           return BinaryOperator::CreateAnd(V, AndRHS);
3893
3894         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3895         // has 1's for all bits that the subtraction with A might affect.
3896         if (Op0I->hasOneUse()) {
3897           uint32_t BitWidth = AndRHSMask.getBitWidth();
3898           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3899           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3900
3901           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3902           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3903               MaskedValueIsZero(Op0LHS, Mask)) {
3904             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3905             InsertNewInstBefore(NewNeg, I);
3906             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3907           }
3908         }
3909         break;
3910
3911       case Instruction::Shl:
3912       case Instruction::LShr:
3913         // (1 << x) & 1 --> zext(x == 0)
3914         // (1 >> x) & 1 --> zext(x == 0)
3915         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3916           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3917                                            Constant::getNullValue(I.getType()));
3918           InsertNewInstBefore(NewICmp, I);
3919           return new ZExtInst(NewICmp, I.getType());
3920         }
3921         break;
3922       }
3923
3924       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3925         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3926           return Res;
3927     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3928       // If this is an integer truncation or change from signed-to-unsigned, and
3929       // if the source is an and/or with immediate, transform it.  This
3930       // frequently occurs for bitfield accesses.
3931       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3932         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3933             CastOp->getNumOperands() == 2)
3934           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3935             if (CastOp->getOpcode() == Instruction::And) {
3936               // Change: and (cast (and X, C1) to T), C2
3937               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3938               // This will fold the two constants together, which may allow 
3939               // other simplifications.
3940               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3941                 CastOp->getOperand(0), I.getType(), 
3942                 CastOp->getName()+".shrunk");
3943               NewCast = InsertNewInstBefore(NewCast, I);
3944               // trunc_or_bitcast(C1)&C2
3945               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3946               C3 = ConstantExpr::getAnd(C3, AndRHS);
3947               return BinaryOperator::CreateAnd(NewCast, C3);
3948             } else if (CastOp->getOpcode() == Instruction::Or) {
3949               // Change: and (cast (or X, C1) to T), C2
3950               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3951               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3952               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3953                 return ReplaceInstUsesWith(I, AndRHS);
3954             }
3955           }
3956       }
3957     }
3958
3959     // Try to fold constant and into select arguments.
3960     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3961       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3962         return R;
3963     if (isa<PHINode>(Op0))
3964       if (Instruction *NV = FoldOpIntoPhi(I))
3965         return NV;
3966   }
3967
3968   Value *Op0NotVal = dyn_castNotVal(Op0);
3969   Value *Op1NotVal = dyn_castNotVal(Op1);
3970
3971   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3972     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3973
3974   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3975   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3976     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3977                                                I.getName()+".demorgan");
3978     InsertNewInstBefore(Or, I);
3979     return BinaryOperator::CreateNot(Or);
3980   }
3981   
3982   {
3983     Value *A = 0, *B = 0, *C = 0, *D = 0;
3984     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3985       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3986         return ReplaceInstUsesWith(I, Op1);
3987     
3988       // (A|B) & ~(A&B) -> A^B
3989       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3990         if ((A == C && B == D) || (A == D && B == C))
3991           return BinaryOperator::CreateXor(A, B);
3992       }
3993     }
3994     
3995     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3996       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3997         return ReplaceInstUsesWith(I, Op0);
3998
3999       // ~(A&B) & (A|B) -> A^B
4000       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4001         if ((A == C && B == D) || (A == D && B == C))
4002           return BinaryOperator::CreateXor(A, B);
4003       }
4004     }
4005     
4006     if (Op0->hasOneUse() &&
4007         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4008       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4009         I.swapOperands();     // Simplify below
4010         std::swap(Op0, Op1);
4011       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4012         cast<BinaryOperator>(Op0)->swapOperands();
4013         I.swapOperands();     // Simplify below
4014         std::swap(Op0, Op1);
4015       }
4016     }
4017
4018     if (Op1->hasOneUse() &&
4019         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4020       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4021         cast<BinaryOperator>(Op1)->swapOperands();
4022         std::swap(A, B);
4023       }
4024       if (A == Op0) {                                // A&(A^B) -> A & ~B
4025         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4026         InsertNewInstBefore(NotB, I);
4027         return BinaryOperator::CreateAnd(A, NotB);
4028       }
4029     }
4030
4031     // (A&((~A)|B)) -> A&B
4032     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4033         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4034       return BinaryOperator::CreateAnd(A, Op1);
4035     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4036         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4037       return BinaryOperator::CreateAnd(A, Op0);
4038   }
4039   
4040   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4041     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4042     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4043       return R;
4044
4045     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4046       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4047         return Res;
4048   }
4049
4050   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4051   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4052     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4053       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4054         const Type *SrcTy = Op0C->getOperand(0)->getType();
4055         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4056             // Only do this if the casts both really cause code to be generated.
4057             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4058                               I.getType(), TD) &&
4059             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4060                               I.getType(), TD)) {
4061           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4062                                                          Op1C->getOperand(0),
4063                                                          I.getName());
4064           InsertNewInstBefore(NewOp, I);
4065           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4066         }
4067       }
4068     
4069   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4070   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4071     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4072       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4073           SI0->getOperand(1) == SI1->getOperand(1) &&
4074           (SI0->hasOneUse() || SI1->hasOneUse())) {
4075         Instruction *NewOp =
4076           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4077                                                         SI1->getOperand(0),
4078                                                         SI0->getName()), I);
4079         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4080                                       SI1->getOperand(1));
4081       }
4082   }
4083
4084   // If and'ing two fcmp, try combine them into one.
4085   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4086     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4087       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4088           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4089         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4090         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4091           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4092             // If either of the constants are nans, then the whole thing returns
4093             // false.
4094             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4095               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4096             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4097                                 RHS->getOperand(0));
4098           }
4099       } else {
4100         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4101         FCmpInst::Predicate Op0CC, Op1CC;
4102         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4103             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4104           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4105             // Swap RHS operands to match LHS.
4106             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4107             std::swap(Op1LHS, Op1RHS);
4108           }
4109           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4110             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4111             if (Op0CC == Op1CC)
4112               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4113             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4114                      Op1CC == FCmpInst::FCMP_FALSE)
4115               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4116             else if (Op0CC == FCmpInst::FCMP_TRUE)
4117               return ReplaceInstUsesWith(I, Op1);
4118             else if (Op1CC == FCmpInst::FCMP_TRUE)
4119               return ReplaceInstUsesWith(I, Op0);
4120             bool Op0Ordered;
4121             bool Op1Ordered;
4122             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4123             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4124             if (Op1Pred == 0) {
4125               std::swap(Op0, Op1);
4126               std::swap(Op0Pred, Op1Pred);
4127               std::swap(Op0Ordered, Op1Ordered);
4128             }
4129             if (Op0Pred == 0) {
4130               // uno && ueq -> uno && (uno || eq) -> ueq
4131               // ord && olt -> ord && (ord && lt) -> olt
4132               if (Op0Ordered == Op1Ordered)
4133                 return ReplaceInstUsesWith(I, Op1);
4134               // uno && oeq -> uno && (ord && eq) -> false
4135               // uno && ord -> false
4136               if (!Op0Ordered)
4137                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4138               // ord && ueq -> ord && (uno || eq) -> oeq
4139               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4140                                                     Op0LHS, Op0RHS));
4141             }
4142           }
4143         }
4144       }
4145     }
4146   }
4147
4148   return Changed ? &I : 0;
4149 }
4150
4151 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4152 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4153 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4154 /// the expression came from the corresponding "byte swapped" byte in some other
4155 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4156 /// we know that the expression deposits the low byte of %X into the high byte
4157 /// of the bswap result and that all other bytes are zero.  This expression is
4158 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4159 /// match.
4160 ///
4161 /// This function returns true if the match was unsuccessful and false if so.
4162 /// On entry to the function the "OverallLeftShift" is a signed integer value
4163 /// indicating the number of bytes that the subexpression is later shifted.  For
4164 /// example, if the expression is later right shifted by 16 bits, the
4165 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4166 /// byte of ByteValues is actually being set.
4167 ///
4168 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4169 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4170 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4171 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4172 /// always in the local (OverallLeftShift) coordinate space.
4173 ///
4174 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4175                               SmallVector<Value*, 8> &ByteValues) {
4176   if (Instruction *I = dyn_cast<Instruction>(V)) {
4177     // If this is an or instruction, it may be an inner node of the bswap.
4178     if (I->getOpcode() == Instruction::Or) {
4179       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4180                                ByteValues) ||
4181              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4182                                ByteValues);
4183     }
4184   
4185     // If this is a logical shift by a constant multiple of 8, recurse with
4186     // OverallLeftShift and ByteMask adjusted.
4187     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4188       unsigned ShAmt = 
4189         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4190       // Ensure the shift amount is defined and of a byte value.
4191       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4192         return true;
4193
4194       unsigned ByteShift = ShAmt >> 3;
4195       if (I->getOpcode() == Instruction::Shl) {
4196         // X << 2 -> collect(X, +2)
4197         OverallLeftShift += ByteShift;
4198         ByteMask >>= ByteShift;
4199       } else {
4200         // X >>u 2 -> collect(X, -2)
4201         OverallLeftShift -= ByteShift;
4202         ByteMask <<= ByteShift;
4203         ByteMask &= (~0U >> (32-ByteValues.size()));
4204       }
4205
4206       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4207       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4208
4209       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4210                                ByteValues);
4211     }
4212
4213     // If this is a logical 'and' with a mask that clears bytes, clear the
4214     // corresponding bytes in ByteMask.
4215     if (I->getOpcode() == Instruction::And &&
4216         isa<ConstantInt>(I->getOperand(1))) {
4217       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4218       unsigned NumBytes = ByteValues.size();
4219       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4220       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4221       
4222       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4223         // If this byte is masked out by a later operation, we don't care what
4224         // the and mask is.
4225         if ((ByteMask & (1 << i)) == 0)
4226           continue;
4227         
4228         // If the AndMask is all zeros for this byte, clear the bit.
4229         APInt MaskB = AndMask & Byte;
4230         if (MaskB == 0) {
4231           ByteMask &= ~(1U << i);
4232           continue;
4233         }
4234         
4235         // If the AndMask is not all ones for this byte, it's not a bytezap.
4236         if (MaskB != Byte)
4237           return true;
4238
4239         // Otherwise, this byte is kept.
4240       }
4241
4242       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4243                                ByteValues);
4244     }
4245   }
4246   
4247   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4248   // the input value to the bswap.  Some observations: 1) if more than one byte
4249   // is demanded from this input, then it could not be successfully assembled
4250   // into a byteswap.  At least one of the two bytes would not be aligned with
4251   // their ultimate destination.
4252   if (!isPowerOf2_32(ByteMask)) return true;
4253   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4254   
4255   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4256   // is demanded, it needs to go into byte 0 of the result.  This means that the
4257   // byte needs to be shifted until it lands in the right byte bucket.  The
4258   // shift amount depends on the position: if the byte is coming from the high
4259   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4260   // low part, it must be shifted left.
4261   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4262   if (InputByteNo < ByteValues.size()/2) {
4263     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4264       return true;
4265   } else {
4266     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4267       return true;
4268   }
4269   
4270   // If the destination byte value is already defined, the values are or'd
4271   // together, which isn't a bswap (unless it's an or of the same bits).
4272   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4273     return true;
4274   ByteValues[DestByteNo] = V;
4275   return false;
4276 }
4277
4278 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4279 /// If so, insert the new bswap intrinsic and return it.
4280 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4281   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4282   if (!ITy || ITy->getBitWidth() % 16 || 
4283       // ByteMask only allows up to 32-byte values.
4284       ITy->getBitWidth() > 32*8) 
4285     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4286   
4287   /// ByteValues - For each byte of the result, we keep track of which value
4288   /// defines each byte.
4289   SmallVector<Value*, 8> ByteValues;
4290   ByteValues.resize(ITy->getBitWidth()/8);
4291     
4292   // Try to find all the pieces corresponding to the bswap.
4293   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4294   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4295     return 0;
4296   
4297   // Check to see if all of the bytes come from the same value.
4298   Value *V = ByteValues[0];
4299   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4300   
4301   // Check to make sure that all of the bytes come from the same value.
4302   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4303     if (ByteValues[i] != V)
4304       return 0;
4305   const Type *Tys[] = { ITy };
4306   Module *M = I.getParent()->getParent()->getParent();
4307   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4308   return CallInst::Create(F, V);
4309 }
4310
4311 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4312 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4313 /// we can simplify this expression to "cond ? C : D or B".
4314 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4315                                          Value *C, Value *D) {
4316   // If A is not a select of -1/0, this cannot match.
4317   Value *Cond = 0;
4318   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4319     return 0;
4320
4321   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4322   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4323     return SelectInst::Create(Cond, C, B);
4324   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4325     return SelectInst::Create(Cond, C, B);
4326   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4327   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4328     return SelectInst::Create(Cond, C, D);
4329   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4330     return SelectInst::Create(Cond, C, D);
4331   return 0;
4332 }
4333
4334 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4335 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4336                                          ICmpInst *LHS, ICmpInst *RHS) {
4337   Value *Val, *Val2;
4338   ConstantInt *LHSCst, *RHSCst;
4339   ICmpInst::Predicate LHSCC, RHSCC;
4340   
4341   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4342   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4343       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4344     return 0;
4345   
4346   // From here on, we only handle:
4347   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4348   if (Val != Val2) return 0;
4349   
4350   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4351   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4352       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4353       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4354       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4355     return 0;
4356   
4357   // We can't fold (ugt x, C) | (sgt x, C2).
4358   if (!PredicatesFoldable(LHSCC, RHSCC))
4359     return 0;
4360   
4361   // Ensure that the larger constant is on the RHS.
4362   bool ShouldSwap;
4363   if (ICmpInst::isSignedPredicate(LHSCC) ||
4364       (ICmpInst::isEquality(LHSCC) && 
4365        ICmpInst::isSignedPredicate(RHSCC)))
4366     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4367   else
4368     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4369   
4370   if (ShouldSwap) {
4371     std::swap(LHS, RHS);
4372     std::swap(LHSCst, RHSCst);
4373     std::swap(LHSCC, RHSCC);
4374   }
4375   
4376   // At this point, we know we have have two icmp instructions
4377   // comparing a value against two constants and or'ing the result
4378   // together.  Because of the above check, we know that we only have
4379   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4380   // FoldICmpLogical check above), that the two constants are not
4381   // equal.
4382   assert(LHSCst != RHSCst && "Compares not folded above?");
4383
4384   switch (LHSCC) {
4385   default: assert(0 && "Unknown integer condition code!");
4386   case ICmpInst::ICMP_EQ:
4387     switch (RHSCC) {
4388     default: assert(0 && "Unknown integer condition code!");
4389     case ICmpInst::ICMP_EQ:
4390       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4391         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4392         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4393                                                      Val->getName()+".off");
4394         InsertNewInstBefore(Add, I);
4395         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4396         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4397       }
4398       break;                         // (X == 13 | X == 15) -> no change
4399     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4400     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4401       break;
4402     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4403     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4404     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4405       return ReplaceInstUsesWith(I, RHS);
4406     }
4407     break;
4408   case ICmpInst::ICMP_NE:
4409     switch (RHSCC) {
4410     default: assert(0 && "Unknown integer condition code!");
4411     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4412     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4413     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4414       return ReplaceInstUsesWith(I, LHS);
4415     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4416     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4417     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4418       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4419     }
4420     break;
4421   case ICmpInst::ICMP_ULT:
4422     switch (RHSCC) {
4423     default: assert(0 && "Unknown integer condition code!");
4424     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4425       break;
4426     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4427       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4428       // this can cause overflow.
4429       if (RHSCst->isMaxValue(false))
4430         return ReplaceInstUsesWith(I, LHS);
4431       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4432     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4433       break;
4434     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4435     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4436       return ReplaceInstUsesWith(I, RHS);
4437     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4438       break;
4439     }
4440     break;
4441   case ICmpInst::ICMP_SLT:
4442     switch (RHSCC) {
4443     default: assert(0 && "Unknown integer condition code!");
4444     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4445       break;
4446     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4447       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4448       // this can cause overflow.
4449       if (RHSCst->isMaxValue(true))
4450         return ReplaceInstUsesWith(I, LHS);
4451       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4452     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4453       break;
4454     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4455     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4456       return ReplaceInstUsesWith(I, RHS);
4457     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4458       break;
4459     }
4460     break;
4461   case ICmpInst::ICMP_UGT:
4462     switch (RHSCC) {
4463     default: assert(0 && "Unknown integer condition code!");
4464     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4465     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4466       return ReplaceInstUsesWith(I, LHS);
4467     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4468       break;
4469     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4470     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4471       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4472     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4473       break;
4474     }
4475     break;
4476   case ICmpInst::ICMP_SGT:
4477     switch (RHSCC) {
4478     default: assert(0 && "Unknown integer condition code!");
4479     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4480     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4481       return ReplaceInstUsesWith(I, LHS);
4482     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4483       break;
4484     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4485     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4486       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4487     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4488       break;
4489     }
4490     break;
4491   }
4492   return 0;
4493 }
4494
4495 /// FoldOrWithConstants - This helper function folds:
4496 ///
4497 ///     ((A | B) & C1) | (B & C2)
4498 ///
4499 /// into:
4500 /// 
4501 ///     (A & C1) | B
4502 ///
4503 /// when the XOR of the two constants is "all ones" (-1).
4504 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4505                                                Value *A, Value *B, Value *C) {
4506   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4507   if (!CI1) return 0;
4508
4509   Value *V1 = 0;
4510   ConstantInt *CI2 = 0;
4511   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4512
4513   APInt Xor = CI1->getValue() ^ CI2->getValue();
4514   if (!Xor.isAllOnesValue()) return 0;
4515
4516   if (V1 == A || V1 == B) {
4517     Instruction *NewOp =
4518       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4519     return BinaryOperator::CreateOr(NewOp, V1);
4520   }
4521
4522   return 0;
4523 }
4524
4525 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4526   bool Changed = SimplifyCommutative(I);
4527   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4528
4529   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4530     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4531
4532   // or X, X = X
4533   if (Op0 == Op1)
4534     return ReplaceInstUsesWith(I, Op0);
4535
4536   // See if we can simplify any instructions used by the instruction whose sole 
4537   // purpose is to compute bits we don't care about.
4538   if (!isa<VectorType>(I.getType())) {
4539     if (SimplifyDemandedInstructionBits(I))
4540       return &I;
4541   } else if (isa<ConstantAggregateZero>(Op1)) {
4542     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4543   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4544     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4545       return ReplaceInstUsesWith(I, I.getOperand(1));
4546   }
4547     
4548
4549   
4550   // or X, -1 == -1
4551   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4552     ConstantInt *C1 = 0; Value *X = 0;
4553     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4554     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4555       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4556       InsertNewInstBefore(Or, I);
4557       Or->takeName(Op0);
4558       return BinaryOperator::CreateAnd(Or, 
4559                ConstantInt::get(RHS->getValue() | C1->getValue()));
4560     }
4561
4562     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4563     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4564       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4565       InsertNewInstBefore(Or, I);
4566       Or->takeName(Op0);
4567       return BinaryOperator::CreateXor(Or,
4568                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4569     }
4570
4571     // Try to fold constant and into select arguments.
4572     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4573       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4574         return R;
4575     if (isa<PHINode>(Op0))
4576       if (Instruction *NV = FoldOpIntoPhi(I))
4577         return NV;
4578   }
4579
4580   Value *A = 0, *B = 0;
4581   ConstantInt *C1 = 0, *C2 = 0;
4582
4583   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4584     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4585       return ReplaceInstUsesWith(I, Op1);
4586   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4587     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4588       return ReplaceInstUsesWith(I, Op0);
4589
4590   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4591   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4592   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4593       match(Op1, m_Or(m_Value(), m_Value())) ||
4594       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4595        match(Op1, m_Shift(m_Value(), m_Value())))) {
4596     if (Instruction *BSwap = MatchBSwap(I))
4597       return BSwap;
4598   }
4599   
4600   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4601   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4602       MaskedValueIsZero(Op1, C1->getValue())) {
4603     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4604     InsertNewInstBefore(NOr, I);
4605     NOr->takeName(Op0);
4606     return BinaryOperator::CreateXor(NOr, C1);
4607   }
4608
4609   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4610   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4611       MaskedValueIsZero(Op0, C1->getValue())) {
4612     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4613     InsertNewInstBefore(NOr, I);
4614     NOr->takeName(Op0);
4615     return BinaryOperator::CreateXor(NOr, C1);
4616   }
4617
4618   // (A & C)|(B & D)
4619   Value *C = 0, *D = 0;
4620   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4621       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4622     Value *V1 = 0, *V2 = 0, *V3 = 0;
4623     C1 = dyn_cast<ConstantInt>(C);
4624     C2 = dyn_cast<ConstantInt>(D);
4625     if (C1 && C2) {  // (A & C1)|(B & C2)
4626       // If we have: ((V + N) & C1) | (V & C2)
4627       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4628       // replace with V+N.
4629       if (C1->getValue() == ~C2->getValue()) {
4630         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4631             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4632           // Add commutes, try both ways.
4633           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4634             return ReplaceInstUsesWith(I, A);
4635           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4636             return ReplaceInstUsesWith(I, A);
4637         }
4638         // Or commutes, try both ways.
4639         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4640             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4641           // Add commutes, try both ways.
4642           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4643             return ReplaceInstUsesWith(I, B);
4644           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4645             return ReplaceInstUsesWith(I, B);
4646         }
4647       }
4648       V1 = 0; V2 = 0; V3 = 0;
4649     }
4650     
4651     // Check to see if we have any common things being and'ed.  If so, find the
4652     // terms for V1 & (V2|V3).
4653     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4654       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4655         V1 = A, V2 = C, V3 = D;
4656       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4657         V1 = A, V2 = B, V3 = C;
4658       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4659         V1 = C, V2 = A, V3 = D;
4660       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4661         V1 = C, V2 = A, V3 = B;
4662       
4663       if (V1) {
4664         Value *Or =
4665           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4666         return BinaryOperator::CreateAnd(V1, Or);
4667       }
4668     }
4669
4670     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4671     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4672       return Match;
4673     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4674       return Match;
4675     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4676       return Match;
4677     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4678       return Match;
4679
4680     // ((A&~B)|(~A&B)) -> A^B
4681     if ((match(C, m_Not(m_Specific(D))) &&
4682          match(B, m_Not(m_Specific(A)))))
4683       return BinaryOperator::CreateXor(A, D);
4684     // ((~B&A)|(~A&B)) -> A^B
4685     if ((match(A, m_Not(m_Specific(D))) &&
4686          match(B, m_Not(m_Specific(C)))))
4687       return BinaryOperator::CreateXor(C, D);
4688     // ((A&~B)|(B&~A)) -> A^B
4689     if ((match(C, m_Not(m_Specific(B))) &&
4690          match(D, m_Not(m_Specific(A)))))
4691       return BinaryOperator::CreateXor(A, B);
4692     // ((~B&A)|(B&~A)) -> A^B
4693     if ((match(A, m_Not(m_Specific(B))) &&
4694          match(D, m_Not(m_Specific(C)))))
4695       return BinaryOperator::CreateXor(C, B);
4696   }
4697   
4698   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4699   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4700     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4701       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4702           SI0->getOperand(1) == SI1->getOperand(1) &&
4703           (SI0->hasOneUse() || SI1->hasOneUse())) {
4704         Instruction *NewOp =
4705         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4706                                                      SI1->getOperand(0),
4707                                                      SI0->getName()), I);
4708         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4709                                       SI1->getOperand(1));
4710       }
4711   }
4712
4713   // ((A|B)&1)|(B&-2) -> (A&1) | B
4714   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4715       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4716     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4717     if (Ret) return Ret;
4718   }
4719   // (B&-2)|((A|B)&1) -> (A&1) | B
4720   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4721       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4722     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4723     if (Ret) return Ret;
4724   }
4725
4726   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4727     if (A == Op1)   // ~A | A == -1
4728       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4729   } else {
4730     A = 0;
4731   }
4732   // Note, A is still live here!
4733   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4734     if (Op0 == B)
4735       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4736
4737     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4738     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4739       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4740                                               I.getName()+".demorgan"), I);
4741       return BinaryOperator::CreateNot(And);
4742     }
4743   }
4744
4745   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4746   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4747     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4748       return R;
4749
4750     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4751       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4752         return Res;
4753   }
4754     
4755   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4756   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4757     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4758       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4759         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4760             !isa<ICmpInst>(Op1C->getOperand(0))) {
4761           const Type *SrcTy = Op0C->getOperand(0)->getType();
4762           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4763               // Only do this if the casts both really cause code to be
4764               // generated.
4765               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4766                                 I.getType(), TD) &&
4767               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4768                                 I.getType(), TD)) {
4769             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4770                                                           Op1C->getOperand(0),
4771                                                           I.getName());
4772             InsertNewInstBefore(NewOp, I);
4773             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4774           }
4775         }
4776       }
4777   }
4778   
4779     
4780   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4781   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4782     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4783       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4784           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4785           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4786         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4787           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4788             // If either of the constants are nans, then the whole thing returns
4789             // true.
4790             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4791               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4792             
4793             // Otherwise, no need to compare the two constants, compare the
4794             // rest.
4795             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4796                                 RHS->getOperand(0));
4797           }
4798       } else {
4799         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4800         FCmpInst::Predicate Op0CC, Op1CC;
4801         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4802             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4803           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4804             // Swap RHS operands to match LHS.
4805             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4806             std::swap(Op1LHS, Op1RHS);
4807           }
4808           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4809             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4810             if (Op0CC == Op1CC)
4811               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4812             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4813                      Op1CC == FCmpInst::FCMP_TRUE)
4814               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4815             else if (Op0CC == FCmpInst::FCMP_FALSE)
4816               return ReplaceInstUsesWith(I, Op1);
4817             else if (Op1CC == FCmpInst::FCMP_FALSE)
4818               return ReplaceInstUsesWith(I, Op0);
4819             bool Op0Ordered;
4820             bool Op1Ordered;
4821             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4822             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4823             if (Op0Ordered == Op1Ordered) {
4824               // If both are ordered or unordered, return a new fcmp with
4825               // or'ed predicates.
4826               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4827                                        Op0LHS, Op0RHS);
4828               if (Instruction *I = dyn_cast<Instruction>(RV))
4829                 return I;
4830               // Otherwise, it's a constant boolean value...
4831               return ReplaceInstUsesWith(I, RV);
4832             }
4833           }
4834         }
4835       }
4836     }
4837   }
4838
4839   return Changed ? &I : 0;
4840 }
4841
4842 namespace {
4843
4844 // XorSelf - Implements: X ^ X --> 0
4845 struct XorSelf {
4846   Value *RHS;
4847   XorSelf(Value *rhs) : RHS(rhs) {}
4848   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4849   Instruction *apply(BinaryOperator &Xor) const {
4850     return &Xor;
4851   }
4852 };
4853
4854 }
4855
4856 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4857   bool Changed = SimplifyCommutative(I);
4858   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4859
4860   if (isa<UndefValue>(Op1)) {
4861     if (isa<UndefValue>(Op0))
4862       // Handle undef ^ undef -> 0 special case. This is a common
4863       // idiom (misuse).
4864       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4865     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4866   }
4867
4868   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4869   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4870     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4871     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4872   }
4873   
4874   // See if we can simplify any instructions used by the instruction whose sole 
4875   // purpose is to compute bits we don't care about.
4876   if (!isa<VectorType>(I.getType())) {
4877     if (SimplifyDemandedInstructionBits(I))
4878       return &I;
4879   } else if (isa<ConstantAggregateZero>(Op1)) {
4880     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4881   }
4882
4883   // Is this a ~ operation?
4884   if (Value *NotOp = dyn_castNotVal(&I)) {
4885     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4886     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4887     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4888       if (Op0I->getOpcode() == Instruction::And || 
4889           Op0I->getOpcode() == Instruction::Or) {
4890         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4891         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4892           Instruction *NotY =
4893             BinaryOperator::CreateNot(Op0I->getOperand(1),
4894                                       Op0I->getOperand(1)->getName()+".not");
4895           InsertNewInstBefore(NotY, I);
4896           if (Op0I->getOpcode() == Instruction::And)
4897             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4898           else
4899             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4900         }
4901       }
4902     }
4903   }
4904   
4905   
4906   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4907     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4908       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4909       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4910         return new ICmpInst(ICI->getInversePredicate(),
4911                             ICI->getOperand(0), ICI->getOperand(1));
4912
4913       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4914         return new FCmpInst(FCI->getInversePredicate(),
4915                             FCI->getOperand(0), FCI->getOperand(1));
4916     }
4917
4918     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4919     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4920       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4921         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4922           Instruction::CastOps Opcode = Op0C->getOpcode();
4923           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4924             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4925                                              Op0C->getDestTy())) {
4926               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4927                                      CI->getOpcode(), CI->getInversePredicate(),
4928                                      CI->getOperand(0), CI->getOperand(1)), I);
4929               NewCI->takeName(CI);
4930               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4931             }
4932           }
4933         }
4934       }
4935     }
4936
4937     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4938       // ~(c-X) == X-c-1 == X+(-c-1)
4939       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4940         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4941           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4942           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4943                                               ConstantInt::get(I.getType(), 1));
4944           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4945         }
4946           
4947       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4948         if (Op0I->getOpcode() == Instruction::Add) {
4949           // ~(X-c) --> (-c-1)-X
4950           if (RHS->isAllOnesValue()) {
4951             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4952             return BinaryOperator::CreateSub(
4953                            ConstantExpr::getSub(NegOp0CI,
4954                                              ConstantInt::get(I.getType(), 1)),
4955                                           Op0I->getOperand(0));
4956           } else if (RHS->getValue().isSignBit()) {
4957             // (X + C) ^ signbit -> (X + C + signbit)
4958             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4959             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4960
4961           }
4962         } else if (Op0I->getOpcode() == Instruction::Or) {
4963           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4964           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4965             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4966             // Anything in both C1 and C2 is known to be zero, remove it from
4967             // NewRHS.
4968             Constant *CommonBits = And(Op0CI, RHS);
4969             NewRHS = ConstantExpr::getAnd(NewRHS, 
4970                                           ConstantExpr::getNot(CommonBits));
4971             AddToWorkList(Op0I);
4972             I.setOperand(0, Op0I->getOperand(0));
4973             I.setOperand(1, NewRHS);
4974             return &I;
4975           }
4976         }
4977       }
4978     }
4979
4980     // Try to fold constant and into select arguments.
4981     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4982       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4983         return R;
4984     if (isa<PHINode>(Op0))
4985       if (Instruction *NV = FoldOpIntoPhi(I))
4986         return NV;
4987   }
4988
4989   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4990     if (X == Op1)
4991       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4992
4993   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4994     if (X == Op0)
4995       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4996
4997   
4998   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4999   if (Op1I) {
5000     Value *A, *B;
5001     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5002       if (A == Op0) {              // B^(B|A) == (A|B)^B
5003         Op1I->swapOperands();
5004         I.swapOperands();
5005         std::swap(Op0, Op1);
5006       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5007         I.swapOperands();     // Simplified below.
5008         std::swap(Op0, Op1);
5009       }
5010     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5011       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5012     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5013       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5014     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5015       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5016         Op1I->swapOperands();
5017         std::swap(A, B);
5018       }
5019       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5020         I.swapOperands();     // Simplified below.
5021         std::swap(Op0, Op1);
5022       }
5023     }
5024   }
5025   
5026   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5027   if (Op0I) {
5028     Value *A, *B;
5029     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5030       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5031         std::swap(A, B);
5032       if (B == Op1) {                                // (A|B)^B == A & ~B
5033         Instruction *NotB =
5034           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5035         return BinaryOperator::CreateAnd(A, NotB);
5036       }
5037     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5038       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5039     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5040       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5041     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5042       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5043         std::swap(A, B);
5044       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5045           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5046         Instruction *N =
5047           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5048         return BinaryOperator::CreateAnd(N, Op1);
5049       }
5050     }
5051   }
5052   
5053   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5054   if (Op0I && Op1I && Op0I->isShift() && 
5055       Op0I->getOpcode() == Op1I->getOpcode() && 
5056       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5057       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5058     Instruction *NewOp =
5059       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5060                                                     Op1I->getOperand(0),
5061                                                     Op0I->getName()), I);
5062     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5063                                   Op1I->getOperand(1));
5064   }
5065     
5066   if (Op0I && Op1I) {
5067     Value *A, *B, *C, *D;
5068     // (A & B)^(A | B) -> A ^ B
5069     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5070         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5071       if ((A == C && B == D) || (A == D && B == C)) 
5072         return BinaryOperator::CreateXor(A, B);
5073     }
5074     // (A | B)^(A & B) -> A ^ B
5075     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5076         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5077       if ((A == C && B == D) || (A == D && B == C)) 
5078         return BinaryOperator::CreateXor(A, B);
5079     }
5080     
5081     // (A & B)^(C & D)
5082     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5083         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5084         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5085       // (X & Y)^(X & Y) -> (Y^Z) & X
5086       Value *X = 0, *Y = 0, *Z = 0;
5087       if (A == C)
5088         X = A, Y = B, Z = D;
5089       else if (A == D)
5090         X = A, Y = B, Z = C;
5091       else if (B == C)
5092         X = B, Y = A, Z = D;
5093       else if (B == D)
5094         X = B, Y = A, Z = C;
5095       
5096       if (X) {
5097         Instruction *NewOp =
5098         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5099         return BinaryOperator::CreateAnd(NewOp, X);
5100       }
5101     }
5102   }
5103     
5104   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5105   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5106     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5107       return R;
5108
5109   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5110   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5111     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5112       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5113         const Type *SrcTy = Op0C->getOperand(0)->getType();
5114         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5115             // Only do this if the casts both really cause code to be generated.
5116             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5117                               I.getType(), TD) &&
5118             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5119                               I.getType(), TD)) {
5120           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5121                                                          Op1C->getOperand(0),
5122                                                          I.getName());
5123           InsertNewInstBefore(NewOp, I);
5124           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5125         }
5126       }
5127   }
5128
5129   return Changed ? &I : 0;
5130 }
5131
5132 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5133 /// overflowed for this type.
5134 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5135                             ConstantInt *In2, bool IsSigned = false) {
5136   Result = cast<ConstantInt>(Add(In1, In2));
5137
5138   if (IsSigned)
5139     if (In2->getValue().isNegative())
5140       return Result->getValue().sgt(In1->getValue());
5141     else
5142       return Result->getValue().slt(In1->getValue());
5143   else
5144     return Result->getValue().ult(In1->getValue());
5145 }
5146
5147 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5148 /// overflowed for this type.
5149 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5150                             ConstantInt *In2, bool IsSigned = false) {
5151   Result = cast<ConstantInt>(Subtract(In1, In2));
5152
5153   if (IsSigned)
5154     if (In2->getValue().isNegative())
5155       return Result->getValue().slt(In1->getValue());
5156     else
5157       return Result->getValue().sgt(In1->getValue());
5158   else
5159     return Result->getValue().ugt(In1->getValue());
5160 }
5161
5162 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5163 /// code necessary to compute the offset from the base pointer (without adding
5164 /// in the base pointer).  Return the result as a signed integer of intptr size.
5165 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5166   TargetData &TD = IC.getTargetData();
5167   gep_type_iterator GTI = gep_type_begin(GEP);
5168   const Type *IntPtrTy = TD.getIntPtrType();
5169   Value *Result = Constant::getNullValue(IntPtrTy);
5170
5171   // Build a mask for high order bits.
5172   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5173   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5174
5175   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5176        ++i, ++GTI) {
5177     Value *Op = *i;
5178     uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
5179     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5180       if (OpC->isZero()) continue;
5181       
5182       // Handle a struct index, which adds its field offset to the pointer.
5183       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5184         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5185         
5186         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5187           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5188         else
5189           Result = IC.InsertNewInstBefore(
5190                    BinaryOperator::CreateAdd(Result,
5191                                              ConstantInt::get(IntPtrTy, Size),
5192                                              GEP->getName()+".offs"), I);
5193         continue;
5194       }
5195       
5196       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5197       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5198       Scale = ConstantExpr::getMul(OC, Scale);
5199       if (Constant *RC = dyn_cast<Constant>(Result))
5200         Result = ConstantExpr::getAdd(RC, Scale);
5201       else {
5202         // Emit an add instruction.
5203         Result = IC.InsertNewInstBefore(
5204            BinaryOperator::CreateAdd(Result, Scale,
5205                                      GEP->getName()+".offs"), I);
5206       }
5207       continue;
5208     }
5209     // Convert to correct type.
5210     if (Op->getType() != IntPtrTy) {
5211       if (Constant *OpC = dyn_cast<Constant>(Op))
5212         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5213       else
5214         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5215                                                  Op->getName()+".c"), I);
5216     }
5217     if (Size != 1) {
5218       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5219       if (Constant *OpC = dyn_cast<Constant>(Op))
5220         Op = ConstantExpr::getMul(OpC, Scale);
5221       else    // We'll let instcombine(mul) convert this to a shl if possible.
5222         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5223                                                   GEP->getName()+".idx"), I);
5224     }
5225
5226     // Emit an add instruction.
5227     if (isa<Constant>(Op) && isa<Constant>(Result))
5228       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5229                                     cast<Constant>(Result));
5230     else
5231       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5232                                                   GEP->getName()+".offs"), I);
5233   }
5234   return Result;
5235 }
5236
5237
5238 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5239 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5240 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5241 /// complex, and scales are involved.  The above expression would also be legal
5242 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5243 /// later form is less amenable to optimization though, and we are allowed to
5244 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5245 ///
5246 /// If we can't emit an optimized form for this expression, this returns null.
5247 /// 
5248 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5249                                           InstCombiner &IC) {
5250   TargetData &TD = IC.getTargetData();
5251   gep_type_iterator GTI = gep_type_begin(GEP);
5252
5253   // Check to see if this gep only has a single variable index.  If so, and if
5254   // any constant indices are a multiple of its scale, then we can compute this
5255   // in terms of the scale of the variable index.  For example, if the GEP
5256   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5257   // because the expression will cross zero at the same point.
5258   unsigned i, e = GEP->getNumOperands();
5259   int64_t Offset = 0;
5260   for (i = 1; i != e; ++i, ++GTI) {
5261     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5262       // Compute the aggregate offset of constant indices.
5263       if (CI->isZero()) continue;
5264
5265       // Handle a struct index, which adds its field offset to the pointer.
5266       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5267         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5268       } else {
5269         uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5270         Offset += Size*CI->getSExtValue();
5271       }
5272     } else {
5273       // Found our variable index.
5274       break;
5275     }
5276   }
5277   
5278   // If there are no variable indices, we must have a constant offset, just
5279   // evaluate it the general way.
5280   if (i == e) return 0;
5281   
5282   Value *VariableIdx = GEP->getOperand(i);
5283   // Determine the scale factor of the variable element.  For example, this is
5284   // 4 if the variable index is into an array of i32.
5285   uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
5286   
5287   // Verify that there are no other variable indices.  If so, emit the hard way.
5288   for (++i, ++GTI; i != e; ++i, ++GTI) {
5289     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5290     if (!CI) return 0;
5291    
5292     // Compute the aggregate offset of constant indices.
5293     if (CI->isZero()) continue;
5294     
5295     // Handle a struct index, which adds its field offset to the pointer.
5296     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5297       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5298     } else {
5299       uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5300       Offset += Size*CI->getSExtValue();
5301     }
5302   }
5303   
5304   // Okay, we know we have a single variable index, which must be a
5305   // pointer/array/vector index.  If there is no offset, life is simple, return
5306   // the index.
5307   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5308   if (Offset == 0) {
5309     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5310     // we don't need to bother extending: the extension won't affect where the
5311     // computation crosses zero.
5312     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5313       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5314                                   VariableIdx->getNameStart(), &I);
5315     return VariableIdx;
5316   }
5317   
5318   // Otherwise, there is an index.  The computation we will do will be modulo
5319   // the pointer size, so get it.
5320   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5321   
5322   Offset &= PtrSizeMask;
5323   VariableScale &= PtrSizeMask;
5324
5325   // To do this transformation, any constant index must be a multiple of the
5326   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5327   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5328   // multiple of the variable scale.
5329   int64_t NewOffs = Offset / (int64_t)VariableScale;
5330   if (Offset != NewOffs*(int64_t)VariableScale)
5331     return 0;
5332
5333   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5334   const Type *IntPtrTy = TD.getIntPtrType();
5335   if (VariableIdx->getType() != IntPtrTy)
5336     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5337                                               true /*SExt*/, 
5338                                               VariableIdx->getNameStart(), &I);
5339   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5340   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5341 }
5342
5343
5344 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5345 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5346 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5347                                        ICmpInst::Predicate Cond,
5348                                        Instruction &I) {
5349   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5350
5351   // Look through bitcasts.
5352   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5353     RHS = BCI->getOperand(0);
5354
5355   Value *PtrBase = GEPLHS->getOperand(0);
5356   if (PtrBase == RHS) {
5357     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5358     // This transformation (ignoring the base and scales) is valid because we
5359     // know pointers can't overflow.  See if we can output an optimized form.
5360     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5361     
5362     // If not, synthesize the offset the hard way.
5363     if (Offset == 0)
5364       Offset = EmitGEPOffset(GEPLHS, I, *this);
5365     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5366                         Constant::getNullValue(Offset->getType()));
5367   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5368     // If the base pointers are different, but the indices are the same, just
5369     // compare the base pointer.
5370     if (PtrBase != GEPRHS->getOperand(0)) {
5371       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5372       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5373                         GEPRHS->getOperand(0)->getType();
5374       if (IndicesTheSame)
5375         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5376           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5377             IndicesTheSame = false;
5378             break;
5379           }
5380
5381       // If all indices are the same, just compare the base pointers.
5382       if (IndicesTheSame)
5383         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5384                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5385
5386       // Otherwise, the base pointers are different and the indices are
5387       // different, bail out.
5388       return 0;
5389     }
5390
5391     // If one of the GEPs has all zero indices, recurse.
5392     bool AllZeros = true;
5393     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5394       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5395           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5396         AllZeros = false;
5397         break;
5398       }
5399     if (AllZeros)
5400       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5401                           ICmpInst::getSwappedPredicate(Cond), I);
5402
5403     // If the other GEP has all zero indices, recurse.
5404     AllZeros = true;
5405     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5406       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5407           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5408         AllZeros = false;
5409         break;
5410       }
5411     if (AllZeros)
5412       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5413
5414     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5415       // If the GEPs only differ by one index, compare it.
5416       unsigned NumDifferences = 0;  // Keep track of # differences.
5417       unsigned DiffOperand = 0;     // The operand that differs.
5418       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5419         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5420           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5421                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5422             // Irreconcilable differences.
5423             NumDifferences = 2;
5424             break;
5425           } else {
5426             if (NumDifferences++) break;
5427             DiffOperand = i;
5428           }
5429         }
5430
5431       if (NumDifferences == 0)   // SAME GEP?
5432         return ReplaceInstUsesWith(I, // No comparison is needed here.
5433                                    ConstantInt::get(Type::Int1Ty,
5434                                              ICmpInst::isTrueWhenEqual(Cond)));
5435
5436       else if (NumDifferences == 1) {
5437         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5438         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5439         // Make sure we do a signed comparison here.
5440         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5441       }
5442     }
5443
5444     // Only lower this if the icmp is the only user of the GEP or if we expect
5445     // the result to fold to a constant!
5446     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5447         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5448       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5449       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5450       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5451       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5452     }
5453   }
5454   return 0;
5455 }
5456
5457 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5458 ///
5459 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5460                                                 Instruction *LHSI,
5461                                                 Constant *RHSC) {
5462   if (!isa<ConstantFP>(RHSC)) return 0;
5463   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5464   
5465   // Get the width of the mantissa.  We don't want to hack on conversions that
5466   // might lose information from the integer, e.g. "i64 -> float"
5467   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5468   if (MantissaWidth == -1) return 0;  // Unknown.
5469   
5470   // Check to see that the input is converted from an integer type that is small
5471   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5472   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5473   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5474   
5475   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5476   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5477   if (LHSUnsigned)
5478     ++InputSize;
5479   
5480   // If the conversion would lose info, don't hack on this.
5481   if ((int)InputSize > MantissaWidth)
5482     return 0;
5483   
5484   // Otherwise, we can potentially simplify the comparison.  We know that it
5485   // will always come through as an integer value and we know the constant is
5486   // not a NAN (it would have been previously simplified).
5487   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5488   
5489   ICmpInst::Predicate Pred;
5490   switch (I.getPredicate()) {
5491   default: assert(0 && "Unexpected predicate!");
5492   case FCmpInst::FCMP_UEQ:
5493   case FCmpInst::FCMP_OEQ:
5494     Pred = ICmpInst::ICMP_EQ;
5495     break;
5496   case FCmpInst::FCMP_UGT:
5497   case FCmpInst::FCMP_OGT:
5498     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5499     break;
5500   case FCmpInst::FCMP_UGE:
5501   case FCmpInst::FCMP_OGE:
5502     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5503     break;
5504   case FCmpInst::FCMP_ULT:
5505   case FCmpInst::FCMP_OLT:
5506     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5507     break;
5508   case FCmpInst::FCMP_ULE:
5509   case FCmpInst::FCMP_OLE:
5510     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5511     break;
5512   case FCmpInst::FCMP_UNE:
5513   case FCmpInst::FCMP_ONE:
5514     Pred = ICmpInst::ICMP_NE;
5515     break;
5516   case FCmpInst::FCMP_ORD:
5517     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5518   case FCmpInst::FCMP_UNO:
5519     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5520   }
5521   
5522   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5523   
5524   // Now we know that the APFloat is a normal number, zero or inf.
5525   
5526   // See if the FP constant is too large for the integer.  For example,
5527   // comparing an i8 to 300.0.
5528   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5529   
5530   if (!LHSUnsigned) {
5531     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5532     // and large values.
5533     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5534     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5535                           APFloat::rmNearestTiesToEven);
5536     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5537       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5538           Pred == ICmpInst::ICMP_SLE)
5539         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5540       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5541     }
5542   } else {
5543     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5544     // +INF and large values.
5545     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5546     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5547                           APFloat::rmNearestTiesToEven);
5548     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5549       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5550           Pred == ICmpInst::ICMP_ULE)
5551         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5552       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5553     }
5554   }
5555   
5556   if (!LHSUnsigned) {
5557     // See if the RHS value is < SignedMin.
5558     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5559     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5560                           APFloat::rmNearestTiesToEven);
5561     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5562       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5563           Pred == ICmpInst::ICMP_SGE)
5564         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5565       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5566     }
5567   }
5568
5569   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5570   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5571   // casting the FP value to the integer value and back, checking for equality.
5572   // Don't do this for zero, because -0.0 is not fractional.
5573   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5574   if (!RHS.isZero() &&
5575       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5576     // If we had a comparison against a fractional value, we have to adjust the
5577     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5578     // at this point.
5579     switch (Pred) {
5580     default: assert(0 && "Unexpected integer comparison!");
5581     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5582       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5583     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5584       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5585     case ICmpInst::ICMP_ULE:
5586       // (float)int <= 4.4   --> int <= 4
5587       // (float)int <= -4.4  --> false
5588       if (RHS.isNegative())
5589         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5590       break;
5591     case ICmpInst::ICMP_SLE:
5592       // (float)int <= 4.4   --> int <= 4
5593       // (float)int <= -4.4  --> int < -4
5594       if (RHS.isNegative())
5595         Pred = ICmpInst::ICMP_SLT;
5596       break;
5597     case ICmpInst::ICMP_ULT:
5598       // (float)int < -4.4   --> false
5599       // (float)int < 4.4    --> int <= 4
5600       if (RHS.isNegative())
5601         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5602       Pred = ICmpInst::ICMP_ULE;
5603       break;
5604     case ICmpInst::ICMP_SLT:
5605       // (float)int < -4.4   --> int < -4
5606       // (float)int < 4.4    --> int <= 4
5607       if (!RHS.isNegative())
5608         Pred = ICmpInst::ICMP_SLE;
5609       break;
5610     case ICmpInst::ICMP_UGT:
5611       // (float)int > 4.4    --> int > 4
5612       // (float)int > -4.4   --> true
5613       if (RHS.isNegative())
5614         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5615       break;
5616     case ICmpInst::ICMP_SGT:
5617       // (float)int > 4.4    --> int > 4
5618       // (float)int > -4.4   --> int >= -4
5619       if (RHS.isNegative())
5620         Pred = ICmpInst::ICMP_SGE;
5621       break;
5622     case ICmpInst::ICMP_UGE:
5623       // (float)int >= -4.4   --> true
5624       // (float)int >= 4.4    --> int > 4
5625       if (!RHS.isNegative())
5626         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5627       Pred = ICmpInst::ICMP_UGT;
5628       break;
5629     case ICmpInst::ICMP_SGE:
5630       // (float)int >= -4.4   --> int >= -4
5631       // (float)int >= 4.4    --> int > 4
5632       if (!RHS.isNegative())
5633         Pred = ICmpInst::ICMP_SGT;
5634       break;
5635     }
5636   }
5637
5638   // Lower this FP comparison into an appropriate integer version of the
5639   // comparison.
5640   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5641 }
5642
5643 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5644   bool Changed = SimplifyCompare(I);
5645   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5646
5647   // Fold trivial predicates.
5648   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5649     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5650   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5651     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5652   
5653   // Simplify 'fcmp pred X, X'
5654   if (Op0 == Op1) {
5655     switch (I.getPredicate()) {
5656     default: assert(0 && "Unknown predicate!");
5657     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5658     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5659     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5660       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5661     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5662     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5663     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5664       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5665       
5666     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5667     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5668     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5669     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5670       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5671       I.setPredicate(FCmpInst::FCMP_UNO);
5672       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5673       return &I;
5674       
5675     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5676     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5677     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5678     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5679       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5680       I.setPredicate(FCmpInst::FCMP_ORD);
5681       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5682       return &I;
5683     }
5684   }
5685     
5686   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5687     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5688
5689   // Handle fcmp with constant RHS
5690   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5691     // If the constant is a nan, see if we can fold the comparison based on it.
5692     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5693       if (CFP->getValueAPF().isNaN()) {
5694         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5695           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5696         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5697                "Comparison must be either ordered or unordered!");
5698         // True if unordered.
5699         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5700       }
5701     }
5702     
5703     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5704       switch (LHSI->getOpcode()) {
5705       case Instruction::PHI:
5706         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5707         // block.  If in the same block, we're encouraging jump threading.  If
5708         // not, we are just pessimizing the code by making an i1 phi.
5709         if (LHSI->getParent() == I.getParent())
5710           if (Instruction *NV = FoldOpIntoPhi(I))
5711             return NV;
5712         break;
5713       case Instruction::SIToFP:
5714       case Instruction::UIToFP:
5715         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5716           return NV;
5717         break;
5718       case Instruction::Select:
5719         // If either operand of the select is a constant, we can fold the
5720         // comparison into the select arms, which will cause one to be
5721         // constant folded and the select turned into a bitwise or.
5722         Value *Op1 = 0, *Op2 = 0;
5723         if (LHSI->hasOneUse()) {
5724           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5725             // Fold the known value into the constant operand.
5726             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5727             // Insert a new FCmp of the other select operand.
5728             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5729                                                       LHSI->getOperand(2), RHSC,
5730                                                       I.getName()), I);
5731           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5732             // Fold the known value into the constant operand.
5733             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5734             // Insert a new FCmp of the other select operand.
5735             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5736                                                       LHSI->getOperand(1), RHSC,
5737                                                       I.getName()), I);
5738           }
5739         }
5740
5741         if (Op1)
5742           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5743         break;
5744       }
5745   }
5746
5747   return Changed ? &I : 0;
5748 }
5749
5750 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5751   bool Changed = SimplifyCompare(I);
5752   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5753   const Type *Ty = Op0->getType();
5754
5755   // icmp X, X
5756   if (Op0 == Op1)
5757     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5758                                                    I.isTrueWhenEqual()));
5759
5760   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5761     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5762   
5763   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5764   // addresses never equal each other!  We already know that Op0 != Op1.
5765   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5766        isa<ConstantPointerNull>(Op0)) &&
5767       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5768        isa<ConstantPointerNull>(Op1)))
5769     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5770                                                    !I.isTrueWhenEqual()));
5771
5772   // icmp's with boolean values can always be turned into bitwise operations
5773   if (Ty == Type::Int1Ty) {
5774     switch (I.getPredicate()) {
5775     default: assert(0 && "Invalid icmp instruction!");
5776     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5777       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5778       InsertNewInstBefore(Xor, I);
5779       return BinaryOperator::CreateNot(Xor);
5780     }
5781     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5782       return BinaryOperator::CreateXor(Op0, Op1);
5783
5784     case ICmpInst::ICMP_UGT:
5785       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5786       // FALL THROUGH
5787     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5788       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5789       InsertNewInstBefore(Not, I);
5790       return BinaryOperator::CreateAnd(Not, Op1);
5791     }
5792     case ICmpInst::ICMP_SGT:
5793       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5794       // FALL THROUGH
5795     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5796       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5797       InsertNewInstBefore(Not, I);
5798       return BinaryOperator::CreateAnd(Not, Op0);
5799     }
5800     case ICmpInst::ICMP_UGE:
5801       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5802       // FALL THROUGH
5803     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5804       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5805       InsertNewInstBefore(Not, I);
5806       return BinaryOperator::CreateOr(Not, Op1);
5807     }
5808     case ICmpInst::ICMP_SGE:
5809       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5810       // FALL THROUGH
5811     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5812       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5813       InsertNewInstBefore(Not, I);
5814       return BinaryOperator::CreateOr(Not, Op0);
5815     }
5816     }
5817   }
5818
5819   // See if we are doing a comparison with a constant.
5820   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5821     Value *A, *B;
5822     
5823     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5824     if (I.isEquality() && CI->isNullValue() &&
5825         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5826       // (icmp cond A B) if cond is equality
5827       return new ICmpInst(I.getPredicate(), A, B);
5828     }
5829     
5830     // If we have an icmp le or icmp ge instruction, turn it into the
5831     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5832     // them being folded in the code below.
5833     switch (I.getPredicate()) {
5834     default: break;
5835     case ICmpInst::ICMP_ULE:
5836       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5837         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5838       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5839     case ICmpInst::ICMP_SLE:
5840       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5841         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5842       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5843     case ICmpInst::ICMP_UGE:
5844       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5845         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5846       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5847     case ICmpInst::ICMP_SGE:
5848       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5849         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5850       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5851     }
5852     
5853     // See if we can fold the comparison based on range information we can get
5854     // by checking whether bits are known to be zero or one in the input.
5855     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5856     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5857     
5858     // If this comparison is a normal comparison, it demands all
5859     // bits, if it is a sign bit comparison, it only demands the sign bit.
5860     bool UnusedBit;
5861     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5862     
5863     if (SimplifyDemandedBits(I.getOperandUse(0), 
5864                              isSignBit ? APInt::getSignBit(BitWidth)
5865                                        : APInt::getAllOnesValue(BitWidth),
5866                              KnownZero, KnownOne, 0))
5867       return &I;
5868         
5869     // Given the known and unknown bits, compute a range that the LHS could be
5870     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5871     // EQ and NE we use unsigned values.
5872     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5873     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5874       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5875     else
5876       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5877     
5878     // If Min and Max are known to be the same, then SimplifyDemandedBits
5879     // figured out that the LHS is a constant.  Just constant fold this now so
5880     // that code below can assume that Min != Max.
5881     if (Min == Max)
5882       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5883                                                           ConstantInt::get(Min),
5884                                                           CI));
5885     
5886     // Based on the range information we know about the LHS, see if we can
5887     // simplify this comparison.  For example, (x&4) < 8  is always true.
5888     const APInt &RHSVal = CI->getValue();
5889     switch (I.getPredicate()) {  // LE/GE have been folded already.
5890     default: assert(0 && "Unknown icmp opcode!");
5891     case ICmpInst::ICMP_EQ:
5892       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5893         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5894       break;
5895     case ICmpInst::ICMP_NE:
5896       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5897         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5898       break;
5899     case ICmpInst::ICMP_ULT:
5900       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5901         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5902       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5903         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5904       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5905         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5906       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5907         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5908         
5909       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5910       if (CI->isMinValue(true))
5911         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5912                             ConstantInt::getAllOnesValue(Op0->getType()));
5913       break;
5914     case ICmpInst::ICMP_UGT:
5915       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5916         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5917       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5918         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5919         
5920       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5921         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5922       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5923         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5924       
5925       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5926       if (CI->isMaxValue(true))
5927         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5928                             ConstantInt::getNullValue(Op0->getType()));
5929       break;
5930     case ICmpInst::ICMP_SLT:
5931       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5932         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5933       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5934         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5935       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5936         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5937       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5938         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5939       break;
5940     case ICmpInst::ICMP_SGT: 
5941       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5942         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5943       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5944         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5945         
5946       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5947         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5948       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5949         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5950       break;
5951     }
5952   }
5953
5954   // Test if the ICmpInst instruction is used exclusively by a select as
5955   // part of a minimum or maximum operation. If so, refrain from doing
5956   // any other folding. This helps out other analyses which understand
5957   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5958   // and CodeGen. And in this case, at least one of the comparison
5959   // operands has at least one user besides the compare (the select),
5960   // which would often largely negate the benefit of folding anyway.
5961   if (I.hasOneUse())
5962     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5963       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5964           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5965         return 0;
5966
5967   // See if we are doing a comparison between a constant and an instruction that
5968   // can be folded into the comparison.
5969   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5970     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5971     // instruction, see if that instruction also has constants so that the 
5972     // instruction can be folded into the icmp 
5973     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5974       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5975         return Res;
5976   }
5977
5978   // Handle icmp with constant (but not simple integer constant) RHS
5979   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5980     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5981       switch (LHSI->getOpcode()) {
5982       case Instruction::GetElementPtr:
5983         if (RHSC->isNullValue()) {
5984           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5985           bool isAllZeros = true;
5986           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5987             if (!isa<Constant>(LHSI->getOperand(i)) ||
5988                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5989               isAllZeros = false;
5990               break;
5991             }
5992           if (isAllZeros)
5993             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5994                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5995         }
5996         break;
5997
5998       case Instruction::PHI:
5999         // Only fold icmp into the PHI if the phi and fcmp are in the same
6000         // block.  If in the same block, we're encouraging jump threading.  If
6001         // not, we are just pessimizing the code by making an i1 phi.
6002         if (LHSI->getParent() == I.getParent())
6003           if (Instruction *NV = FoldOpIntoPhi(I))
6004             return NV;
6005         break;
6006       case Instruction::Select: {
6007         // If either operand of the select is a constant, we can fold the
6008         // comparison into the select arms, which will cause one to be
6009         // constant folded and the select turned into a bitwise or.
6010         Value *Op1 = 0, *Op2 = 0;
6011         if (LHSI->hasOneUse()) {
6012           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6013             // Fold the known value into the constant operand.
6014             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6015             // Insert a new ICmp of the other select operand.
6016             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6017                                                    LHSI->getOperand(2), RHSC,
6018                                                    I.getName()), I);
6019           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6020             // Fold the known value into the constant operand.
6021             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6022             // Insert a new ICmp of the other select operand.
6023             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6024                                                    LHSI->getOperand(1), RHSC,
6025                                                    I.getName()), I);
6026           }
6027         }
6028
6029         if (Op1)
6030           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6031         break;
6032       }
6033       case Instruction::Malloc:
6034         // If we have (malloc != null), and if the malloc has a single use, we
6035         // can assume it is successful and remove the malloc.
6036         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6037           AddToWorkList(LHSI);
6038           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6039                                                          !I.isTrueWhenEqual()));
6040         }
6041         break;
6042       }
6043   }
6044
6045   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6046   if (User *GEP = dyn_castGetElementPtr(Op0))
6047     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6048       return NI;
6049   if (User *GEP = dyn_castGetElementPtr(Op1))
6050     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6051                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6052       return NI;
6053
6054   // Test to see if the operands of the icmp are casted versions of other
6055   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6056   // now.
6057   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6058     if (isa<PointerType>(Op0->getType()) && 
6059         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6060       // We keep moving the cast from the left operand over to the right
6061       // operand, where it can often be eliminated completely.
6062       Op0 = CI->getOperand(0);
6063
6064       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6065       // so eliminate it as well.
6066       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6067         Op1 = CI2->getOperand(0);
6068
6069       // If Op1 is a constant, we can fold the cast into the constant.
6070       if (Op0->getType() != Op1->getType()) {
6071         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6072           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6073         } else {
6074           // Otherwise, cast the RHS right before the icmp
6075           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6076         }
6077       }
6078       return new ICmpInst(I.getPredicate(), Op0, Op1);
6079     }
6080   }
6081   
6082   if (isa<CastInst>(Op0)) {
6083     // Handle the special case of: icmp (cast bool to X), <cst>
6084     // This comes up when you have code like
6085     //   int X = A < B;
6086     //   if (X) ...
6087     // For generality, we handle any zero-extension of any operand comparison
6088     // with a constant or another cast from the same type.
6089     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6090       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6091         return R;
6092   }
6093   
6094   // See if it's the same type of instruction on the left and right.
6095   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6096     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6097       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6098           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6099         switch (Op0I->getOpcode()) {
6100         default: break;
6101         case Instruction::Add:
6102         case Instruction::Sub:
6103         case Instruction::Xor:
6104           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6105             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6106                                 Op1I->getOperand(0));
6107           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6108           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6109             if (CI->getValue().isSignBit()) {
6110               ICmpInst::Predicate Pred = I.isSignedPredicate()
6111                                              ? I.getUnsignedPredicate()
6112                                              : I.getSignedPredicate();
6113               return new ICmpInst(Pred, Op0I->getOperand(0),
6114                                   Op1I->getOperand(0));
6115             }
6116             
6117             if (CI->getValue().isMaxSignedValue()) {
6118               ICmpInst::Predicate Pred = I.isSignedPredicate()
6119                                              ? I.getUnsignedPredicate()
6120                                              : I.getSignedPredicate();
6121               Pred = I.getSwappedPredicate(Pred);
6122               return new ICmpInst(Pred, Op0I->getOperand(0),
6123                                   Op1I->getOperand(0));
6124             }
6125           }
6126           break;
6127         case Instruction::Mul:
6128           if (!I.isEquality())
6129             break;
6130
6131           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6132             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6133             // Mask = -1 >> count-trailing-zeros(Cst).
6134             if (!CI->isZero() && !CI->isOne()) {
6135               const APInt &AP = CI->getValue();
6136               ConstantInt *Mask = ConstantInt::get(
6137                                       APInt::getLowBitsSet(AP.getBitWidth(),
6138                                                            AP.getBitWidth() -
6139                                                       AP.countTrailingZeros()));
6140               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6141                                                             Mask);
6142               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6143                                                             Mask);
6144               InsertNewInstBefore(And1, I);
6145               InsertNewInstBefore(And2, I);
6146               return new ICmpInst(I.getPredicate(), And1, And2);
6147             }
6148           }
6149           break;
6150         }
6151       }
6152     }
6153   }
6154   
6155   // ~x < ~y --> y < x
6156   { Value *A, *B;
6157     if (match(Op0, m_Not(m_Value(A))) &&
6158         match(Op1, m_Not(m_Value(B))))
6159       return new ICmpInst(I.getPredicate(), B, A);
6160   }
6161   
6162   if (I.isEquality()) {
6163     Value *A, *B, *C, *D;
6164     
6165     // -x == -y --> x == y
6166     if (match(Op0, m_Neg(m_Value(A))) &&
6167         match(Op1, m_Neg(m_Value(B))))
6168       return new ICmpInst(I.getPredicate(), A, B);
6169     
6170     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6171       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6172         Value *OtherVal = A == Op1 ? B : A;
6173         return new ICmpInst(I.getPredicate(), OtherVal,
6174                             Constant::getNullValue(A->getType()));
6175       }
6176
6177       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6178         // A^c1 == C^c2 --> A == C^(c1^c2)
6179         ConstantInt *C1, *C2;
6180         if (match(B, m_ConstantInt(C1)) &&
6181             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6182           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6183           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6184           return new ICmpInst(I.getPredicate(), A,
6185                               InsertNewInstBefore(Xor, I));
6186         }
6187         
6188         // A^B == A^D -> B == D
6189         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6190         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6191         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6192         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6193       }
6194     }
6195     
6196     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6197         (A == Op0 || B == Op0)) {
6198       // A == (A^B)  ->  B == 0
6199       Value *OtherVal = A == Op0 ? B : A;
6200       return new ICmpInst(I.getPredicate(), OtherVal,
6201                           Constant::getNullValue(A->getType()));
6202     }
6203
6204     // (A-B) == A  ->  B == 0
6205     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6206       return new ICmpInst(I.getPredicate(), B, 
6207                           Constant::getNullValue(B->getType()));
6208
6209     // A == (A-B)  ->  B == 0
6210     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6211       return new ICmpInst(I.getPredicate(), B,
6212                           Constant::getNullValue(B->getType()));
6213     
6214     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6215     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6216         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6217         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6218       Value *X = 0, *Y = 0, *Z = 0;
6219       
6220       if (A == C) {
6221         X = B; Y = D; Z = A;
6222       } else if (A == D) {
6223         X = B; Y = C; Z = A;
6224       } else if (B == C) {
6225         X = A; Y = D; Z = B;
6226       } else if (B == D) {
6227         X = A; Y = C; Z = B;
6228       }
6229       
6230       if (X) {   // Build (X^Y) & Z
6231         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6232         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6233         I.setOperand(0, Op1);
6234         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6235         return &I;
6236       }
6237     }
6238   }
6239   return Changed ? &I : 0;
6240 }
6241
6242
6243 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6244 /// and CmpRHS are both known to be integer constants.
6245 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6246                                           ConstantInt *DivRHS) {
6247   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6248   const APInt &CmpRHSV = CmpRHS->getValue();
6249   
6250   // FIXME: If the operand types don't match the type of the divide 
6251   // then don't attempt this transform. The code below doesn't have the
6252   // logic to deal with a signed divide and an unsigned compare (and
6253   // vice versa). This is because (x /s C1) <s C2  produces different 
6254   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6255   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6256   // work. :(  The if statement below tests that condition and bails 
6257   // if it finds it. 
6258   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6259   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6260     return 0;
6261   if (DivRHS->isZero())
6262     return 0; // The ProdOV computation fails on divide by zero.
6263   if (DivIsSigned && DivRHS->isAllOnesValue())
6264     return 0; // The overflow computation also screws up here
6265   if (DivRHS->isOne())
6266     return 0; // Not worth bothering, and eliminates some funny cases
6267               // with INT_MIN.
6268
6269   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6270   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6271   // C2 (CI). By solving for X we can turn this into a range check 
6272   // instead of computing a divide. 
6273   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6274
6275   // Determine if the product overflows by seeing if the product is
6276   // not equal to the divide. Make sure we do the same kind of divide
6277   // as in the LHS instruction that we're folding. 
6278   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6279                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6280
6281   // Get the ICmp opcode
6282   ICmpInst::Predicate Pred = ICI.getPredicate();
6283
6284   // Figure out the interval that is being checked.  For example, a comparison
6285   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6286   // Compute this interval based on the constants involved and the signedness of
6287   // the compare/divide.  This computes a half-open interval, keeping track of
6288   // whether either value in the interval overflows.  After analysis each
6289   // overflow variable is set to 0 if it's corresponding bound variable is valid
6290   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6291   int LoOverflow = 0, HiOverflow = 0;
6292   ConstantInt *LoBound = 0, *HiBound = 0;
6293   
6294   if (!DivIsSigned) {  // udiv
6295     // e.g. X/5 op 3  --> [15, 20)
6296     LoBound = Prod;
6297     HiOverflow = LoOverflow = ProdOV;
6298     if (!HiOverflow)
6299       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6300   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6301     if (CmpRHSV == 0) {       // (X / pos) op 0
6302       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6303       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6304       HiBound = DivRHS;
6305     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6306       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6307       HiOverflow = LoOverflow = ProdOV;
6308       if (!HiOverflow)
6309         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6310     } else {                       // (X / pos) op neg
6311       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6312       HiBound = AddOne(Prod);
6313       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6314       if (!LoOverflow) {
6315         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6316         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6317                                      true) ? -1 : 0;
6318        }
6319     }
6320   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6321     if (CmpRHSV == 0) {       // (X / neg) op 0
6322       // e.g. X/-5 op 0  --> [-4, 5)
6323       LoBound = AddOne(DivRHS);
6324       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6325       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6326         HiOverflow = 1;            // [INTMIN+1, overflow)
6327         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6328       }
6329     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6330       // e.g. X/-5 op 3  --> [-19, -14)
6331       HiBound = AddOne(Prod);
6332       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6333       if (!LoOverflow)
6334         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6335     } else {                       // (X / neg) op neg
6336       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6337       LoOverflow = HiOverflow = ProdOV;
6338       if (!HiOverflow)
6339         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6340     }
6341     
6342     // Dividing by a negative swaps the condition.  LT <-> GT
6343     Pred = ICmpInst::getSwappedPredicate(Pred);
6344   }
6345
6346   Value *X = DivI->getOperand(0);
6347   switch (Pred) {
6348   default: assert(0 && "Unhandled icmp opcode!");
6349   case ICmpInst::ICMP_EQ:
6350     if (LoOverflow && HiOverflow)
6351       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6352     else if (HiOverflow)
6353       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6354                           ICmpInst::ICMP_UGE, X, LoBound);
6355     else if (LoOverflow)
6356       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6357                           ICmpInst::ICMP_ULT, X, HiBound);
6358     else
6359       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6360   case ICmpInst::ICMP_NE:
6361     if (LoOverflow && HiOverflow)
6362       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6363     else if (HiOverflow)
6364       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6365                           ICmpInst::ICMP_ULT, X, LoBound);
6366     else if (LoOverflow)
6367       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6368                           ICmpInst::ICMP_UGE, X, HiBound);
6369     else
6370       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6371   case ICmpInst::ICMP_ULT:
6372   case ICmpInst::ICMP_SLT:
6373     if (LoOverflow == +1)   // Low bound is greater than input range.
6374       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6375     if (LoOverflow == -1)   // Low bound is less than input range.
6376       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6377     return new ICmpInst(Pred, X, LoBound);
6378   case ICmpInst::ICMP_UGT:
6379   case ICmpInst::ICMP_SGT:
6380     if (HiOverflow == +1)       // High bound greater than input range.
6381       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6382     else if (HiOverflow == -1)  // High bound less than input range.
6383       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6384     if (Pred == ICmpInst::ICMP_UGT)
6385       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6386     else
6387       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6388   }
6389 }
6390
6391
6392 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6393 ///
6394 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6395                                                           Instruction *LHSI,
6396                                                           ConstantInt *RHS) {
6397   const APInt &RHSV = RHS->getValue();
6398   
6399   switch (LHSI->getOpcode()) {
6400   case Instruction::Trunc:
6401     if (ICI.isEquality() && LHSI->hasOneUse()) {
6402       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6403       // of the high bits truncated out of x are known.
6404       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6405              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6406       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6407       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6408       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6409       
6410       // If all the high bits are known, we can do this xform.
6411       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6412         // Pull in the high bits from known-ones set.
6413         APInt NewRHS(RHS->getValue());
6414         NewRHS.zext(SrcBits);
6415         NewRHS |= KnownOne;
6416         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6417                             ConstantInt::get(NewRHS));
6418       }
6419     }
6420     break;
6421       
6422   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6423     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6424       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6425       // fold the xor.
6426       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6427           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6428         Value *CompareVal = LHSI->getOperand(0);
6429         
6430         // If the sign bit of the XorCST is not set, there is no change to
6431         // the operation, just stop using the Xor.
6432         if (!XorCST->getValue().isNegative()) {
6433           ICI.setOperand(0, CompareVal);
6434           AddToWorkList(LHSI);
6435           return &ICI;
6436         }
6437         
6438         // Was the old condition true if the operand is positive?
6439         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6440         
6441         // If so, the new one isn't.
6442         isTrueIfPositive ^= true;
6443         
6444         if (isTrueIfPositive)
6445           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6446         else
6447           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6448       }
6449
6450       if (LHSI->hasOneUse()) {
6451         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6452         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6453           const APInt &SignBit = XorCST->getValue();
6454           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6455                                          ? ICI.getUnsignedPredicate()
6456                                          : ICI.getSignedPredicate();
6457           return new ICmpInst(Pred, LHSI->getOperand(0),
6458                               ConstantInt::get(RHSV ^ SignBit));
6459         }
6460
6461         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6462         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6463           const APInt &NotSignBit = XorCST->getValue();
6464           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6465                                          ? ICI.getUnsignedPredicate()
6466                                          : ICI.getSignedPredicate();
6467           Pred = ICI.getSwappedPredicate(Pred);
6468           return new ICmpInst(Pred, LHSI->getOperand(0),
6469                               ConstantInt::get(RHSV ^ NotSignBit));
6470         }
6471       }
6472     }
6473     break;
6474   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6475     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6476         LHSI->getOperand(0)->hasOneUse()) {
6477       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6478       
6479       // If the LHS is an AND of a truncating cast, we can widen the
6480       // and/compare to be the input width without changing the value
6481       // produced, eliminating a cast.
6482       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6483         // We can do this transformation if either the AND constant does not
6484         // have its sign bit set or if it is an equality comparison. 
6485         // Extending a relational comparison when we're checking the sign
6486         // bit would not work.
6487         if (Cast->hasOneUse() &&
6488             (ICI.isEquality() ||
6489              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6490           uint32_t BitWidth = 
6491             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6492           APInt NewCST = AndCST->getValue();
6493           NewCST.zext(BitWidth);
6494           APInt NewCI = RHSV;
6495           NewCI.zext(BitWidth);
6496           Instruction *NewAnd = 
6497             BinaryOperator::CreateAnd(Cast->getOperand(0),
6498                                       ConstantInt::get(NewCST),LHSI->getName());
6499           InsertNewInstBefore(NewAnd, ICI);
6500           return new ICmpInst(ICI.getPredicate(), NewAnd,
6501                               ConstantInt::get(NewCI));
6502         }
6503       }
6504       
6505       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6506       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6507       // happens a LOT in code produced by the C front-end, for bitfield
6508       // access.
6509       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6510       if (Shift && !Shift->isShift())
6511         Shift = 0;
6512       
6513       ConstantInt *ShAmt;
6514       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6515       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6516       const Type *AndTy = AndCST->getType();          // Type of the and.
6517       
6518       // We can fold this as long as we can't shift unknown bits
6519       // into the mask.  This can only happen with signed shift
6520       // rights, as they sign-extend.
6521       if (ShAmt) {
6522         bool CanFold = Shift->isLogicalShift();
6523         if (!CanFold) {
6524           // To test for the bad case of the signed shr, see if any
6525           // of the bits shifted in could be tested after the mask.
6526           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6527           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6528           
6529           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6530           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6531                AndCST->getValue()) == 0)
6532             CanFold = true;
6533         }
6534         
6535         if (CanFold) {
6536           Constant *NewCst;
6537           if (Shift->getOpcode() == Instruction::Shl)
6538             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6539           else
6540             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6541           
6542           // Check to see if we are shifting out any of the bits being
6543           // compared.
6544           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6545             // If we shifted bits out, the fold is not going to work out.
6546             // As a special case, check to see if this means that the
6547             // result is always true or false now.
6548             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6549               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6550             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6551               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6552           } else {
6553             ICI.setOperand(1, NewCst);
6554             Constant *NewAndCST;
6555             if (Shift->getOpcode() == Instruction::Shl)
6556               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6557             else
6558               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6559             LHSI->setOperand(1, NewAndCST);
6560             LHSI->setOperand(0, Shift->getOperand(0));
6561             AddToWorkList(Shift); // Shift is dead.
6562             AddUsesToWorkList(ICI);
6563             return &ICI;
6564           }
6565         }
6566       }
6567       
6568       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6569       // preferable because it allows the C<<Y expression to be hoisted out
6570       // of a loop if Y is invariant and X is not.
6571       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6572           ICI.isEquality() && !Shift->isArithmeticShift() &&
6573           isa<Instruction>(Shift->getOperand(0))) {
6574         // Compute C << Y.
6575         Value *NS;
6576         if (Shift->getOpcode() == Instruction::LShr) {
6577           NS = BinaryOperator::CreateShl(AndCST, 
6578                                          Shift->getOperand(1), "tmp");
6579         } else {
6580           // Insert a logical shift.
6581           NS = BinaryOperator::CreateLShr(AndCST,
6582                                           Shift->getOperand(1), "tmp");
6583         }
6584         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6585         
6586         // Compute X & (C << Y).
6587         Instruction *NewAnd = 
6588           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6589         InsertNewInstBefore(NewAnd, ICI);
6590         
6591         ICI.setOperand(0, NewAnd);
6592         return &ICI;
6593       }
6594     }
6595     break;
6596     
6597   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6598     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6599     if (!ShAmt) break;
6600     
6601     uint32_t TypeBits = RHSV.getBitWidth();
6602     
6603     // Check that the shift amount is in range.  If not, don't perform
6604     // undefined shifts.  When the shift is visited it will be
6605     // simplified.
6606     if (ShAmt->uge(TypeBits))
6607       break;
6608     
6609     if (ICI.isEquality()) {
6610       // If we are comparing against bits always shifted out, the
6611       // comparison cannot succeed.
6612       Constant *Comp =
6613         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6614       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6615         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6616         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6617         return ReplaceInstUsesWith(ICI, Cst);
6618       }
6619       
6620       if (LHSI->hasOneUse()) {
6621         // Otherwise strength reduce the shift into an and.
6622         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6623         Constant *Mask =
6624           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6625         
6626         Instruction *AndI =
6627           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6628                                     Mask, LHSI->getName()+".mask");
6629         Value *And = InsertNewInstBefore(AndI, ICI);
6630         return new ICmpInst(ICI.getPredicate(), And,
6631                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6632       }
6633     }
6634     
6635     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6636     bool TrueIfSigned = false;
6637     if (LHSI->hasOneUse() &&
6638         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6639       // (X << 31) <s 0  --> (X&1) != 0
6640       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6641                                            (TypeBits-ShAmt->getZExtValue()-1));
6642       Instruction *AndI =
6643         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6644                                   Mask, LHSI->getName()+".mask");
6645       Value *And = InsertNewInstBefore(AndI, ICI);
6646       
6647       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6648                           And, Constant::getNullValue(And->getType()));
6649     }
6650     break;
6651   }
6652     
6653   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6654   case Instruction::AShr: {
6655     // Only handle equality comparisons of shift-by-constant.
6656     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6657     if (!ShAmt || !ICI.isEquality()) break;
6658
6659     // Check that the shift amount is in range.  If not, don't perform
6660     // undefined shifts.  When the shift is visited it will be
6661     // simplified.
6662     uint32_t TypeBits = RHSV.getBitWidth();
6663     if (ShAmt->uge(TypeBits))
6664       break;
6665     
6666     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6667       
6668     // If we are comparing against bits always shifted out, the
6669     // comparison cannot succeed.
6670     APInt Comp = RHSV << ShAmtVal;
6671     if (LHSI->getOpcode() == Instruction::LShr)
6672       Comp = Comp.lshr(ShAmtVal);
6673     else
6674       Comp = Comp.ashr(ShAmtVal);
6675     
6676     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6677       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6678       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6679       return ReplaceInstUsesWith(ICI, Cst);
6680     }
6681     
6682     // Otherwise, check to see if the bits shifted out are known to be zero.
6683     // If so, we can compare against the unshifted value:
6684     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6685     if (LHSI->hasOneUse() &&
6686         MaskedValueIsZero(LHSI->getOperand(0), 
6687                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6688       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6689                           ConstantExpr::getShl(RHS, ShAmt));
6690     }
6691       
6692     if (LHSI->hasOneUse()) {
6693       // Otherwise strength reduce the shift into an and.
6694       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6695       Constant *Mask = ConstantInt::get(Val);
6696       
6697       Instruction *AndI =
6698         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6699                                   Mask, LHSI->getName()+".mask");
6700       Value *And = InsertNewInstBefore(AndI, ICI);
6701       return new ICmpInst(ICI.getPredicate(), And,
6702                           ConstantExpr::getShl(RHS, ShAmt));
6703     }
6704     break;
6705   }
6706     
6707   case Instruction::SDiv:
6708   case Instruction::UDiv:
6709     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6710     // Fold this div into the comparison, producing a range check. 
6711     // Determine, based on the divide type, what the range is being 
6712     // checked.  If there is an overflow on the low or high side, remember 
6713     // it, otherwise compute the range [low, hi) bounding the new value.
6714     // See: InsertRangeTest above for the kinds of replacements possible.
6715     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6716       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6717                                           DivRHS))
6718         return R;
6719     break;
6720
6721   case Instruction::Add:
6722     // Fold: icmp pred (add, X, C1), C2
6723
6724     if (!ICI.isEquality()) {
6725       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6726       if (!LHSC) break;
6727       const APInt &LHSV = LHSC->getValue();
6728
6729       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6730                             .subtract(LHSV);
6731
6732       if (ICI.isSignedPredicate()) {
6733         if (CR.getLower().isSignBit()) {
6734           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6735                               ConstantInt::get(CR.getUpper()));
6736         } else if (CR.getUpper().isSignBit()) {
6737           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6738                               ConstantInt::get(CR.getLower()));
6739         }
6740       } else {
6741         if (CR.getLower().isMinValue()) {
6742           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6743                               ConstantInt::get(CR.getUpper()));
6744         } else if (CR.getUpper().isMinValue()) {
6745           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6746                               ConstantInt::get(CR.getLower()));
6747         }
6748       }
6749     }
6750     break;
6751   }
6752   
6753   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6754   if (ICI.isEquality()) {
6755     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6756     
6757     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6758     // the second operand is a constant, simplify a bit.
6759     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6760       switch (BO->getOpcode()) {
6761       case Instruction::SRem:
6762         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6763         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6764           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6765           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6766             Instruction *NewRem =
6767               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6768                                          BO->getName());
6769             InsertNewInstBefore(NewRem, ICI);
6770             return new ICmpInst(ICI.getPredicate(), NewRem, 
6771                                 Constant::getNullValue(BO->getType()));
6772           }
6773         }
6774         break;
6775       case Instruction::Add:
6776         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6777         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6778           if (BO->hasOneUse())
6779             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6780                                 Subtract(RHS, BOp1C));
6781         } else if (RHSV == 0) {
6782           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6783           // efficiently invertible, or if the add has just this one use.
6784           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6785           
6786           if (Value *NegVal = dyn_castNegVal(BOp1))
6787             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6788           else if (Value *NegVal = dyn_castNegVal(BOp0))
6789             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6790           else if (BO->hasOneUse()) {
6791             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6792             InsertNewInstBefore(Neg, ICI);
6793             Neg->takeName(BO);
6794             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6795           }
6796         }
6797         break;
6798       case Instruction::Xor:
6799         // For the xor case, we can xor two constants together, eliminating
6800         // the explicit xor.
6801         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6802           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6803                               ConstantExpr::getXor(RHS, BOC));
6804         
6805         // FALLTHROUGH
6806       case Instruction::Sub:
6807         // Replace (([sub|xor] A, B) != 0) with (A != B)
6808         if (RHSV == 0)
6809           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6810                               BO->getOperand(1));
6811         break;
6812         
6813       case Instruction::Or:
6814         // If bits are being or'd in that are not present in the constant we
6815         // are comparing against, then the comparison could never succeed!
6816         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6817           Constant *NotCI = ConstantExpr::getNot(RHS);
6818           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6819             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6820                                                              isICMP_NE));
6821         }
6822         break;
6823         
6824       case Instruction::And:
6825         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6826           // If bits are being compared against that are and'd out, then the
6827           // comparison can never succeed!
6828           if ((RHSV & ~BOC->getValue()) != 0)
6829             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6830                                                              isICMP_NE));
6831           
6832           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6833           if (RHS == BOC && RHSV.isPowerOf2())
6834             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6835                                 ICmpInst::ICMP_NE, LHSI,
6836                                 Constant::getNullValue(RHS->getType()));
6837           
6838           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6839           if (BOC->getValue().isSignBit()) {
6840             Value *X = BO->getOperand(0);
6841             Constant *Zero = Constant::getNullValue(X->getType());
6842             ICmpInst::Predicate pred = isICMP_NE ? 
6843               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6844             return new ICmpInst(pred, X, Zero);
6845           }
6846           
6847           // ((X & ~7) == 0) --> X < 8
6848           if (RHSV == 0 && isHighOnes(BOC)) {
6849             Value *X = BO->getOperand(0);
6850             Constant *NegX = ConstantExpr::getNeg(BOC);
6851             ICmpInst::Predicate pred = isICMP_NE ? 
6852               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6853             return new ICmpInst(pred, X, NegX);
6854           }
6855         }
6856       default: break;
6857       }
6858     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6859       // Handle icmp {eq|ne} <intrinsic>, intcst.
6860       if (II->getIntrinsicID() == Intrinsic::bswap) {
6861         AddToWorkList(II);
6862         ICI.setOperand(0, II->getOperand(1));
6863         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6864         return &ICI;
6865       }
6866     }
6867   }
6868   return 0;
6869 }
6870
6871 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6872 /// We only handle extending casts so far.
6873 ///
6874 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6875   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6876   Value *LHSCIOp        = LHSCI->getOperand(0);
6877   const Type *SrcTy     = LHSCIOp->getType();
6878   const Type *DestTy    = LHSCI->getType();
6879   Value *RHSCIOp;
6880
6881   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6882   // integer type is the same size as the pointer type.
6883   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6884       getTargetData().getPointerSizeInBits() == 
6885          cast<IntegerType>(DestTy)->getBitWidth()) {
6886     Value *RHSOp = 0;
6887     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6888       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6889     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6890       RHSOp = RHSC->getOperand(0);
6891       // If the pointer types don't match, insert a bitcast.
6892       if (LHSCIOp->getType() != RHSOp->getType())
6893         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6894     }
6895
6896     if (RHSOp)
6897       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6898   }
6899   
6900   // The code below only handles extension cast instructions, so far.
6901   // Enforce this.
6902   if (LHSCI->getOpcode() != Instruction::ZExt &&
6903       LHSCI->getOpcode() != Instruction::SExt)
6904     return 0;
6905
6906   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6907   bool isSignedCmp = ICI.isSignedPredicate();
6908
6909   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6910     // Not an extension from the same type?
6911     RHSCIOp = CI->getOperand(0);
6912     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6913       return 0;
6914     
6915     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6916     // and the other is a zext), then we can't handle this.
6917     if (CI->getOpcode() != LHSCI->getOpcode())
6918       return 0;
6919
6920     // Deal with equality cases early.
6921     if (ICI.isEquality())
6922       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6923
6924     // A signed comparison of sign extended values simplifies into a
6925     // signed comparison.
6926     if (isSignedCmp && isSignedExt)
6927       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6928
6929     // The other three cases all fold into an unsigned comparison.
6930     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6931   }
6932
6933   // If we aren't dealing with a constant on the RHS, exit early
6934   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6935   if (!CI)
6936     return 0;
6937
6938   // Compute the constant that would happen if we truncated to SrcTy then
6939   // reextended to DestTy.
6940   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6941   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6942
6943   // If the re-extended constant didn't change...
6944   if (Res2 == CI) {
6945     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6946     // For example, we might have:
6947     //    %A = sext short %X to uint
6948     //    %B = icmp ugt uint %A, 1330
6949     // It is incorrect to transform this into 
6950     //    %B = icmp ugt short %X, 1330 
6951     // because %A may have negative value. 
6952     //
6953     // However, we allow this when the compare is EQ/NE, because they are
6954     // signless.
6955     if (isSignedExt == isSignedCmp || ICI.isEquality())
6956       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6957     return 0;
6958   }
6959
6960   // The re-extended constant changed so the constant cannot be represented 
6961   // in the shorter type. Consequently, we cannot emit a simple comparison.
6962
6963   // First, handle some easy cases. We know the result cannot be equal at this
6964   // point so handle the ICI.isEquality() cases
6965   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6966     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6967   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6968     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6969
6970   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6971   // should have been folded away previously and not enter in here.
6972   Value *Result;
6973   if (isSignedCmp) {
6974     // We're performing a signed comparison.
6975     if (cast<ConstantInt>(CI)->getValue().isNegative())
6976       Result = ConstantInt::getFalse();          // X < (small) --> false
6977     else
6978       Result = ConstantInt::getTrue();           // X < (large) --> true
6979   } else {
6980     // We're performing an unsigned comparison.
6981     if (isSignedExt) {
6982       // We're performing an unsigned comp with a sign extended value.
6983       // This is true if the input is >= 0. [aka >s -1]
6984       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6985       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6986                                    NegOne, ICI.getName()), ICI);
6987     } else {
6988       // Unsigned extend & unsigned compare -> always true.
6989       Result = ConstantInt::getTrue();
6990     }
6991   }
6992
6993   // Finally, return the value computed.
6994   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6995       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6996     return ReplaceInstUsesWith(ICI, Result);
6997
6998   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6999           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7000          "ICmp should be folded!");
7001   if (Constant *CI = dyn_cast<Constant>(Result))
7002     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7003   return BinaryOperator::CreateNot(Result);
7004 }
7005
7006 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7007   return commonShiftTransforms(I);
7008 }
7009
7010 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7011   return commonShiftTransforms(I);
7012 }
7013
7014 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7015   if (Instruction *R = commonShiftTransforms(I))
7016     return R;
7017   
7018   Value *Op0 = I.getOperand(0);
7019   
7020   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7021   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7022     if (CSI->isAllOnesValue())
7023       return ReplaceInstUsesWith(I, CSI);
7024   
7025   // See if we can turn a signed shr into an unsigned shr.
7026   if (!isa<VectorType>(I.getType()) &&
7027       MaskedValueIsZero(Op0,
7028                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
7029     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7030   
7031   return 0;
7032 }
7033
7034 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7035   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7036   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7037
7038   // shl X, 0 == X and shr X, 0 == X
7039   // shl 0, X == 0 and shr 0, X == 0
7040   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7041       Op0 == Constant::getNullValue(Op0->getType()))
7042     return ReplaceInstUsesWith(I, Op0);
7043   
7044   if (isa<UndefValue>(Op0)) {            
7045     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7046       return ReplaceInstUsesWith(I, Op0);
7047     else                                    // undef << X -> 0, undef >>u X -> 0
7048       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7049   }
7050   if (isa<UndefValue>(Op1)) {
7051     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7052       return ReplaceInstUsesWith(I, Op0);          
7053     else                                     // X << undef, X >>u undef -> 0
7054       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7055   }
7056
7057   // Try to fold constant and into select arguments.
7058   if (isa<Constant>(Op0))
7059     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7060       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7061         return R;
7062
7063   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7064     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7065       return Res;
7066   return 0;
7067 }
7068
7069 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7070                                                BinaryOperator &I) {
7071   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7072
7073   // See if we can simplify any instructions used by the instruction whose sole 
7074   // purpose is to compute bits we don't care about.
7075   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7076   if (SimplifyDemandedInstructionBits(I))
7077     return &I;
7078   
7079   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7080   // of a signed value.
7081   //
7082   if (Op1->uge(TypeBits)) {
7083     if (I.getOpcode() != Instruction::AShr)
7084       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7085     else {
7086       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7087       return &I;
7088     }
7089   }
7090   
7091   // ((X*C1) << C2) == (X * (C1 << C2))
7092   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7093     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7094       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7095         return BinaryOperator::CreateMul(BO->getOperand(0),
7096                                          ConstantExpr::getShl(BOOp, Op1));
7097   
7098   // Try to fold constant and into select arguments.
7099   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7100     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7101       return R;
7102   if (isa<PHINode>(Op0))
7103     if (Instruction *NV = FoldOpIntoPhi(I))
7104       return NV;
7105   
7106   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7107   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7108     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7109     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7110     // place.  Don't try to do this transformation in this case.  Also, we
7111     // require that the input operand is a shift-by-constant so that we have
7112     // confidence that the shifts will get folded together.  We could do this
7113     // xform in more cases, but it is unlikely to be profitable.
7114     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7115         isa<ConstantInt>(TrOp->getOperand(1))) {
7116       // Okay, we'll do this xform.  Make the shift of shift.
7117       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7118       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7119                                                 I.getName());
7120       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7121
7122       // For logical shifts, the truncation has the effect of making the high
7123       // part of the register be zeros.  Emulate this by inserting an AND to
7124       // clear the top bits as needed.  This 'and' will usually be zapped by
7125       // other xforms later if dead.
7126       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7127       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7128       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7129       
7130       // The mask we constructed says what the trunc would do if occurring
7131       // between the shifts.  We want to know the effect *after* the second
7132       // shift.  We know that it is a logical shift by a constant, so adjust the
7133       // mask as appropriate.
7134       if (I.getOpcode() == Instruction::Shl)
7135         MaskV <<= Op1->getZExtValue();
7136       else {
7137         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7138         MaskV = MaskV.lshr(Op1->getZExtValue());
7139       }
7140
7141       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7142                                                    TI->getName());
7143       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7144
7145       // Return the value truncated to the interesting size.
7146       return new TruncInst(And, I.getType());
7147     }
7148   }
7149   
7150   if (Op0->hasOneUse()) {
7151     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7152       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7153       Value *V1, *V2;
7154       ConstantInt *CC;
7155       switch (Op0BO->getOpcode()) {
7156         default: break;
7157         case Instruction::Add:
7158         case Instruction::And:
7159         case Instruction::Or:
7160         case Instruction::Xor: {
7161           // These operators commute.
7162           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7163           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7164               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7165             Instruction *YS = BinaryOperator::CreateShl(
7166                                             Op0BO->getOperand(0), Op1,
7167                                             Op0BO->getName());
7168             InsertNewInstBefore(YS, I); // (Y << C)
7169             Instruction *X = 
7170               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7171                                      Op0BO->getOperand(1)->getName());
7172             InsertNewInstBefore(X, I);  // (X + (Y << C))
7173             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7174             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7175                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7176           }
7177           
7178           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7179           Value *Op0BOOp1 = Op0BO->getOperand(1);
7180           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7181               match(Op0BOOp1, 
7182                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7183                           m_ConstantInt(CC))) &&
7184               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7185             Instruction *YS = BinaryOperator::CreateShl(
7186                                                      Op0BO->getOperand(0), Op1,
7187                                                      Op0BO->getName());
7188             InsertNewInstBefore(YS, I); // (Y << C)
7189             Instruction *XM =
7190               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7191                                         V1->getName()+".mask");
7192             InsertNewInstBefore(XM, I); // X & (CC << C)
7193             
7194             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7195           }
7196         }
7197           
7198         // FALL THROUGH.
7199         case Instruction::Sub: {
7200           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7201           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7202               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7203             Instruction *YS = BinaryOperator::CreateShl(
7204                                                      Op0BO->getOperand(1), Op1,
7205                                                      Op0BO->getName());
7206             InsertNewInstBefore(YS, I); // (Y << C)
7207             Instruction *X =
7208               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7209                                      Op0BO->getOperand(0)->getName());
7210             InsertNewInstBefore(X, I);  // (X + (Y << C))
7211             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7212             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7213                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7214           }
7215           
7216           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7217           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7218               match(Op0BO->getOperand(0),
7219                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7220                           m_ConstantInt(CC))) && V2 == Op1 &&
7221               cast<BinaryOperator>(Op0BO->getOperand(0))
7222                   ->getOperand(0)->hasOneUse()) {
7223             Instruction *YS = BinaryOperator::CreateShl(
7224                                                      Op0BO->getOperand(1), Op1,
7225                                                      Op0BO->getName());
7226             InsertNewInstBefore(YS, I); // (Y << C)
7227             Instruction *XM =
7228               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7229                                         V1->getName()+".mask");
7230             InsertNewInstBefore(XM, I); // X & (CC << C)
7231             
7232             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7233           }
7234           
7235           break;
7236         }
7237       }
7238       
7239       
7240       // If the operand is an bitwise operator with a constant RHS, and the
7241       // shift is the only use, we can pull it out of the shift.
7242       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7243         bool isValid = true;     // Valid only for And, Or, Xor
7244         bool highBitSet = false; // Transform if high bit of constant set?
7245         
7246         switch (Op0BO->getOpcode()) {
7247           default: isValid = false; break;   // Do not perform transform!
7248           case Instruction::Add:
7249             isValid = isLeftShift;
7250             break;
7251           case Instruction::Or:
7252           case Instruction::Xor:
7253             highBitSet = false;
7254             break;
7255           case Instruction::And:
7256             highBitSet = true;
7257             break;
7258         }
7259         
7260         // If this is a signed shift right, and the high bit is modified
7261         // by the logical operation, do not perform the transformation.
7262         // The highBitSet boolean indicates the value of the high bit of
7263         // the constant which would cause it to be modified for this
7264         // operation.
7265         //
7266         if (isValid && I.getOpcode() == Instruction::AShr)
7267           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7268         
7269         if (isValid) {
7270           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7271           
7272           Instruction *NewShift =
7273             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7274           InsertNewInstBefore(NewShift, I);
7275           NewShift->takeName(Op0BO);
7276           
7277           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7278                                         NewRHS);
7279         }
7280       }
7281     }
7282   }
7283   
7284   // Find out if this is a shift of a shift by a constant.
7285   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7286   if (ShiftOp && !ShiftOp->isShift())
7287     ShiftOp = 0;
7288   
7289   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7290     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7291     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7292     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7293     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7294     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7295     Value *X = ShiftOp->getOperand(0);
7296     
7297     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7298     if (AmtSum > TypeBits)
7299       AmtSum = TypeBits;
7300     
7301     const IntegerType *Ty = cast<IntegerType>(I.getType());
7302     
7303     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7304     if (I.getOpcode() == ShiftOp->getOpcode()) {
7305       return BinaryOperator::Create(I.getOpcode(), X,
7306                                     ConstantInt::get(Ty, AmtSum));
7307     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7308                I.getOpcode() == Instruction::AShr) {
7309       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7310       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7311     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7312                I.getOpcode() == Instruction::LShr) {
7313       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7314       Instruction *Shift =
7315         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7316       InsertNewInstBefore(Shift, I);
7317
7318       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7319       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7320     }
7321     
7322     // Okay, if we get here, one shift must be left, and the other shift must be
7323     // right.  See if the amounts are equal.
7324     if (ShiftAmt1 == ShiftAmt2) {
7325       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7326       if (I.getOpcode() == Instruction::Shl) {
7327         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7328         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7329       }
7330       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7331       if (I.getOpcode() == Instruction::LShr) {
7332         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7333         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7334       }
7335       // We can simplify ((X << C) >>s C) into a trunc + sext.
7336       // NOTE: we could do this for any C, but that would make 'unusual' integer
7337       // types.  For now, just stick to ones well-supported by the code
7338       // generators.
7339       const Type *SExtType = 0;
7340       switch (Ty->getBitWidth() - ShiftAmt1) {
7341       case 1  :
7342       case 8  :
7343       case 16 :
7344       case 32 :
7345       case 64 :
7346       case 128:
7347         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7348         break;
7349       default: break;
7350       }
7351       if (SExtType) {
7352         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7353         InsertNewInstBefore(NewTrunc, I);
7354         return new SExtInst(NewTrunc, Ty);
7355       }
7356       // Otherwise, we can't handle it yet.
7357     } else if (ShiftAmt1 < ShiftAmt2) {
7358       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7359       
7360       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7361       if (I.getOpcode() == Instruction::Shl) {
7362         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7363                ShiftOp->getOpcode() == Instruction::AShr);
7364         Instruction *Shift =
7365           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7366         InsertNewInstBefore(Shift, I);
7367         
7368         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7369         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7370       }
7371       
7372       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7373       if (I.getOpcode() == Instruction::LShr) {
7374         assert(ShiftOp->getOpcode() == Instruction::Shl);
7375         Instruction *Shift =
7376           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7377         InsertNewInstBefore(Shift, I);
7378         
7379         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7380         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7381       }
7382       
7383       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7384     } else {
7385       assert(ShiftAmt2 < ShiftAmt1);
7386       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7387
7388       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7389       if (I.getOpcode() == Instruction::Shl) {
7390         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7391                ShiftOp->getOpcode() == Instruction::AShr);
7392         Instruction *Shift =
7393           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7394                                  ConstantInt::get(Ty, ShiftDiff));
7395         InsertNewInstBefore(Shift, I);
7396         
7397         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7398         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7399       }
7400       
7401       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7402       if (I.getOpcode() == Instruction::LShr) {
7403         assert(ShiftOp->getOpcode() == Instruction::Shl);
7404         Instruction *Shift =
7405           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7406         InsertNewInstBefore(Shift, I);
7407         
7408         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7409         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7410       }
7411       
7412       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7413     }
7414   }
7415   return 0;
7416 }
7417
7418
7419 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7420 /// expression.  If so, decompose it, returning some value X, such that Val is
7421 /// X*Scale+Offset.
7422 ///
7423 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7424                                         int &Offset) {
7425   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7426   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7427     Offset = CI->getZExtValue();
7428     Scale  = 0;
7429     return ConstantInt::get(Type::Int32Ty, 0);
7430   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7431     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7432       if (I->getOpcode() == Instruction::Shl) {
7433         // This is a value scaled by '1 << the shift amt'.
7434         Scale = 1U << RHS->getZExtValue();
7435         Offset = 0;
7436         return I->getOperand(0);
7437       } else if (I->getOpcode() == Instruction::Mul) {
7438         // This value is scaled by 'RHS'.
7439         Scale = RHS->getZExtValue();
7440         Offset = 0;
7441         return I->getOperand(0);
7442       } else if (I->getOpcode() == Instruction::Add) {
7443         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7444         // where C1 is divisible by C2.
7445         unsigned SubScale;
7446         Value *SubVal = 
7447           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7448         Offset += RHS->getZExtValue();
7449         Scale = SubScale;
7450         return SubVal;
7451       }
7452     }
7453   }
7454
7455   // Otherwise, we can't look past this.
7456   Scale = 1;
7457   Offset = 0;
7458   return Val;
7459 }
7460
7461
7462 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7463 /// try to eliminate the cast by moving the type information into the alloc.
7464 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7465                                                    AllocationInst &AI) {
7466   const PointerType *PTy = cast<PointerType>(CI.getType());
7467   
7468   // Remove any uses of AI that are dead.
7469   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7470   
7471   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7472     Instruction *User = cast<Instruction>(*UI++);
7473     if (isInstructionTriviallyDead(User)) {
7474       while (UI != E && *UI == User)
7475         ++UI; // If this instruction uses AI more than once, don't break UI.
7476       
7477       ++NumDeadInst;
7478       DOUT << "IC: DCE: " << *User;
7479       EraseInstFromFunction(*User);
7480     }
7481   }
7482   
7483   // Get the type really allocated and the type casted to.
7484   const Type *AllocElTy = AI.getAllocatedType();
7485   const Type *CastElTy = PTy->getElementType();
7486   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7487
7488   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7489   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7490   if (CastElTyAlign < AllocElTyAlign) return 0;
7491
7492   // If the allocation has multiple uses, only promote it if we are strictly
7493   // increasing the alignment of the resultant allocation.  If we keep it the
7494   // same, we open the door to infinite loops of various kinds.
7495   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7496
7497   uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7498   uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
7499   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7500
7501   // See if we can satisfy the modulus by pulling a scale out of the array
7502   // size argument.
7503   unsigned ArraySizeScale;
7504   int ArrayOffset;
7505   Value *NumElements = // See if the array size is a decomposable linear expr.
7506     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7507  
7508   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7509   // do the xform.
7510   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7511       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7512
7513   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7514   Value *Amt = 0;
7515   if (Scale == 1) {
7516     Amt = NumElements;
7517   } else {
7518     // If the allocation size is constant, form a constant mul expression
7519     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7520     if (isa<ConstantInt>(NumElements))
7521       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7522     // otherwise multiply the amount and the number of elements
7523     else if (Scale != 1) {
7524       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7525       Amt = InsertNewInstBefore(Tmp, AI);
7526     }
7527   }
7528   
7529   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7530     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7531     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7532     Amt = InsertNewInstBefore(Tmp, AI);
7533   }
7534   
7535   AllocationInst *New;
7536   if (isa<MallocInst>(AI))
7537     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7538   else
7539     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7540   InsertNewInstBefore(New, AI);
7541   New->takeName(&AI);
7542   
7543   // If the allocation has multiple uses, insert a cast and change all things
7544   // that used it to use the new cast.  This will also hack on CI, but it will
7545   // die soon.
7546   if (!AI.hasOneUse()) {
7547     AddUsesToWorkList(AI);
7548     // New is the allocation instruction, pointer typed. AI is the original
7549     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7550     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7551     InsertNewInstBefore(NewCast, AI);
7552     AI.replaceAllUsesWith(NewCast);
7553   }
7554   return ReplaceInstUsesWith(CI, New);
7555 }
7556
7557 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7558 /// and return it as type Ty without inserting any new casts and without
7559 /// changing the computed value.  This is used by code that tries to decide
7560 /// whether promoting or shrinking integer operations to wider or smaller types
7561 /// will allow us to eliminate a truncate or extend.
7562 ///
7563 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7564 /// extension operation if Ty is larger.
7565 ///
7566 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7567 /// should return true if trunc(V) can be computed by computing V in the smaller
7568 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7569 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7570 /// efficiently truncated.
7571 ///
7572 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7573 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7574 /// the final result.
7575 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7576                                               unsigned CastOpc,
7577                                               int &NumCastsRemoved){
7578   // We can always evaluate constants in another type.
7579   if (isa<ConstantInt>(V))
7580     return true;
7581   
7582   Instruction *I = dyn_cast<Instruction>(V);
7583   if (!I) return false;
7584   
7585   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7586   
7587   // If this is an extension or truncate, we can often eliminate it.
7588   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7589     // If this is a cast from the destination type, we can trivially eliminate
7590     // it, and this will remove a cast overall.
7591     if (I->getOperand(0)->getType() == Ty) {
7592       // If the first operand is itself a cast, and is eliminable, do not count
7593       // this as an eliminable cast.  We would prefer to eliminate those two
7594       // casts first.
7595       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7596         ++NumCastsRemoved;
7597       return true;
7598     }
7599   }
7600
7601   // We can't extend or shrink something that has multiple uses: doing so would
7602   // require duplicating the instruction in general, which isn't profitable.
7603   if (!I->hasOneUse()) return false;
7604
7605   unsigned Opc = I->getOpcode();
7606   switch (Opc) {
7607   case Instruction::Add:
7608   case Instruction::Sub:
7609   case Instruction::Mul:
7610   case Instruction::And:
7611   case Instruction::Or:
7612   case Instruction::Xor:
7613     // These operators can all arbitrarily be extended or truncated.
7614     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7615                                       NumCastsRemoved) &&
7616            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7617                                       NumCastsRemoved);
7618
7619   case Instruction::Shl:
7620     // If we are truncating the result of this SHL, and if it's a shift of a
7621     // constant amount, we can always perform a SHL in a smaller type.
7622     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7623       uint32_t BitWidth = Ty->getBitWidth();
7624       if (BitWidth < OrigTy->getBitWidth() && 
7625           CI->getLimitedValue(BitWidth) < BitWidth)
7626         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7627                                           NumCastsRemoved);
7628     }
7629     break;
7630   case Instruction::LShr:
7631     // If this is a truncate of a logical shr, we can truncate it to a smaller
7632     // lshr iff we know that the bits we would otherwise be shifting in are
7633     // already zeros.
7634     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7635       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7636       uint32_t BitWidth = Ty->getBitWidth();
7637       if (BitWidth < OrigBitWidth &&
7638           MaskedValueIsZero(I->getOperand(0),
7639             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7640           CI->getLimitedValue(BitWidth) < BitWidth) {
7641         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7642                                           NumCastsRemoved);
7643       }
7644     }
7645     break;
7646   case Instruction::ZExt:
7647   case Instruction::SExt:
7648   case Instruction::Trunc:
7649     // If this is the same kind of case as our original (e.g. zext+zext), we
7650     // can safely replace it.  Note that replacing it does not reduce the number
7651     // of casts in the input.
7652     if (Opc == CastOpc)
7653       return true;
7654
7655     // sext (zext ty1), ty2 -> zext ty2
7656     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7657       return true;
7658     break;
7659   case Instruction::Select: {
7660     SelectInst *SI = cast<SelectInst>(I);
7661     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7662                                       NumCastsRemoved) &&
7663            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7664                                       NumCastsRemoved);
7665   }
7666   case Instruction::PHI: {
7667     // We can change a phi if we can change all operands.
7668     PHINode *PN = cast<PHINode>(I);
7669     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7670       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7671                                       NumCastsRemoved))
7672         return false;
7673     return true;
7674   }
7675   default:
7676     // TODO: Can handle more cases here.
7677     break;
7678   }
7679   
7680   return false;
7681 }
7682
7683 /// EvaluateInDifferentType - Given an expression that 
7684 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7685 /// evaluate the expression.
7686 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7687                                              bool isSigned) {
7688   if (Constant *C = dyn_cast<Constant>(V))
7689     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7690
7691   // Otherwise, it must be an instruction.
7692   Instruction *I = cast<Instruction>(V);
7693   Instruction *Res = 0;
7694   unsigned Opc = I->getOpcode();
7695   switch (Opc) {
7696   case Instruction::Add:
7697   case Instruction::Sub:
7698   case Instruction::Mul:
7699   case Instruction::And:
7700   case Instruction::Or:
7701   case Instruction::Xor:
7702   case Instruction::AShr:
7703   case Instruction::LShr:
7704   case Instruction::Shl: {
7705     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7706     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7707     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7708     break;
7709   }    
7710   case Instruction::Trunc:
7711   case Instruction::ZExt:
7712   case Instruction::SExt:
7713     // If the source type of the cast is the type we're trying for then we can
7714     // just return the source.  There's no need to insert it because it is not
7715     // new.
7716     if (I->getOperand(0)->getType() == Ty)
7717       return I->getOperand(0);
7718     
7719     // Otherwise, must be the same type of cast, so just reinsert a new one.
7720     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7721                            Ty);
7722     break;
7723   case Instruction::Select: {
7724     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7725     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7726     Res = SelectInst::Create(I->getOperand(0), True, False);
7727     break;
7728   }
7729   case Instruction::PHI: {
7730     PHINode *OPN = cast<PHINode>(I);
7731     PHINode *NPN = PHINode::Create(Ty);
7732     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7733       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7734       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7735     }
7736     Res = NPN;
7737     break;
7738   }
7739   default: 
7740     // TODO: Can handle more cases here.
7741     assert(0 && "Unreachable!");
7742     break;
7743   }
7744   
7745   Res->takeName(I);
7746   return InsertNewInstBefore(Res, *I);
7747 }
7748
7749 /// @brief Implement the transforms common to all CastInst visitors.
7750 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7751   Value *Src = CI.getOperand(0);
7752
7753   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7754   // eliminate it now.
7755   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7756     if (Instruction::CastOps opc = 
7757         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7758       // The first cast (CSrc) is eliminable so we need to fix up or replace
7759       // the second cast (CI). CSrc will then have a good chance of being dead.
7760       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7761     }
7762   }
7763
7764   // If we are casting a select then fold the cast into the select
7765   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7766     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7767       return NV;
7768
7769   // If we are casting a PHI then fold the cast into the PHI
7770   if (isa<PHINode>(Src))
7771     if (Instruction *NV = FoldOpIntoPhi(CI))
7772       return NV;
7773   
7774   return 0;
7775 }
7776
7777 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7778 /// or not there is a sequence of GEP indices into the type that will land us at
7779 /// the specified offset.  If so, fill them into NewIndices and return the
7780 /// resultant element type, otherwise return null.
7781 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7782                                        SmallVectorImpl<Value*> &NewIndices,
7783                                        const TargetData *TD) {
7784   if (!Ty->isSized()) return 0;
7785   
7786   // Start with the index over the outer type.  Note that the type size
7787   // might be zero (even if the offset isn't zero) if the indexed type
7788   // is something like [0 x {int, int}]
7789   const Type *IntPtrTy = TD->getIntPtrType();
7790   int64_t FirstIdx = 0;
7791   if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
7792     FirstIdx = Offset/TySize;
7793     Offset -= FirstIdx*TySize;
7794     
7795     // Handle hosts where % returns negative instead of values [0..TySize).
7796     if (Offset < 0) {
7797       --FirstIdx;
7798       Offset += TySize;
7799       assert(Offset >= 0);
7800     }
7801     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7802   }
7803   
7804   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7805     
7806   // Index into the types.  If we fail, set OrigBase to null.
7807   while (Offset) {
7808     // Indexing into tail padding between struct/array elements.
7809     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
7810       return 0;
7811     
7812     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7813       const StructLayout *SL = TD->getStructLayout(STy);
7814       assert(Offset < (int64_t)SL->getSizeInBytes() &&
7815              "Offset must stay within the indexed type");
7816       
7817       unsigned Elt = SL->getElementContainingOffset(Offset);
7818       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7819       
7820       Offset -= SL->getElementOffset(Elt);
7821       Ty = STy->getElementType(Elt);
7822     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7823       uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
7824       assert(EltSize && "Cannot index into a zero-sized array");
7825       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7826       Offset %= EltSize;
7827       Ty = AT->getElementType();
7828     } else {
7829       // Otherwise, we can't index into the middle of this atomic type, bail.
7830       return 0;
7831     }
7832   }
7833   
7834   return Ty;
7835 }
7836
7837 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7838 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7839   Value *Src = CI.getOperand(0);
7840   
7841   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7842     // If casting the result of a getelementptr instruction with no offset, turn
7843     // this into a cast of the original pointer!
7844     if (GEP->hasAllZeroIndices()) {
7845       // Changing the cast operand is usually not a good idea but it is safe
7846       // here because the pointer operand is being replaced with another 
7847       // pointer operand so the opcode doesn't need to change.
7848       AddToWorkList(GEP);
7849       CI.setOperand(0, GEP->getOperand(0));
7850       return &CI;
7851     }
7852     
7853     // If the GEP has a single use, and the base pointer is a bitcast, and the
7854     // GEP computes a constant offset, see if we can convert these three
7855     // instructions into fewer.  This typically happens with unions and other
7856     // non-type-safe code.
7857     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7858       if (GEP->hasAllConstantIndices()) {
7859         // We are guaranteed to get a constant from EmitGEPOffset.
7860         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7861         int64_t Offset = OffsetV->getSExtValue();
7862         
7863         // Get the base pointer input of the bitcast, and the type it points to.
7864         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7865         const Type *GEPIdxTy =
7866           cast<PointerType>(OrigBase->getType())->getElementType();
7867         SmallVector<Value*, 8> NewIndices;
7868         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7869           // If we were able to index down into an element, create the GEP
7870           // and bitcast the result.  This eliminates one bitcast, potentially
7871           // two.
7872           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7873                                                         NewIndices.begin(),
7874                                                         NewIndices.end(), "");
7875           InsertNewInstBefore(NGEP, CI);
7876           NGEP->takeName(GEP);
7877           
7878           if (isa<BitCastInst>(CI))
7879             return new BitCastInst(NGEP, CI.getType());
7880           assert(isa<PtrToIntInst>(CI));
7881           return new PtrToIntInst(NGEP, CI.getType());
7882         }
7883       }      
7884     }
7885   }
7886     
7887   return commonCastTransforms(CI);
7888 }
7889
7890
7891 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7892 /// integer types. This function implements the common transforms for all those
7893 /// cases.
7894 /// @brief Implement the transforms common to CastInst with integer operands
7895 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7896   if (Instruction *Result = commonCastTransforms(CI))
7897     return Result;
7898
7899   Value *Src = CI.getOperand(0);
7900   const Type *SrcTy = Src->getType();
7901   const Type *DestTy = CI.getType();
7902   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7903   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7904
7905   // See if we can simplify any instructions used by the LHS whose sole 
7906   // purpose is to compute bits we don't care about.
7907   if (SimplifyDemandedInstructionBits(CI))
7908     return &CI;
7909
7910   // If the source isn't an instruction or has more than one use then we
7911   // can't do anything more. 
7912   Instruction *SrcI = dyn_cast<Instruction>(Src);
7913   if (!SrcI || !Src->hasOneUse())
7914     return 0;
7915
7916   // Attempt to propagate the cast into the instruction for int->int casts.
7917   int NumCastsRemoved = 0;
7918   if (!isa<BitCastInst>(CI) &&
7919       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7920                                  CI.getOpcode(), NumCastsRemoved)) {
7921     // If this cast is a truncate, evaluting in a different type always
7922     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7923     // we need to do an AND to maintain the clear top-part of the computation,
7924     // so we require that the input have eliminated at least one cast.  If this
7925     // is a sign extension, we insert two new casts (to do the extension) so we
7926     // require that two casts have been eliminated.
7927     bool DoXForm = false;
7928     bool JustReplace = false;
7929     switch (CI.getOpcode()) {
7930     default:
7931       // All the others use floating point so we shouldn't actually 
7932       // get here because of the check above.
7933       assert(0 && "Unknown cast type");
7934     case Instruction::Trunc:
7935       DoXForm = true;
7936       break;
7937     case Instruction::ZExt: {
7938       DoXForm = NumCastsRemoved >= 1;
7939       if (!DoXForm && 0) {
7940         // If it's unnecessary to issue an AND to clear the high bits, it's
7941         // always profitable to do this xform.
7942         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
7943         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7944         if (MaskedValueIsZero(TryRes, Mask))
7945           return ReplaceInstUsesWith(CI, TryRes);
7946         
7947         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7948           if (TryI->use_empty())
7949             EraseInstFromFunction(*TryI);
7950       }
7951       break;
7952     }
7953     case Instruction::SExt: {
7954       DoXForm = NumCastsRemoved >= 2;
7955       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
7956         // If we do not have to emit the truncate + sext pair, then it's always
7957         // profitable to do this xform.
7958         //
7959         // It's not safe to eliminate the trunc + sext pair if one of the
7960         // eliminated cast is a truncate. e.g.
7961         // t2 = trunc i32 t1 to i16
7962         // t3 = sext i16 t2 to i32
7963         // !=
7964         // i32 t1
7965         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
7966         unsigned NumSignBits = ComputeNumSignBits(TryRes);
7967         if (NumSignBits > (DestBitSize - SrcBitSize))
7968           return ReplaceInstUsesWith(CI, TryRes);
7969         
7970         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7971           if (TryI->use_empty())
7972             EraseInstFromFunction(*TryI);
7973       }
7974       break;
7975     }
7976     }
7977     
7978     if (DoXForm) {
7979       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
7980            << " cast: " << CI;
7981       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7982                                            CI.getOpcode() == Instruction::SExt);
7983       if (JustReplace)
7984         // Just replace this cast with the result.
7985         return ReplaceInstUsesWith(CI, Res);
7986
7987       assert(Res->getType() == DestTy);
7988       switch (CI.getOpcode()) {
7989       default: assert(0 && "Unknown cast type!");
7990       case Instruction::Trunc:
7991       case Instruction::BitCast:
7992         // Just replace this cast with the result.
7993         return ReplaceInstUsesWith(CI, Res);
7994       case Instruction::ZExt: {
7995         assert(SrcBitSize < DestBitSize && "Not a zext?");
7996
7997         // If the high bits are already zero, just replace this cast with the
7998         // result.
7999         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8000         if (MaskedValueIsZero(Res, Mask))
8001           return ReplaceInstUsesWith(CI, Res);
8002
8003         // We need to emit an AND to clear the high bits.
8004         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8005                                                             SrcBitSize));
8006         return BinaryOperator::CreateAnd(Res, C);
8007       }
8008       case Instruction::SExt: {
8009         // If the high bits are already filled with sign bit, just replace this
8010         // cast with the result.
8011         unsigned NumSignBits = ComputeNumSignBits(Res);
8012         if (NumSignBits > (DestBitSize - SrcBitSize))
8013           return ReplaceInstUsesWith(CI, Res);
8014
8015         // We need to emit a cast to truncate, then a cast to sext.
8016         return CastInst::Create(Instruction::SExt,
8017             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8018                              CI), DestTy);
8019       }
8020       }
8021     }
8022   }
8023   
8024   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8025   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8026
8027   switch (SrcI->getOpcode()) {
8028   case Instruction::Add:
8029   case Instruction::Mul:
8030   case Instruction::And:
8031   case Instruction::Or:
8032   case Instruction::Xor:
8033     // If we are discarding information, rewrite.
8034     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8035       // Don't insert two casts if they cannot be eliminated.  We allow 
8036       // two casts to be inserted if the sizes are the same.  This could 
8037       // only be converting signedness, which is a noop.
8038       if (DestBitSize == SrcBitSize || 
8039           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8040           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8041         Instruction::CastOps opcode = CI.getOpcode();
8042         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8043         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8044         return BinaryOperator::Create(
8045             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8046       }
8047     }
8048
8049     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8050     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8051         SrcI->getOpcode() == Instruction::Xor &&
8052         Op1 == ConstantInt::getTrue() &&
8053         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8054       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8055       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8056     }
8057     break;
8058   case Instruction::SDiv:
8059   case Instruction::UDiv:
8060   case Instruction::SRem:
8061   case Instruction::URem:
8062     // If we are just changing the sign, rewrite.
8063     if (DestBitSize == SrcBitSize) {
8064       // Don't insert two casts if they cannot be eliminated.  We allow 
8065       // two casts to be inserted if the sizes are the same.  This could 
8066       // only be converting signedness, which is a noop.
8067       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8068           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8069         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8070                                        Op0, DestTy, *SrcI);
8071         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8072                                        Op1, DestTy, *SrcI);
8073         return BinaryOperator::Create(
8074           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8075       }
8076     }
8077     break;
8078
8079   case Instruction::Shl:
8080     // Allow changing the sign of the source operand.  Do not allow 
8081     // changing the size of the shift, UNLESS the shift amount is a 
8082     // constant.  We must not change variable sized shifts to a smaller 
8083     // size, because it is undefined to shift more bits out than exist 
8084     // in the value.
8085     if (DestBitSize == SrcBitSize ||
8086         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8087       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8088           Instruction::BitCast : Instruction::Trunc);
8089       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8090       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8091       return BinaryOperator::CreateShl(Op0c, Op1c);
8092     }
8093     break;
8094   case Instruction::AShr:
8095     // If this is a signed shr, and if all bits shifted in are about to be
8096     // truncated off, turn it into an unsigned shr to allow greater
8097     // simplifications.
8098     if (DestBitSize < SrcBitSize &&
8099         isa<ConstantInt>(Op1)) {
8100       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8101       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8102         // Insert the new logical shift right.
8103         return BinaryOperator::CreateLShr(Op0, Op1);
8104       }
8105     }
8106     break;
8107   }
8108   return 0;
8109 }
8110
8111 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8112   if (Instruction *Result = commonIntCastTransforms(CI))
8113     return Result;
8114   
8115   Value *Src = CI.getOperand(0);
8116   const Type *Ty = CI.getType();
8117   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8118   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8119   
8120   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8121     switch (SrcI->getOpcode()) {
8122     default: break;
8123     case Instruction::LShr:
8124       // We can shrink lshr to something smaller if we know the bits shifted in
8125       // are already zeros.
8126       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
8127         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8128         
8129         // Get a mask for the bits shifting in.
8130         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8131         Value* SrcIOp0 = SrcI->getOperand(0);
8132         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
8133           if (ShAmt >= DestBitWidth)        // All zeros.
8134             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8135
8136           // Okay, we can shrink this.  Truncate the input, then return a new
8137           // shift.
8138           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8139           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8140                                        Ty, CI);
8141           return BinaryOperator::CreateLShr(V1, V2);
8142         }
8143       } else {     // This is a variable shr.
8144         
8145         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
8146         // more LLVM instructions, but allows '1 << Y' to be hoisted if
8147         // loop-invariant and CSE'd.
8148         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
8149           Value *One = ConstantInt::get(SrcI->getType(), 1);
8150
8151           Value *V = InsertNewInstBefore(
8152               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
8153                                      "tmp"), CI);
8154           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
8155                                                             SrcI->getOperand(0),
8156                                                             "tmp"), CI);
8157           Value *Zero = Constant::getNullValue(V->getType());
8158           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
8159         }
8160       }
8161       break;
8162     }
8163   }
8164   
8165   return 0;
8166 }
8167
8168 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8169 /// in order to eliminate the icmp.
8170 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8171                                              bool DoXform) {
8172   // If we are just checking for a icmp eq of a single bit and zext'ing it
8173   // to an integer, then shift the bit to the appropriate place and then
8174   // cast to integer to avoid the comparison.
8175   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8176     const APInt &Op1CV = Op1C->getValue();
8177       
8178     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8179     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8180     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8181         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8182       if (!DoXform) return ICI;
8183
8184       Value *In = ICI->getOperand(0);
8185       Value *Sh = ConstantInt::get(In->getType(),
8186                                    In->getType()->getPrimitiveSizeInBits()-1);
8187       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8188                                                         In->getName()+".lobit"),
8189                                CI);
8190       if (In->getType() != CI.getType())
8191         In = CastInst::CreateIntegerCast(In, CI.getType(),
8192                                          false/*ZExt*/, "tmp", &CI);
8193
8194       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8195         Constant *One = ConstantInt::get(In->getType(), 1);
8196         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8197                                                          In->getName()+".not"),
8198                                  CI);
8199       }
8200
8201       return ReplaceInstUsesWith(CI, In);
8202     }
8203       
8204       
8205       
8206     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8207     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8208     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8209     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8210     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8211     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8212     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8213     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8214     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8215         // This only works for EQ and NE
8216         ICI->isEquality()) {
8217       // If Op1C some other power of two, convert:
8218       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8219       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8220       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8221       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8222         
8223       APInt KnownZeroMask(~KnownZero);
8224       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8225         if (!DoXform) return ICI;
8226
8227         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8228         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8229           // (X&4) == 2 --> false
8230           // (X&4) != 2 --> true
8231           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8232           Res = ConstantExpr::getZExt(Res, CI.getType());
8233           return ReplaceInstUsesWith(CI, Res);
8234         }
8235           
8236         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8237         Value *In = ICI->getOperand(0);
8238         if (ShiftAmt) {
8239           // Perform a logical shr by shiftamt.
8240           // Insert the shift to put the result in the low bit.
8241           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8242                                   ConstantInt::get(In->getType(), ShiftAmt),
8243                                                    In->getName()+".lobit"), CI);
8244         }
8245           
8246         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8247           Constant *One = ConstantInt::get(In->getType(), 1);
8248           In = BinaryOperator::CreateXor(In, One, "tmp");
8249           InsertNewInstBefore(cast<Instruction>(In), CI);
8250         }
8251           
8252         if (CI.getType() == In->getType())
8253           return ReplaceInstUsesWith(CI, In);
8254         else
8255           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8256       }
8257     }
8258   }
8259
8260   return 0;
8261 }
8262
8263 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8264   // If one of the common conversion will work ..
8265   if (Instruction *Result = commonIntCastTransforms(CI))
8266     return Result;
8267
8268   Value *Src = CI.getOperand(0);
8269
8270   // If this is a cast of a cast
8271   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8272     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8273     // types and if the sizes are just right we can convert this into a logical
8274     // 'and' which will be much cheaper than the pair of casts.
8275     if (isa<TruncInst>(CSrc)) {
8276       // Get the sizes of the types involved
8277       Value *A = CSrc->getOperand(0);
8278       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8279       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8280       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8281       // If we're actually extending zero bits and the trunc is a no-op
8282       if (MidSize < DstSize && SrcSize == DstSize) {
8283         // Replace both of the casts with an And of the type mask.
8284         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8285         Constant *AndConst = ConstantInt::get(AndValue);
8286         Instruction *And = 
8287           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8288         // Unfortunately, if the type changed, we need to cast it back.
8289         if (And->getType() != CI.getType()) {
8290           And->setName(CSrc->getName()+".mask");
8291           InsertNewInstBefore(And, CI);
8292           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8293         }
8294         return And;
8295       }
8296     }
8297   }
8298
8299   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8300     return transformZExtICmp(ICI, CI);
8301
8302   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8303   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8304     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8305     // of the (zext icmp) will be transformed.
8306     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8307     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8308     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8309         (transformZExtICmp(LHS, CI, false) ||
8310          transformZExtICmp(RHS, CI, false))) {
8311       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8312       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8313       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8314     }
8315   }
8316
8317   return 0;
8318 }
8319
8320 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8321   if (Instruction *I = commonIntCastTransforms(CI))
8322     return I;
8323   
8324   Value *Src = CI.getOperand(0);
8325   
8326   // Canonicalize sign-extend from i1 to a select.
8327   if (Src->getType() == Type::Int1Ty)
8328     return SelectInst::Create(Src,
8329                               ConstantInt::getAllOnesValue(CI.getType()),
8330                               Constant::getNullValue(CI.getType()));
8331
8332   // See if the value being truncated is already sign extended.  If so, just
8333   // eliminate the trunc/sext pair.
8334   if (getOpcode(Src) == Instruction::Trunc) {
8335     Value *Op = cast<User>(Src)->getOperand(0);
8336     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8337     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8338     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8339     unsigned NumSignBits = ComputeNumSignBits(Op);
8340
8341     if (OpBits == DestBits) {
8342       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8343       // bits, it is already ready.
8344       if (NumSignBits > DestBits-MidBits)
8345         return ReplaceInstUsesWith(CI, Op);
8346     } else if (OpBits < DestBits) {
8347       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8348       // bits, just sext from i32.
8349       if (NumSignBits > OpBits-MidBits)
8350         return new SExtInst(Op, CI.getType(), "tmp");
8351     } else {
8352       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8353       // bits, just truncate to i32.
8354       if (NumSignBits > OpBits-MidBits)
8355         return new TruncInst(Op, CI.getType(), "tmp");
8356     }
8357   }
8358
8359   // If the input is a shl/ashr pair of a same constant, then this is a sign
8360   // extension from a smaller value.  If we could trust arbitrary bitwidth
8361   // integers, we could turn this into a truncate to the smaller bit and then
8362   // use a sext for the whole extension.  Since we don't, look deeper and check
8363   // for a truncate.  If the source and dest are the same type, eliminate the
8364   // trunc and extend and just do shifts.  For example, turn:
8365   //   %a = trunc i32 %i to i8
8366   //   %b = shl i8 %a, 6
8367   //   %c = ashr i8 %b, 6
8368   //   %d = sext i8 %c to i32
8369   // into:
8370   //   %a = shl i32 %i, 30
8371   //   %d = ashr i32 %a, 30
8372   Value *A = 0;
8373   ConstantInt *BA = 0, *CA = 0;
8374   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8375                         m_ConstantInt(CA))) &&
8376       BA == CA && isa<TruncInst>(A)) {
8377     Value *I = cast<TruncInst>(A)->getOperand(0);
8378     if (I->getType() == CI.getType()) {
8379       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8380       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8381       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8382       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8383       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8384                                                         CI.getName()), CI);
8385       return BinaryOperator::CreateAShr(I, ShAmtV);
8386     }
8387   }
8388   
8389   return 0;
8390 }
8391
8392 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8393 /// in the specified FP type without changing its value.
8394 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8395   bool losesInfo;
8396   APFloat F = CFP->getValueAPF();
8397   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8398   if (!losesInfo)
8399     return ConstantFP::get(F);
8400   return 0;
8401 }
8402
8403 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8404 /// through it until we get the source value.
8405 static Value *LookThroughFPExtensions(Value *V) {
8406   if (Instruction *I = dyn_cast<Instruction>(V))
8407     if (I->getOpcode() == Instruction::FPExt)
8408       return LookThroughFPExtensions(I->getOperand(0));
8409   
8410   // If this value is a constant, return the constant in the smallest FP type
8411   // that can accurately represent it.  This allows us to turn
8412   // (float)((double)X+2.0) into x+2.0f.
8413   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8414     if (CFP->getType() == Type::PPC_FP128Ty)
8415       return V;  // No constant folding of this.
8416     // See if the value can be truncated to float and then reextended.
8417     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8418       return V;
8419     if (CFP->getType() == Type::DoubleTy)
8420       return V;  // Won't shrink.
8421     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8422       return V;
8423     // Don't try to shrink to various long double types.
8424   }
8425   
8426   return V;
8427 }
8428
8429 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8430   if (Instruction *I = commonCastTransforms(CI))
8431     return I;
8432   
8433   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8434   // smaller than the destination type, we can eliminate the truncate by doing
8435   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8436   // many builtins (sqrt, etc).
8437   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8438   if (OpI && OpI->hasOneUse()) {
8439     switch (OpI->getOpcode()) {
8440     default: break;
8441     case Instruction::Add:
8442     case Instruction::Sub:
8443     case Instruction::Mul:
8444     case Instruction::FDiv:
8445     case Instruction::FRem:
8446       const Type *SrcTy = OpI->getType();
8447       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8448       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8449       if (LHSTrunc->getType() != SrcTy && 
8450           RHSTrunc->getType() != SrcTy) {
8451         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8452         // If the source types were both smaller than the destination type of
8453         // the cast, do this xform.
8454         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8455             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8456           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8457                                       CI.getType(), CI);
8458           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8459                                       CI.getType(), CI);
8460           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8461         }
8462       }
8463       break;  
8464     }
8465   }
8466   return 0;
8467 }
8468
8469 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8470   return commonCastTransforms(CI);
8471 }
8472
8473 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8474   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8475   if (OpI == 0)
8476     return commonCastTransforms(FI);
8477
8478   // fptoui(uitofp(X)) --> X
8479   // fptoui(sitofp(X)) --> X
8480   // This is safe if the intermediate type has enough bits in its mantissa to
8481   // accurately represent all values of X.  For example, do not do this with
8482   // i64->float->i64.  This is also safe for sitofp case, because any negative
8483   // 'X' value would cause an undefined result for the fptoui. 
8484   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8485       OpI->getOperand(0)->getType() == FI.getType() &&
8486       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8487                     OpI->getType()->getFPMantissaWidth())
8488     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8489
8490   return commonCastTransforms(FI);
8491 }
8492
8493 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8494   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8495   if (OpI == 0)
8496     return commonCastTransforms(FI);
8497   
8498   // fptosi(sitofp(X)) --> X
8499   // fptosi(uitofp(X)) --> X
8500   // This is safe if the intermediate type has enough bits in its mantissa to
8501   // accurately represent all values of X.  For example, do not do this with
8502   // i64->float->i64.  This is also safe for sitofp case, because any negative
8503   // 'X' value would cause an undefined result for the fptoui. 
8504   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8505       OpI->getOperand(0)->getType() == FI.getType() &&
8506       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8507                     OpI->getType()->getFPMantissaWidth())
8508     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8509   
8510   return commonCastTransforms(FI);
8511 }
8512
8513 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8514   return commonCastTransforms(CI);
8515 }
8516
8517 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8518   return commonCastTransforms(CI);
8519 }
8520
8521 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8522   return commonPointerCastTransforms(CI);
8523 }
8524
8525 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8526   if (Instruction *I = commonCastTransforms(CI))
8527     return I;
8528   
8529   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8530   if (!DestPointee->isSized()) return 0;
8531
8532   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8533   ConstantInt *Cst;
8534   Value *X;
8535   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8536                                     m_ConstantInt(Cst)))) {
8537     // If the source and destination operands have the same type, see if this
8538     // is a single-index GEP.
8539     if (X->getType() == CI.getType()) {
8540       // Get the size of the pointee type.
8541       uint64_t Size = TD->getTypePaddedSize(DestPointee);
8542
8543       // Convert the constant to intptr type.
8544       APInt Offset = Cst->getValue();
8545       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8546
8547       // If Offset is evenly divisible by Size, we can do this xform.
8548       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8549         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8550         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8551       }
8552     }
8553     // TODO: Could handle other cases, e.g. where add is indexing into field of
8554     // struct etc.
8555   } else if (CI.getOperand(0)->hasOneUse() &&
8556              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8557     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8558     // "inttoptr+GEP" instead of "add+intptr".
8559     
8560     // Get the size of the pointee type.
8561     uint64_t Size = TD->getTypePaddedSize(DestPointee);
8562     
8563     // Convert the constant to intptr type.
8564     APInt Offset = Cst->getValue();
8565     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8566     
8567     // If Offset is evenly divisible by Size, we can do this xform.
8568     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8569       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8570       
8571       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8572                                                             "tmp"), CI);
8573       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8574     }
8575   }
8576   return 0;
8577 }
8578
8579 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8580   // If the operands are integer typed then apply the integer transforms,
8581   // otherwise just apply the common ones.
8582   Value *Src = CI.getOperand(0);
8583   const Type *SrcTy = Src->getType();
8584   const Type *DestTy = CI.getType();
8585
8586   if (SrcTy->isInteger() && DestTy->isInteger()) {
8587     if (Instruction *Result = commonIntCastTransforms(CI))
8588       return Result;
8589   } else if (isa<PointerType>(SrcTy)) {
8590     if (Instruction *I = commonPointerCastTransforms(CI))
8591       return I;
8592   } else {
8593     if (Instruction *Result = commonCastTransforms(CI))
8594       return Result;
8595   }
8596
8597
8598   // Get rid of casts from one type to the same type. These are useless and can
8599   // be replaced by the operand.
8600   if (DestTy == Src->getType())
8601     return ReplaceInstUsesWith(CI, Src);
8602
8603   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8604     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8605     const Type *DstElTy = DstPTy->getElementType();
8606     const Type *SrcElTy = SrcPTy->getElementType();
8607     
8608     // If the address spaces don't match, don't eliminate the bitcast, which is
8609     // required for changing types.
8610     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8611       return 0;
8612     
8613     // If we are casting a malloc or alloca to a pointer to a type of the same
8614     // size, rewrite the allocation instruction to allocate the "right" type.
8615     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8616       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8617         return V;
8618     
8619     // If the source and destination are pointers, and this cast is equivalent
8620     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8621     // This can enhance SROA and other transforms that want type-safe pointers.
8622     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8623     unsigned NumZeros = 0;
8624     while (SrcElTy != DstElTy && 
8625            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8626            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8627       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8628       ++NumZeros;
8629     }
8630
8631     // If we found a path from the src to dest, create the getelementptr now.
8632     if (SrcElTy == DstElTy) {
8633       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8634       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8635                                        ((Instruction*) NULL));
8636     }
8637   }
8638
8639   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8640     if (SVI->hasOneUse()) {
8641       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8642       // a bitconvert to a vector with the same # elts.
8643       if (isa<VectorType>(DestTy) && 
8644           cast<VectorType>(DestTy)->getNumElements() ==
8645                 SVI->getType()->getNumElements() &&
8646           SVI->getType()->getNumElements() ==
8647             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8648         CastInst *Tmp;
8649         // If either of the operands is a cast from CI.getType(), then
8650         // evaluating the shuffle in the casted destination's type will allow
8651         // us to eliminate at least one cast.
8652         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8653              Tmp->getOperand(0)->getType() == DestTy) ||
8654             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8655              Tmp->getOperand(0)->getType() == DestTy)) {
8656           Value *LHS = InsertCastBefore(Instruction::BitCast,
8657                                         SVI->getOperand(0), DestTy, CI);
8658           Value *RHS = InsertCastBefore(Instruction::BitCast,
8659                                         SVI->getOperand(1), DestTy, CI);
8660           // Return a new shuffle vector.  Use the same element ID's, as we
8661           // know the vector types match #elts.
8662           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8663         }
8664       }
8665     }
8666   }
8667   return 0;
8668 }
8669
8670 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8671 ///   %C = or %A, %B
8672 ///   %D = select %cond, %C, %A
8673 /// into:
8674 ///   %C = select %cond, %B, 0
8675 ///   %D = or %A, %C
8676 ///
8677 /// Assuming that the specified instruction is an operand to the select, return
8678 /// a bitmask indicating which operands of this instruction are foldable if they
8679 /// equal the other incoming value of the select.
8680 ///
8681 static unsigned GetSelectFoldableOperands(Instruction *I) {
8682   switch (I->getOpcode()) {
8683   case Instruction::Add:
8684   case Instruction::Mul:
8685   case Instruction::And:
8686   case Instruction::Or:
8687   case Instruction::Xor:
8688     return 3;              // Can fold through either operand.
8689   case Instruction::Sub:   // Can only fold on the amount subtracted.
8690   case Instruction::Shl:   // Can only fold on the shift amount.
8691   case Instruction::LShr:
8692   case Instruction::AShr:
8693     return 1;
8694   default:
8695     return 0;              // Cannot fold
8696   }
8697 }
8698
8699 /// GetSelectFoldableConstant - For the same transformation as the previous
8700 /// function, return the identity constant that goes into the select.
8701 static Constant *GetSelectFoldableConstant(Instruction *I) {
8702   switch (I->getOpcode()) {
8703   default: assert(0 && "This cannot happen!"); abort();
8704   case Instruction::Add:
8705   case Instruction::Sub:
8706   case Instruction::Or:
8707   case Instruction::Xor:
8708   case Instruction::Shl:
8709   case Instruction::LShr:
8710   case Instruction::AShr:
8711     return Constant::getNullValue(I->getType());
8712   case Instruction::And:
8713     return Constant::getAllOnesValue(I->getType());
8714   case Instruction::Mul:
8715     return ConstantInt::get(I->getType(), 1);
8716   }
8717 }
8718
8719 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8720 /// have the same opcode and only one use each.  Try to simplify this.
8721 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8722                                           Instruction *FI) {
8723   if (TI->getNumOperands() == 1) {
8724     // If this is a non-volatile load or a cast from the same type,
8725     // merge.
8726     if (TI->isCast()) {
8727       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8728         return 0;
8729     } else {
8730       return 0;  // unknown unary op.
8731     }
8732
8733     // Fold this by inserting a select from the input values.
8734     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8735                                            FI->getOperand(0), SI.getName()+".v");
8736     InsertNewInstBefore(NewSI, SI);
8737     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8738                             TI->getType());
8739   }
8740
8741   // Only handle binary operators here.
8742   if (!isa<BinaryOperator>(TI))
8743     return 0;
8744
8745   // Figure out if the operations have any operands in common.
8746   Value *MatchOp, *OtherOpT, *OtherOpF;
8747   bool MatchIsOpZero;
8748   if (TI->getOperand(0) == FI->getOperand(0)) {
8749     MatchOp  = TI->getOperand(0);
8750     OtherOpT = TI->getOperand(1);
8751     OtherOpF = FI->getOperand(1);
8752     MatchIsOpZero = true;
8753   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8754     MatchOp  = TI->getOperand(1);
8755     OtherOpT = TI->getOperand(0);
8756     OtherOpF = FI->getOperand(0);
8757     MatchIsOpZero = false;
8758   } else if (!TI->isCommutative()) {
8759     return 0;
8760   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8761     MatchOp  = TI->getOperand(0);
8762     OtherOpT = TI->getOperand(1);
8763     OtherOpF = FI->getOperand(0);
8764     MatchIsOpZero = true;
8765   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8766     MatchOp  = TI->getOperand(1);
8767     OtherOpT = TI->getOperand(0);
8768     OtherOpF = FI->getOperand(1);
8769     MatchIsOpZero = true;
8770   } else {
8771     return 0;
8772   }
8773
8774   // If we reach here, they do have operations in common.
8775   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8776                                          OtherOpF, SI.getName()+".v");
8777   InsertNewInstBefore(NewSI, SI);
8778
8779   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8780     if (MatchIsOpZero)
8781       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8782     else
8783       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8784   }
8785   assert(0 && "Shouldn't get here");
8786   return 0;
8787 }
8788
8789 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8790 /// ICmpInst as its first operand.
8791 ///
8792 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8793                                                    ICmpInst *ICI) {
8794   bool Changed = false;
8795   ICmpInst::Predicate Pred = ICI->getPredicate();
8796   Value *CmpLHS = ICI->getOperand(0);
8797   Value *CmpRHS = ICI->getOperand(1);
8798   Value *TrueVal = SI.getTrueValue();
8799   Value *FalseVal = SI.getFalseValue();
8800
8801   // Check cases where the comparison is with a constant that
8802   // can be adjusted to fit the min/max idiom. We may edit ICI in
8803   // place here, so make sure the select is the only user.
8804   if (ICI->hasOneUse())
8805     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8806       switch (Pred) {
8807       default: break;
8808       case ICmpInst::ICMP_ULT:
8809       case ICmpInst::ICMP_SLT: {
8810         // X < MIN ? T : F  -->  F
8811         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8812           return ReplaceInstUsesWith(SI, FalseVal);
8813         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8814         Constant *AdjustedRHS = SubOne(CI);
8815         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8816             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8817           Pred = ICmpInst::getSwappedPredicate(Pred);
8818           CmpRHS = AdjustedRHS;
8819           std::swap(FalseVal, TrueVal);
8820           ICI->setPredicate(Pred);
8821           ICI->setOperand(1, CmpRHS);
8822           SI.setOperand(1, TrueVal);
8823           SI.setOperand(2, FalseVal);
8824           Changed = true;
8825         }
8826         break;
8827       }
8828       case ICmpInst::ICMP_UGT:
8829       case ICmpInst::ICMP_SGT: {
8830         // X > MAX ? T : F  -->  F
8831         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8832           return ReplaceInstUsesWith(SI, FalseVal);
8833         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8834         Constant *AdjustedRHS = AddOne(CI);
8835         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8836             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8837           Pred = ICmpInst::getSwappedPredicate(Pred);
8838           CmpRHS = AdjustedRHS;
8839           std::swap(FalseVal, TrueVal);
8840           ICI->setPredicate(Pred);
8841           ICI->setOperand(1, CmpRHS);
8842           SI.setOperand(1, TrueVal);
8843           SI.setOperand(2, FalseVal);
8844           Changed = true;
8845         }
8846         break;
8847       }
8848       }
8849
8850       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8851       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8852       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8853       if (match(TrueVal, m_ConstantInt<-1>()) &&
8854           match(FalseVal, m_ConstantInt<0>()))
8855         Pred = ICI->getPredicate();
8856       else if (match(TrueVal, m_ConstantInt<0>()) &&
8857                match(FalseVal, m_ConstantInt<-1>()))
8858         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8859       
8860       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8861         // If we are just checking for a icmp eq of a single bit and zext'ing it
8862         // to an integer, then shift the bit to the appropriate place and then
8863         // cast to integer to avoid the comparison.
8864         const APInt &Op1CV = CI->getValue();
8865     
8866         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8867         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8868         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8869             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8870           Value *In = ICI->getOperand(0);
8871           Value *Sh = ConstantInt::get(In->getType(),
8872                                        In->getType()->getPrimitiveSizeInBits()-1);
8873           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8874                                                           In->getName()+".lobit"),
8875                                    *ICI);
8876           if (In->getType() != SI.getType())
8877             In = CastInst::CreateIntegerCast(In, SI.getType(),
8878                                              true/*SExt*/, "tmp", ICI);
8879     
8880           if (Pred == ICmpInst::ICMP_SGT)
8881             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8882                                        In->getName()+".not"), *ICI);
8883     
8884           return ReplaceInstUsesWith(SI, In);
8885         }
8886       }
8887     }
8888
8889   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8890     // Transform (X == Y) ? X : Y  -> Y
8891     if (Pred == ICmpInst::ICMP_EQ)
8892       return ReplaceInstUsesWith(SI, FalseVal);
8893     // Transform (X != Y) ? X : Y  -> X
8894     if (Pred == ICmpInst::ICMP_NE)
8895       return ReplaceInstUsesWith(SI, TrueVal);
8896     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8897
8898   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8899     // Transform (X == Y) ? Y : X  -> X
8900     if (Pred == ICmpInst::ICMP_EQ)
8901       return ReplaceInstUsesWith(SI, FalseVal);
8902     // Transform (X != Y) ? Y : X  -> Y
8903     if (Pred == ICmpInst::ICMP_NE)
8904       return ReplaceInstUsesWith(SI, TrueVal);
8905     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8906   }
8907
8908   /// NOTE: if we wanted to, this is where to detect integer ABS
8909
8910   return Changed ? &SI : 0;
8911 }
8912
8913 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8914   Value *CondVal = SI.getCondition();
8915   Value *TrueVal = SI.getTrueValue();
8916   Value *FalseVal = SI.getFalseValue();
8917
8918   // select true, X, Y  -> X
8919   // select false, X, Y -> Y
8920   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8921     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8922
8923   // select C, X, X -> X
8924   if (TrueVal == FalseVal)
8925     return ReplaceInstUsesWith(SI, TrueVal);
8926
8927   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8928     return ReplaceInstUsesWith(SI, FalseVal);
8929   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8930     return ReplaceInstUsesWith(SI, TrueVal);
8931   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8932     if (isa<Constant>(TrueVal))
8933       return ReplaceInstUsesWith(SI, TrueVal);
8934     else
8935       return ReplaceInstUsesWith(SI, FalseVal);
8936   }
8937
8938   if (SI.getType() == Type::Int1Ty) {
8939     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8940       if (C->getZExtValue()) {
8941         // Change: A = select B, true, C --> A = or B, C
8942         return BinaryOperator::CreateOr(CondVal, FalseVal);
8943       } else {
8944         // Change: A = select B, false, C --> A = and !B, C
8945         Value *NotCond =
8946           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8947                                              "not."+CondVal->getName()), SI);
8948         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8949       }
8950     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8951       if (C->getZExtValue() == false) {
8952         // Change: A = select B, C, false --> A = and B, C
8953         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8954       } else {
8955         // Change: A = select B, C, true --> A = or !B, C
8956         Value *NotCond =
8957           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8958                                              "not."+CondVal->getName()), SI);
8959         return BinaryOperator::CreateOr(NotCond, TrueVal);
8960       }
8961     }
8962     
8963     // select a, b, a  -> a&b
8964     // select a, a, b  -> a|b
8965     if (CondVal == TrueVal)
8966       return BinaryOperator::CreateOr(CondVal, FalseVal);
8967     else if (CondVal == FalseVal)
8968       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8969   }
8970
8971   // Selecting between two integer constants?
8972   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8973     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8974       // select C, 1, 0 -> zext C to int
8975       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8976         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8977       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8978         // select C, 0, 1 -> zext !C to int
8979         Value *NotCond =
8980           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8981                                                "not."+CondVal->getName()), SI);
8982         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8983       }
8984
8985       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8986
8987         // (x <s 0) ? -1 : 0 -> ashr x, 31
8988         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8989           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8990             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8991               // The comparison constant and the result are not neccessarily the
8992               // same width. Make an all-ones value by inserting a AShr.
8993               Value *X = IC->getOperand(0);
8994               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8995               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8996               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8997                                                         ShAmt, "ones");
8998               InsertNewInstBefore(SRA, SI);
8999
9000               // Then cast to the appropriate width.
9001               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9002             }
9003           }
9004
9005
9006         // If one of the constants is zero (we know they can't both be) and we
9007         // have an icmp instruction with zero, and we have an 'and' with the
9008         // non-constant value, eliminate this whole mess.  This corresponds to
9009         // cases like this: ((X & 27) ? 27 : 0)
9010         if (TrueValC->isZero() || FalseValC->isZero())
9011           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9012               cast<Constant>(IC->getOperand(1))->isNullValue())
9013             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9014               if (ICA->getOpcode() == Instruction::And &&
9015                   isa<ConstantInt>(ICA->getOperand(1)) &&
9016                   (ICA->getOperand(1) == TrueValC ||
9017                    ICA->getOperand(1) == FalseValC) &&
9018                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9019                 // Okay, now we know that everything is set up, we just don't
9020                 // know whether we have a icmp_ne or icmp_eq and whether the 
9021                 // true or false val is the zero.
9022                 bool ShouldNotVal = !TrueValC->isZero();
9023                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9024                 Value *V = ICA;
9025                 if (ShouldNotVal)
9026                   V = InsertNewInstBefore(BinaryOperator::Create(
9027                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9028                 return ReplaceInstUsesWith(SI, V);
9029               }
9030       }
9031     }
9032
9033   // See if we are selecting two values based on a comparison of the two values.
9034   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9035     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9036       // Transform (X == Y) ? X : Y  -> Y
9037       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9038         // This is not safe in general for floating point:  
9039         // consider X== -0, Y== +0.
9040         // It becomes safe if either operand is a nonzero constant.
9041         ConstantFP *CFPt, *CFPf;
9042         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9043               !CFPt->getValueAPF().isZero()) ||
9044             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9045              !CFPf->getValueAPF().isZero()))
9046         return ReplaceInstUsesWith(SI, FalseVal);
9047       }
9048       // Transform (X != Y) ? X : Y  -> X
9049       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9050         return ReplaceInstUsesWith(SI, TrueVal);
9051       // NOTE: if we wanted to, this is where to detect MIN/MAX
9052
9053     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9054       // Transform (X == Y) ? Y : X  -> X
9055       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9056         // This is not safe in general for floating point:  
9057         // consider X== -0, Y== +0.
9058         // It becomes safe if either operand is a nonzero constant.
9059         ConstantFP *CFPt, *CFPf;
9060         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9061               !CFPt->getValueAPF().isZero()) ||
9062             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9063              !CFPf->getValueAPF().isZero()))
9064           return ReplaceInstUsesWith(SI, FalseVal);
9065       }
9066       // Transform (X != Y) ? Y : X  -> Y
9067       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9068         return ReplaceInstUsesWith(SI, TrueVal);
9069       // NOTE: if we wanted to, this is where to detect MIN/MAX
9070     }
9071     // NOTE: if we wanted to, this is where to detect ABS
9072   }
9073
9074   // See if we are selecting two values based on a comparison of the two values.
9075   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9076     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9077       return Result;
9078
9079   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9080     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9081       if (TI->hasOneUse() && FI->hasOneUse()) {
9082         Instruction *AddOp = 0, *SubOp = 0;
9083
9084         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9085         if (TI->getOpcode() == FI->getOpcode())
9086           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9087             return IV;
9088
9089         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9090         // even legal for FP.
9091         if (TI->getOpcode() == Instruction::Sub &&
9092             FI->getOpcode() == Instruction::Add) {
9093           AddOp = FI; SubOp = TI;
9094         } else if (FI->getOpcode() == Instruction::Sub &&
9095                    TI->getOpcode() == Instruction::Add) {
9096           AddOp = TI; SubOp = FI;
9097         }
9098
9099         if (AddOp) {
9100           Value *OtherAddOp = 0;
9101           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9102             OtherAddOp = AddOp->getOperand(1);
9103           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9104             OtherAddOp = AddOp->getOperand(0);
9105           }
9106
9107           if (OtherAddOp) {
9108             // So at this point we know we have (Y -> OtherAddOp):
9109             //        select C, (add X, Y), (sub X, Z)
9110             Value *NegVal;  // Compute -Z
9111             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9112               NegVal = ConstantExpr::getNeg(C);
9113             } else {
9114               NegVal = InsertNewInstBefore(
9115                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9116             }
9117
9118             Value *NewTrueOp = OtherAddOp;
9119             Value *NewFalseOp = NegVal;
9120             if (AddOp != TI)
9121               std::swap(NewTrueOp, NewFalseOp);
9122             Instruction *NewSel =
9123               SelectInst::Create(CondVal, NewTrueOp,
9124                                  NewFalseOp, SI.getName() + ".p");
9125
9126             NewSel = InsertNewInstBefore(NewSel, SI);
9127             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9128           }
9129         }
9130       }
9131
9132   // See if we can fold the select into one of our operands.
9133   if (SI.getType()->isInteger()) {
9134     // See the comment above GetSelectFoldableOperands for a description of the
9135     // transformation we are doing here.
9136     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9137       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9138           !isa<Constant>(FalseVal))
9139         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9140           unsigned OpToFold = 0;
9141           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9142             OpToFold = 1;
9143           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9144             OpToFold = 2;
9145           }
9146
9147           if (OpToFold) {
9148             Constant *C = GetSelectFoldableConstant(TVI);
9149             Instruction *NewSel =
9150               SelectInst::Create(SI.getCondition(),
9151                                  TVI->getOperand(2-OpToFold), C);
9152             InsertNewInstBefore(NewSel, SI);
9153             NewSel->takeName(TVI);
9154             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9155               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9156             else {
9157               assert(0 && "Unknown instruction!!");
9158             }
9159           }
9160         }
9161
9162     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9163       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9164           !isa<Constant>(TrueVal))
9165         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9166           unsigned OpToFold = 0;
9167           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9168             OpToFold = 1;
9169           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9170             OpToFold = 2;
9171           }
9172
9173           if (OpToFold) {
9174             Constant *C = GetSelectFoldableConstant(FVI);
9175             Instruction *NewSel =
9176               SelectInst::Create(SI.getCondition(), C,
9177                                  FVI->getOperand(2-OpToFold));
9178             InsertNewInstBefore(NewSel, SI);
9179             NewSel->takeName(FVI);
9180             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9181               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9182             else
9183               assert(0 && "Unknown instruction!!");
9184           }
9185         }
9186   }
9187
9188   if (BinaryOperator::isNot(CondVal)) {
9189     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9190     SI.setOperand(1, FalseVal);
9191     SI.setOperand(2, TrueVal);
9192     return &SI;
9193   }
9194
9195   return 0;
9196 }
9197
9198 /// EnforceKnownAlignment - If the specified pointer points to an object that
9199 /// we control, modify the object's alignment to PrefAlign. This isn't
9200 /// often possible though. If alignment is important, a more reliable approach
9201 /// is to simply align all global variables and allocation instructions to
9202 /// their preferred alignment from the beginning.
9203 ///
9204 static unsigned EnforceKnownAlignment(Value *V,
9205                                       unsigned Align, unsigned PrefAlign) {
9206
9207   User *U = dyn_cast<User>(V);
9208   if (!U) return Align;
9209
9210   switch (getOpcode(U)) {
9211   default: break;
9212   case Instruction::BitCast:
9213     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9214   case Instruction::GetElementPtr: {
9215     // If all indexes are zero, it is just the alignment of the base pointer.
9216     bool AllZeroOperands = true;
9217     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9218       if (!isa<Constant>(*i) ||
9219           !cast<Constant>(*i)->isNullValue()) {
9220         AllZeroOperands = false;
9221         break;
9222       }
9223
9224     if (AllZeroOperands) {
9225       // Treat this like a bitcast.
9226       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9227     }
9228     break;
9229   }
9230   }
9231
9232   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9233     // If there is a large requested alignment and we can, bump up the alignment
9234     // of the global.
9235     if (!GV->isDeclaration()) {
9236       GV->setAlignment(PrefAlign);
9237       Align = PrefAlign;
9238     }
9239   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9240     // If there is a requested alignment and if this is an alloca, round up.  We
9241     // don't do this for malloc, because some systems can't respect the request.
9242     if (isa<AllocaInst>(AI)) {
9243       AI->setAlignment(PrefAlign);
9244       Align = PrefAlign;
9245     }
9246   }
9247
9248   return Align;
9249 }
9250
9251 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9252 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9253 /// and it is more than the alignment of the ultimate object, see if we can
9254 /// increase the alignment of the ultimate object, making this check succeed.
9255 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9256                                                   unsigned PrefAlign) {
9257   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9258                       sizeof(PrefAlign) * CHAR_BIT;
9259   APInt Mask = APInt::getAllOnesValue(BitWidth);
9260   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9261   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9262   unsigned TrailZ = KnownZero.countTrailingOnes();
9263   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9264
9265   if (PrefAlign > Align)
9266     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9267   
9268     // We don't need to make any adjustment.
9269   return Align;
9270 }
9271
9272 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9273   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9274   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9275   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9276   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9277
9278   if (CopyAlign < MinAlign) {
9279     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9280     return MI;
9281   }
9282   
9283   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9284   // load/store.
9285   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9286   if (MemOpLength == 0) return 0;
9287   
9288   // Source and destination pointer types are always "i8*" for intrinsic.  See
9289   // if the size is something we can handle with a single primitive load/store.
9290   // A single load+store correctly handles overlapping memory in the memmove
9291   // case.
9292   unsigned Size = MemOpLength->getZExtValue();
9293   if (Size == 0) return MI;  // Delete this mem transfer.
9294   
9295   if (Size > 8 || (Size&(Size-1)))
9296     return 0;  // If not 1/2/4/8 bytes, exit.
9297   
9298   // Use an integer load+store unless we can find something better.
9299   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9300   
9301   // Memcpy forces the use of i8* for the source and destination.  That means
9302   // that if you're using memcpy to move one double around, you'll get a cast
9303   // from double* to i8*.  We'd much rather use a double load+store rather than
9304   // an i64 load+store, here because this improves the odds that the source or
9305   // dest address will be promotable.  See if we can find a better type than the
9306   // integer datatype.
9307   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9308     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9309     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9310       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9311       // down through these levels if so.
9312       while (!SrcETy->isSingleValueType()) {
9313         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9314           if (STy->getNumElements() == 1)
9315             SrcETy = STy->getElementType(0);
9316           else
9317             break;
9318         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9319           if (ATy->getNumElements() == 1)
9320             SrcETy = ATy->getElementType();
9321           else
9322             break;
9323         } else
9324           break;
9325       }
9326       
9327       if (SrcETy->isSingleValueType())
9328         NewPtrTy = PointerType::getUnqual(SrcETy);
9329     }
9330   }
9331   
9332   
9333   // If the memcpy/memmove provides better alignment info than we can
9334   // infer, use it.
9335   SrcAlign = std::max(SrcAlign, CopyAlign);
9336   DstAlign = std::max(DstAlign, CopyAlign);
9337   
9338   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9339   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9340   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9341   InsertNewInstBefore(L, *MI);
9342   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9343
9344   // Set the size of the copy to 0, it will be deleted on the next iteration.
9345   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9346   return MI;
9347 }
9348
9349 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9350   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9351   if (MI->getAlignment()->getZExtValue() < Alignment) {
9352     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9353     return MI;
9354   }
9355   
9356   // Extract the length and alignment and fill if they are constant.
9357   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9358   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9359   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9360     return 0;
9361   uint64_t Len = LenC->getZExtValue();
9362   Alignment = MI->getAlignment()->getZExtValue();
9363   
9364   // If the length is zero, this is a no-op
9365   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9366   
9367   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9368   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9369     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9370     
9371     Value *Dest = MI->getDest();
9372     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9373
9374     // Alignment 0 is identity for alignment 1 for memset, but not store.
9375     if (Alignment == 0) Alignment = 1;
9376     
9377     // Extract the fill value and store.
9378     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9379     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9380                                       Alignment), *MI);
9381     
9382     // Set the size of the copy to 0, it will be deleted on the next iteration.
9383     MI->setLength(Constant::getNullValue(LenC->getType()));
9384     return MI;
9385   }
9386
9387   return 0;
9388 }
9389
9390
9391 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9392 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9393 /// the heavy lifting.
9394 ///
9395 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9396   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9397   if (!II) return visitCallSite(&CI);
9398   
9399   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9400   // visitCallSite.
9401   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9402     bool Changed = false;
9403
9404     // memmove/cpy/set of zero bytes is a noop.
9405     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9406       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9407
9408       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9409         if (CI->getZExtValue() == 1) {
9410           // Replace the instruction with just byte operations.  We would
9411           // transform other cases to loads/stores, but we don't know if
9412           // alignment is sufficient.
9413         }
9414     }
9415
9416     // If we have a memmove and the source operation is a constant global,
9417     // then the source and dest pointers can't alias, so we can change this
9418     // into a call to memcpy.
9419     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9420       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9421         if (GVSrc->isConstant()) {
9422           Module *M = CI.getParent()->getParent()->getParent();
9423           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9424           const Type *Tys[1];
9425           Tys[0] = CI.getOperand(3)->getType();
9426           CI.setOperand(0, 
9427                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9428           Changed = true;
9429         }
9430
9431       // memmove(x,x,size) -> noop.
9432       if (MMI->getSource() == MMI->getDest())
9433         return EraseInstFromFunction(CI);
9434     }
9435
9436     // If we can determine a pointer alignment that is bigger than currently
9437     // set, update the alignment.
9438     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9439       if (Instruction *I = SimplifyMemTransfer(MI))
9440         return I;
9441     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9442       if (Instruction *I = SimplifyMemSet(MSI))
9443         return I;
9444     }
9445           
9446     if (Changed) return II;
9447   }
9448   
9449   switch (II->getIntrinsicID()) {
9450   default: break;
9451   case Intrinsic::bswap:
9452     // bswap(bswap(x)) -> x
9453     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9454       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9455         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9456     break;
9457   case Intrinsic::ppc_altivec_lvx:
9458   case Intrinsic::ppc_altivec_lvxl:
9459   case Intrinsic::x86_sse_loadu_ps:
9460   case Intrinsic::x86_sse2_loadu_pd:
9461   case Intrinsic::x86_sse2_loadu_dq:
9462     // Turn PPC lvx     -> load if the pointer is known aligned.
9463     // Turn X86 loadups -> load if the pointer is known aligned.
9464     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9465       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9466                                        PointerType::getUnqual(II->getType()),
9467                                        CI);
9468       return new LoadInst(Ptr);
9469     }
9470     break;
9471   case Intrinsic::ppc_altivec_stvx:
9472   case Intrinsic::ppc_altivec_stvxl:
9473     // Turn stvx -> store if the pointer is known aligned.
9474     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9475       const Type *OpPtrTy = 
9476         PointerType::getUnqual(II->getOperand(1)->getType());
9477       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9478       return new StoreInst(II->getOperand(1), Ptr);
9479     }
9480     break;
9481   case Intrinsic::x86_sse_storeu_ps:
9482   case Intrinsic::x86_sse2_storeu_pd:
9483   case Intrinsic::x86_sse2_storeu_dq:
9484     // Turn X86 storeu -> store if the pointer is known aligned.
9485     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9486       const Type *OpPtrTy = 
9487         PointerType::getUnqual(II->getOperand(2)->getType());
9488       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9489       return new StoreInst(II->getOperand(2), Ptr);
9490     }
9491     break;
9492     
9493   case Intrinsic::x86_sse_cvttss2si: {
9494     // These intrinsics only demands the 0th element of its input vector.  If
9495     // we can simplify the input based on that, do so now.
9496     uint64_t UndefElts;
9497     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9498                                               UndefElts)) {
9499       II->setOperand(1, V);
9500       return II;
9501     }
9502     break;
9503   }
9504     
9505   case Intrinsic::ppc_altivec_vperm:
9506     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9507     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9508       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9509       
9510       // Check that all of the elements are integer constants or undefs.
9511       bool AllEltsOk = true;
9512       for (unsigned i = 0; i != 16; ++i) {
9513         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9514             !isa<UndefValue>(Mask->getOperand(i))) {
9515           AllEltsOk = false;
9516           break;
9517         }
9518       }
9519       
9520       if (AllEltsOk) {
9521         // Cast the input vectors to byte vectors.
9522         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9523         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9524         Value *Result = UndefValue::get(Op0->getType());
9525         
9526         // Only extract each element once.
9527         Value *ExtractedElts[32];
9528         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9529         
9530         for (unsigned i = 0; i != 16; ++i) {
9531           if (isa<UndefValue>(Mask->getOperand(i)))
9532             continue;
9533           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9534           Idx &= 31;  // Match the hardware behavior.
9535           
9536           if (ExtractedElts[Idx] == 0) {
9537             Instruction *Elt = 
9538               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9539             InsertNewInstBefore(Elt, CI);
9540             ExtractedElts[Idx] = Elt;
9541           }
9542         
9543           // Insert this value into the result vector.
9544           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9545                                              i, "tmp");
9546           InsertNewInstBefore(cast<Instruction>(Result), CI);
9547         }
9548         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9549       }
9550     }
9551     break;
9552
9553   case Intrinsic::stackrestore: {
9554     // If the save is right next to the restore, remove the restore.  This can
9555     // happen when variable allocas are DCE'd.
9556     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9557       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9558         BasicBlock::iterator BI = SS;
9559         if (&*++BI == II)
9560           return EraseInstFromFunction(CI);
9561       }
9562     }
9563     
9564     // Scan down this block to see if there is another stack restore in the
9565     // same block without an intervening call/alloca.
9566     BasicBlock::iterator BI = II;
9567     TerminatorInst *TI = II->getParent()->getTerminator();
9568     bool CannotRemove = false;
9569     for (++BI; &*BI != TI; ++BI) {
9570       if (isa<AllocaInst>(BI)) {
9571         CannotRemove = true;
9572         break;
9573       }
9574       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9575         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9576           // If there is a stackrestore below this one, remove this one.
9577           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9578             return EraseInstFromFunction(CI);
9579           // Otherwise, ignore the intrinsic.
9580         } else {
9581           // If we found a non-intrinsic call, we can't remove the stack
9582           // restore.
9583           CannotRemove = true;
9584           break;
9585         }
9586       }
9587     }
9588     
9589     // If the stack restore is in a return/unwind block and if there are no
9590     // allocas or calls between the restore and the return, nuke the restore.
9591     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9592       return EraseInstFromFunction(CI);
9593     break;
9594   }
9595   }
9596
9597   return visitCallSite(II);
9598 }
9599
9600 // InvokeInst simplification
9601 //
9602 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9603   return visitCallSite(&II);
9604 }
9605
9606 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9607 /// passed through the varargs area, we can eliminate the use of the cast.
9608 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9609                                          const CastInst * const CI,
9610                                          const TargetData * const TD,
9611                                          const int ix) {
9612   if (!CI->isLosslessCast())
9613     return false;
9614
9615   // The size of ByVal arguments is derived from the type, so we
9616   // can't change to a type with a different size.  If the size were
9617   // passed explicitly we could avoid this check.
9618   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9619     return true;
9620
9621   const Type* SrcTy = 
9622             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9623   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9624   if (!SrcTy->isSized() || !DstTy->isSized())
9625     return false;
9626   if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
9627     return false;
9628   return true;
9629 }
9630
9631 // visitCallSite - Improvements for call and invoke instructions.
9632 //
9633 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9634   bool Changed = false;
9635
9636   // If the callee is a constexpr cast of a function, attempt to move the cast
9637   // to the arguments of the call/invoke.
9638   if (transformConstExprCastCall(CS)) return 0;
9639
9640   Value *Callee = CS.getCalledValue();
9641
9642   if (Function *CalleeF = dyn_cast<Function>(Callee))
9643     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9644       Instruction *OldCall = CS.getInstruction();
9645       // If the call and callee calling conventions don't match, this call must
9646       // be unreachable, as the call is undefined.
9647       new StoreInst(ConstantInt::getTrue(),
9648                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9649                                     OldCall);
9650       if (!OldCall->use_empty())
9651         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9652       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9653         return EraseInstFromFunction(*OldCall);
9654       return 0;
9655     }
9656
9657   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9658     // This instruction is not reachable, just remove it.  We insert a store to
9659     // undef so that we know that this code is not reachable, despite the fact
9660     // that we can't modify the CFG here.
9661     new StoreInst(ConstantInt::getTrue(),
9662                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9663                   CS.getInstruction());
9664
9665     if (!CS.getInstruction()->use_empty())
9666       CS.getInstruction()->
9667         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9668
9669     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9670       // Don't break the CFG, insert a dummy cond branch.
9671       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9672                          ConstantInt::getTrue(), II);
9673     }
9674     return EraseInstFromFunction(*CS.getInstruction());
9675   }
9676
9677   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9678     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9679       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9680         return transformCallThroughTrampoline(CS);
9681
9682   const PointerType *PTy = cast<PointerType>(Callee->getType());
9683   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9684   if (FTy->isVarArg()) {
9685     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9686     // See if we can optimize any arguments passed through the varargs area of
9687     // the call.
9688     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9689            E = CS.arg_end(); I != E; ++I, ++ix) {
9690       CastInst *CI = dyn_cast<CastInst>(*I);
9691       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9692         *I = CI->getOperand(0);
9693         Changed = true;
9694       }
9695     }
9696   }
9697
9698   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9699     // Inline asm calls cannot throw - mark them 'nounwind'.
9700     CS.setDoesNotThrow();
9701     Changed = true;
9702   }
9703
9704   return Changed ? CS.getInstruction() : 0;
9705 }
9706
9707 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9708 // attempt to move the cast to the arguments of the call/invoke.
9709 //
9710 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9711   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9712   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9713   if (CE->getOpcode() != Instruction::BitCast || 
9714       !isa<Function>(CE->getOperand(0)))
9715     return false;
9716   Function *Callee = cast<Function>(CE->getOperand(0));
9717   Instruction *Caller = CS.getInstruction();
9718   const AttrListPtr &CallerPAL = CS.getAttributes();
9719
9720   // Okay, this is a cast from a function to a different type.  Unless doing so
9721   // would cause a type conversion of one of our arguments, change this call to
9722   // be a direct call with arguments casted to the appropriate types.
9723   //
9724   const FunctionType *FT = Callee->getFunctionType();
9725   const Type *OldRetTy = Caller->getType();
9726   const Type *NewRetTy = FT->getReturnType();
9727
9728   if (isa<StructType>(NewRetTy))
9729     return false; // TODO: Handle multiple return values.
9730
9731   // Check to see if we are changing the return type...
9732   if (OldRetTy != NewRetTy) {
9733     if (Callee->isDeclaration() &&
9734         // Conversion is ok if changing from one pointer type to another or from
9735         // a pointer to an integer of the same size.
9736         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9737           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9738       return false;   // Cannot transform this return value.
9739
9740     if (!Caller->use_empty() &&
9741         // void -> non-void is handled specially
9742         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9743       return false;   // Cannot transform this return value.
9744
9745     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9746       Attributes RAttrs = CallerPAL.getRetAttributes();
9747       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9748         return false;   // Attribute not compatible with transformed value.
9749     }
9750
9751     // If the callsite is an invoke instruction, and the return value is used by
9752     // a PHI node in a successor, we cannot change the return type of the call
9753     // because there is no place to put the cast instruction (without breaking
9754     // the critical edge).  Bail out in this case.
9755     if (!Caller->use_empty())
9756       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9757         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9758              UI != E; ++UI)
9759           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9760             if (PN->getParent() == II->getNormalDest() ||
9761                 PN->getParent() == II->getUnwindDest())
9762               return false;
9763   }
9764
9765   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9766   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9767
9768   CallSite::arg_iterator AI = CS.arg_begin();
9769   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9770     const Type *ParamTy = FT->getParamType(i);
9771     const Type *ActTy = (*AI)->getType();
9772
9773     if (!CastInst::isCastable(ActTy, ParamTy))
9774       return false;   // Cannot transform this parameter value.
9775
9776     if (CallerPAL.getParamAttributes(i + 1) 
9777         & Attribute::typeIncompatible(ParamTy))
9778       return false;   // Attribute not compatible with transformed value.
9779
9780     // Converting from one pointer type to another or between a pointer and an
9781     // integer of the same size is safe even if we do not have a body.
9782     bool isConvertible = ActTy == ParamTy ||
9783       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9784        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9785     if (Callee->isDeclaration() && !isConvertible) return false;
9786   }
9787
9788   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9789       Callee->isDeclaration())
9790     return false;   // Do not delete arguments unless we have a function body.
9791
9792   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9793       !CallerPAL.isEmpty())
9794     // In this case we have more arguments than the new function type, but we
9795     // won't be dropping them.  Check that these extra arguments have attributes
9796     // that are compatible with being a vararg call argument.
9797     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9798       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9799         break;
9800       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9801       if (PAttrs & Attribute::VarArgsIncompatible)
9802         return false;
9803     }
9804
9805   // Okay, we decided that this is a safe thing to do: go ahead and start
9806   // inserting cast instructions as necessary...
9807   std::vector<Value*> Args;
9808   Args.reserve(NumActualArgs);
9809   SmallVector<AttributeWithIndex, 8> attrVec;
9810   attrVec.reserve(NumCommonArgs);
9811
9812   // Get any return attributes.
9813   Attributes RAttrs = CallerPAL.getRetAttributes();
9814
9815   // If the return value is not being used, the type may not be compatible
9816   // with the existing attributes.  Wipe out any problematic attributes.
9817   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9818
9819   // Add the new return attributes.
9820   if (RAttrs)
9821     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9822
9823   AI = CS.arg_begin();
9824   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9825     const Type *ParamTy = FT->getParamType(i);
9826     if ((*AI)->getType() == ParamTy) {
9827       Args.push_back(*AI);
9828     } else {
9829       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9830           false, ParamTy, false);
9831       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9832       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9833     }
9834
9835     // Add any parameter attributes.
9836     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9837       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9838   }
9839
9840   // If the function takes more arguments than the call was taking, add them
9841   // now...
9842   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9843     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9844
9845   // If we are removing arguments to the function, emit an obnoxious warning...
9846   if (FT->getNumParams() < NumActualArgs) {
9847     if (!FT->isVarArg()) {
9848       cerr << "WARNING: While resolving call to function '"
9849            << Callee->getName() << "' arguments were dropped!\n";
9850     } else {
9851       // Add all of the arguments in their promoted form to the arg list...
9852       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9853         const Type *PTy = getPromotedType((*AI)->getType());
9854         if (PTy != (*AI)->getType()) {
9855           // Must promote to pass through va_arg area!
9856           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9857                                                                 PTy, false);
9858           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9859           InsertNewInstBefore(Cast, *Caller);
9860           Args.push_back(Cast);
9861         } else {
9862           Args.push_back(*AI);
9863         }
9864
9865         // Add any parameter attributes.
9866         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9867           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9868       }
9869     }
9870   }
9871
9872   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9873     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9874
9875   if (NewRetTy == Type::VoidTy)
9876     Caller->setName("");   // Void type should not have a name.
9877
9878   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9879
9880   Instruction *NC;
9881   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9882     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9883                             Args.begin(), Args.end(),
9884                             Caller->getName(), Caller);
9885     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9886     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9887   } else {
9888     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9889                           Caller->getName(), Caller);
9890     CallInst *CI = cast<CallInst>(Caller);
9891     if (CI->isTailCall())
9892       cast<CallInst>(NC)->setTailCall();
9893     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9894     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9895   }
9896
9897   // Insert a cast of the return type as necessary.
9898   Value *NV = NC;
9899   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9900     if (NV->getType() != Type::VoidTy) {
9901       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9902                                                             OldRetTy, false);
9903       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9904
9905       // If this is an invoke instruction, we should insert it after the first
9906       // non-phi, instruction in the normal successor block.
9907       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9908         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9909         InsertNewInstBefore(NC, *I);
9910       } else {
9911         // Otherwise, it's a call, just insert cast right after the call instr
9912         InsertNewInstBefore(NC, *Caller);
9913       }
9914       AddUsersToWorkList(*Caller);
9915     } else {
9916       NV = UndefValue::get(Caller->getType());
9917     }
9918   }
9919
9920   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9921     Caller->replaceAllUsesWith(NV);
9922   Caller->eraseFromParent();
9923   RemoveFromWorkList(Caller);
9924   return true;
9925 }
9926
9927 // transformCallThroughTrampoline - Turn a call to a function created by the
9928 // init_trampoline intrinsic into a direct call to the underlying function.
9929 //
9930 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9931   Value *Callee = CS.getCalledValue();
9932   const PointerType *PTy = cast<PointerType>(Callee->getType());
9933   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9934   const AttrListPtr &Attrs = CS.getAttributes();
9935
9936   // If the call already has the 'nest' attribute somewhere then give up -
9937   // otherwise 'nest' would occur twice after splicing in the chain.
9938   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9939     return 0;
9940
9941   IntrinsicInst *Tramp =
9942     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9943
9944   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9945   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9946   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9947
9948   const AttrListPtr &NestAttrs = NestF->getAttributes();
9949   if (!NestAttrs.isEmpty()) {
9950     unsigned NestIdx = 1;
9951     const Type *NestTy = 0;
9952     Attributes NestAttr = Attribute::None;
9953
9954     // Look for a parameter marked with the 'nest' attribute.
9955     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9956          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9957       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9958         // Record the parameter type and any other attributes.
9959         NestTy = *I;
9960         NestAttr = NestAttrs.getParamAttributes(NestIdx);
9961         break;
9962       }
9963
9964     if (NestTy) {
9965       Instruction *Caller = CS.getInstruction();
9966       std::vector<Value*> NewArgs;
9967       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9968
9969       SmallVector<AttributeWithIndex, 8> NewAttrs;
9970       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9971
9972       // Insert the nest argument into the call argument list, which may
9973       // mean appending it.  Likewise for attributes.
9974
9975       // Add any result attributes.
9976       if (Attributes Attr = Attrs.getRetAttributes())
9977         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9978
9979       {
9980         unsigned Idx = 1;
9981         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9982         do {
9983           if (Idx == NestIdx) {
9984             // Add the chain argument and attributes.
9985             Value *NestVal = Tramp->getOperand(3);
9986             if (NestVal->getType() != NestTy)
9987               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9988             NewArgs.push_back(NestVal);
9989             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9990           }
9991
9992           if (I == E)
9993             break;
9994
9995           // Add the original argument and attributes.
9996           NewArgs.push_back(*I);
9997           if (Attributes Attr = Attrs.getParamAttributes(Idx))
9998             NewAttrs.push_back
9999               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10000
10001           ++Idx, ++I;
10002         } while (1);
10003       }
10004
10005       // Add any function attributes.
10006       if (Attributes Attr = Attrs.getFnAttributes())
10007         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10008
10009       // The trampoline may have been bitcast to a bogus type (FTy).
10010       // Handle this by synthesizing a new function type, equal to FTy
10011       // with the chain parameter inserted.
10012
10013       std::vector<const Type*> NewTypes;
10014       NewTypes.reserve(FTy->getNumParams()+1);
10015
10016       // Insert the chain's type into the list of parameter types, which may
10017       // mean appending it.
10018       {
10019         unsigned Idx = 1;
10020         FunctionType::param_iterator I = FTy->param_begin(),
10021           E = FTy->param_end();
10022
10023         do {
10024           if (Idx == NestIdx)
10025             // Add the chain's type.
10026             NewTypes.push_back(NestTy);
10027
10028           if (I == E)
10029             break;
10030
10031           // Add the original type.
10032           NewTypes.push_back(*I);
10033
10034           ++Idx, ++I;
10035         } while (1);
10036       }
10037
10038       // Replace the trampoline call with a direct call.  Let the generic
10039       // code sort out any function type mismatches.
10040       FunctionType *NewFTy =
10041         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10042       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10043         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10044       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10045
10046       Instruction *NewCaller;
10047       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10048         NewCaller = InvokeInst::Create(NewCallee,
10049                                        II->getNormalDest(), II->getUnwindDest(),
10050                                        NewArgs.begin(), NewArgs.end(),
10051                                        Caller->getName(), Caller);
10052         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10053         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10054       } else {
10055         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10056                                      Caller->getName(), Caller);
10057         if (cast<CallInst>(Caller)->isTailCall())
10058           cast<CallInst>(NewCaller)->setTailCall();
10059         cast<CallInst>(NewCaller)->
10060           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10061         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10062       }
10063       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10064         Caller->replaceAllUsesWith(NewCaller);
10065       Caller->eraseFromParent();
10066       RemoveFromWorkList(Caller);
10067       return 0;
10068     }
10069   }
10070
10071   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10072   // parameter, there is no need to adjust the argument list.  Let the generic
10073   // code sort out any function type mismatches.
10074   Constant *NewCallee =
10075     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10076   CS.setCalledFunction(NewCallee);
10077   return CS.getInstruction();
10078 }
10079
10080 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10081 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10082 /// and a single binop.
10083 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10084   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10085   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10086   unsigned Opc = FirstInst->getOpcode();
10087   Value *LHSVal = FirstInst->getOperand(0);
10088   Value *RHSVal = FirstInst->getOperand(1);
10089     
10090   const Type *LHSType = LHSVal->getType();
10091   const Type *RHSType = RHSVal->getType();
10092   
10093   // Scan to see if all operands are the same opcode, all have one use, and all
10094   // kill their operands (i.e. the operands have one use).
10095   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10096     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10097     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10098         // Verify type of the LHS matches so we don't fold cmp's of different
10099         // types or GEP's with different index types.
10100         I->getOperand(0)->getType() != LHSType ||
10101         I->getOperand(1)->getType() != RHSType)
10102       return 0;
10103
10104     // If they are CmpInst instructions, check their predicates
10105     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10106       if (cast<CmpInst>(I)->getPredicate() !=
10107           cast<CmpInst>(FirstInst)->getPredicate())
10108         return 0;
10109     
10110     // Keep track of which operand needs a phi node.
10111     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10112     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10113   }
10114   
10115   // Otherwise, this is safe to transform!
10116   
10117   Value *InLHS = FirstInst->getOperand(0);
10118   Value *InRHS = FirstInst->getOperand(1);
10119   PHINode *NewLHS = 0, *NewRHS = 0;
10120   if (LHSVal == 0) {
10121     NewLHS = PHINode::Create(LHSType,
10122                              FirstInst->getOperand(0)->getName() + ".pn");
10123     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10124     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10125     InsertNewInstBefore(NewLHS, PN);
10126     LHSVal = NewLHS;
10127   }
10128   
10129   if (RHSVal == 0) {
10130     NewRHS = PHINode::Create(RHSType,
10131                              FirstInst->getOperand(1)->getName() + ".pn");
10132     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10133     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10134     InsertNewInstBefore(NewRHS, PN);
10135     RHSVal = NewRHS;
10136   }
10137   
10138   // Add all operands to the new PHIs.
10139   if (NewLHS || NewRHS) {
10140     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10141       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10142       if (NewLHS) {
10143         Value *NewInLHS = InInst->getOperand(0);
10144         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10145       }
10146       if (NewRHS) {
10147         Value *NewInRHS = InInst->getOperand(1);
10148         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10149       }
10150     }
10151   }
10152     
10153   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10154     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10155   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10156   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10157                          RHSVal);
10158 }
10159
10160 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10161   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10162   
10163   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10164                                         FirstInst->op_end());
10165   
10166   // Scan to see if all operands are the same opcode, all have one use, and all
10167   // kill their operands (i.e. the operands have one use).
10168   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10169     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10170     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10171       GEP->getNumOperands() != FirstInst->getNumOperands())
10172       return 0;
10173
10174     // Compare the operand lists.
10175     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10176       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10177         continue;
10178       
10179       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10180       // if one of the PHIs has a constant for the index.  The index may be
10181       // substantially cheaper to compute for the constants, so making it a
10182       // variable index could pessimize the path.  This also handles the case
10183       // for struct indices, which must always be constant.
10184       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10185           isa<ConstantInt>(GEP->getOperand(op)))
10186         return 0;
10187       
10188       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10189         return 0;
10190       FixedOperands[op] = 0;  // Needs a PHI.
10191     }
10192   }
10193   
10194   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10195   // that is variable.
10196   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10197   
10198   bool HasAnyPHIs = false;
10199   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10200     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10201     Value *FirstOp = FirstInst->getOperand(i);
10202     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10203                                      FirstOp->getName()+".pn");
10204     InsertNewInstBefore(NewPN, PN);
10205     
10206     NewPN->reserveOperandSpace(e);
10207     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10208     OperandPhis[i] = NewPN;
10209     FixedOperands[i] = NewPN;
10210     HasAnyPHIs = true;
10211   }
10212
10213   
10214   // Add all operands to the new PHIs.
10215   if (HasAnyPHIs) {
10216     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10217       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10218       BasicBlock *InBB = PN.getIncomingBlock(i);
10219       
10220       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10221         if (PHINode *OpPhi = OperandPhis[op])
10222           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10223     }
10224   }
10225   
10226   Value *Base = FixedOperands[0];
10227   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10228                                    FixedOperands.end());
10229 }
10230
10231
10232 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10233 /// of the block that defines it.  This means that it must be obvious the value
10234 /// of the load is not changed from the point of the load to the end of the
10235 /// block it is in.
10236 ///
10237 /// Finally, it is safe, but not profitable, to sink a load targetting a
10238 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10239 /// to a register.
10240 static bool isSafeToSinkLoad(LoadInst *L) {
10241   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10242   
10243   for (++BBI; BBI != E; ++BBI)
10244     if (BBI->mayWriteToMemory())
10245       return false;
10246   
10247   // Check for non-address taken alloca.  If not address-taken already, it isn't
10248   // profitable to do this xform.
10249   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10250     bool isAddressTaken = false;
10251     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10252          UI != E; ++UI) {
10253       if (isa<LoadInst>(UI)) continue;
10254       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10255         // If storing TO the alloca, then the address isn't taken.
10256         if (SI->getOperand(1) == AI) continue;
10257       }
10258       isAddressTaken = true;
10259       break;
10260     }
10261     
10262     if (!isAddressTaken)
10263       return false;
10264   }
10265   
10266   return true;
10267 }
10268
10269
10270 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10271 // operator and they all are only used by the PHI, PHI together their
10272 // inputs, and do the operation once, to the result of the PHI.
10273 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10274   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10275
10276   // Scan the instruction, looking for input operations that can be folded away.
10277   // If all input operands to the phi are the same instruction (e.g. a cast from
10278   // the same type or "+42") we can pull the operation through the PHI, reducing
10279   // code size and simplifying code.
10280   Constant *ConstantOp = 0;
10281   const Type *CastSrcTy = 0;
10282   bool isVolatile = false;
10283   if (isa<CastInst>(FirstInst)) {
10284     CastSrcTy = FirstInst->getOperand(0)->getType();
10285   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10286     // Can fold binop, compare or shift here if the RHS is a constant, 
10287     // otherwise call FoldPHIArgBinOpIntoPHI.
10288     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10289     if (ConstantOp == 0)
10290       return FoldPHIArgBinOpIntoPHI(PN);
10291   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10292     isVolatile = LI->isVolatile();
10293     // We can't sink the load if the loaded value could be modified between the
10294     // load and the PHI.
10295     if (LI->getParent() != PN.getIncomingBlock(0) ||
10296         !isSafeToSinkLoad(LI))
10297       return 0;
10298     
10299     // If the PHI is of volatile loads and the load block has multiple
10300     // successors, sinking it would remove a load of the volatile value from
10301     // the path through the other successor.
10302     if (isVolatile &&
10303         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10304       return 0;
10305     
10306   } else if (isa<GetElementPtrInst>(FirstInst)) {
10307     return FoldPHIArgGEPIntoPHI(PN);
10308   } else {
10309     return 0;  // Cannot fold this operation.
10310   }
10311
10312   // Check to see if all arguments are the same operation.
10313   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10314     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10315     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10316     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10317       return 0;
10318     if (CastSrcTy) {
10319       if (I->getOperand(0)->getType() != CastSrcTy)
10320         return 0;  // Cast operation must match.
10321     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10322       // We can't sink the load if the loaded value could be modified between 
10323       // the load and the PHI.
10324       if (LI->isVolatile() != isVolatile ||
10325           LI->getParent() != PN.getIncomingBlock(i) ||
10326           !isSafeToSinkLoad(LI))
10327         return 0;
10328       
10329       // If the PHI is of volatile loads and the load block has multiple
10330       // successors, sinking it would remove a load of the volatile value from
10331       // the path through the other successor.
10332       if (isVolatile &&
10333           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10334         return 0;
10335
10336       
10337     } else if (I->getOperand(1) != ConstantOp) {
10338       return 0;
10339     }
10340   }
10341
10342   // Okay, they are all the same operation.  Create a new PHI node of the
10343   // correct type, and PHI together all of the LHS's of the instructions.
10344   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10345                                    PN.getName()+".in");
10346   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10347
10348   Value *InVal = FirstInst->getOperand(0);
10349   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10350
10351   // Add all operands to the new PHI.
10352   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10353     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10354     if (NewInVal != InVal)
10355       InVal = 0;
10356     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10357   }
10358
10359   Value *PhiVal;
10360   if (InVal) {
10361     // The new PHI unions all of the same values together.  This is really
10362     // common, so we handle it intelligently here for compile-time speed.
10363     PhiVal = InVal;
10364     delete NewPN;
10365   } else {
10366     InsertNewInstBefore(NewPN, PN);
10367     PhiVal = NewPN;
10368   }
10369
10370   // Insert and return the new operation.
10371   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10372     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10373   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10374     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10375   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10376     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10377                            PhiVal, ConstantOp);
10378   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10379   
10380   // If this was a volatile load that we are merging, make sure to loop through
10381   // and mark all the input loads as non-volatile.  If we don't do this, we will
10382   // insert a new volatile load and the old ones will not be deletable.
10383   if (isVolatile)
10384     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10385       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10386   
10387   return new LoadInst(PhiVal, "", isVolatile);
10388 }
10389
10390 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10391 /// that is dead.
10392 static bool DeadPHICycle(PHINode *PN,
10393                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10394   if (PN->use_empty()) return true;
10395   if (!PN->hasOneUse()) return false;
10396
10397   // Remember this node, and if we find the cycle, return.
10398   if (!PotentiallyDeadPHIs.insert(PN))
10399     return true;
10400   
10401   // Don't scan crazily complex things.
10402   if (PotentiallyDeadPHIs.size() == 16)
10403     return false;
10404
10405   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10406     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10407
10408   return false;
10409 }
10410
10411 /// PHIsEqualValue - Return true if this phi node is always equal to
10412 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10413 ///   z = some value; x = phi (y, z); y = phi (x, z)
10414 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10415                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10416   // See if we already saw this PHI node.
10417   if (!ValueEqualPHIs.insert(PN))
10418     return true;
10419   
10420   // Don't scan crazily complex things.
10421   if (ValueEqualPHIs.size() == 16)
10422     return false;
10423  
10424   // Scan the operands to see if they are either phi nodes or are equal to
10425   // the value.
10426   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10427     Value *Op = PN->getIncomingValue(i);
10428     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10429       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10430         return false;
10431     } else if (Op != NonPhiInVal)
10432       return false;
10433   }
10434   
10435   return true;
10436 }
10437
10438
10439 // PHINode simplification
10440 //
10441 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10442   // If LCSSA is around, don't mess with Phi nodes
10443   if (MustPreserveLCSSA) return 0;
10444   
10445   if (Value *V = PN.hasConstantValue())
10446     return ReplaceInstUsesWith(PN, V);
10447
10448   // If all PHI operands are the same operation, pull them through the PHI,
10449   // reducing code size.
10450   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10451       isa<Instruction>(PN.getIncomingValue(1)) &&
10452       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10453       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10454       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10455       // than themselves more than once.
10456       PN.getIncomingValue(0)->hasOneUse())
10457     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10458       return Result;
10459
10460   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10461   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10462   // PHI)... break the cycle.
10463   if (PN.hasOneUse()) {
10464     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10465     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10466       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10467       PotentiallyDeadPHIs.insert(&PN);
10468       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10469         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10470     }
10471    
10472     // If this phi has a single use, and if that use just computes a value for
10473     // the next iteration of a loop, delete the phi.  This occurs with unused
10474     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10475     // common case here is good because the only other things that catch this
10476     // are induction variable analysis (sometimes) and ADCE, which is only run
10477     // late.
10478     if (PHIUser->hasOneUse() &&
10479         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10480         PHIUser->use_back() == &PN) {
10481       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10482     }
10483   }
10484
10485   // We sometimes end up with phi cycles that non-obviously end up being the
10486   // same value, for example:
10487   //   z = some value; x = phi (y, z); y = phi (x, z)
10488   // where the phi nodes don't necessarily need to be in the same block.  Do a
10489   // quick check to see if the PHI node only contains a single non-phi value, if
10490   // so, scan to see if the phi cycle is actually equal to that value.
10491   {
10492     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10493     // Scan for the first non-phi operand.
10494     while (InValNo != NumOperandVals && 
10495            isa<PHINode>(PN.getIncomingValue(InValNo)))
10496       ++InValNo;
10497
10498     if (InValNo != NumOperandVals) {
10499       Value *NonPhiInVal = PN.getOperand(InValNo);
10500       
10501       // Scan the rest of the operands to see if there are any conflicts, if so
10502       // there is no need to recursively scan other phis.
10503       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10504         Value *OpVal = PN.getIncomingValue(InValNo);
10505         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10506           break;
10507       }
10508       
10509       // If we scanned over all operands, then we have one unique value plus
10510       // phi values.  Scan PHI nodes to see if they all merge in each other or
10511       // the value.
10512       if (InValNo == NumOperandVals) {
10513         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10514         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10515           return ReplaceInstUsesWith(PN, NonPhiInVal);
10516       }
10517     }
10518   }
10519   return 0;
10520 }
10521
10522 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10523                                    Instruction *InsertPoint,
10524                                    InstCombiner *IC) {
10525   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10526   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10527   // We must cast correctly to the pointer type. Ensure that we
10528   // sign extend the integer value if it is smaller as this is
10529   // used for address computation.
10530   Instruction::CastOps opcode = 
10531      (VTySize < PtrSize ? Instruction::SExt :
10532       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10533   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10534 }
10535
10536
10537 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10538   Value *PtrOp = GEP.getOperand(0);
10539   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10540   // If so, eliminate the noop.
10541   if (GEP.getNumOperands() == 1)
10542     return ReplaceInstUsesWith(GEP, PtrOp);
10543
10544   if (isa<UndefValue>(GEP.getOperand(0)))
10545     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10546
10547   bool HasZeroPointerIndex = false;
10548   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10549     HasZeroPointerIndex = C->isNullValue();
10550
10551   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10552     return ReplaceInstUsesWith(GEP, PtrOp);
10553
10554   // Eliminate unneeded casts for indices.
10555   bool MadeChange = false;
10556   
10557   gep_type_iterator GTI = gep_type_begin(GEP);
10558   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10559        i != e; ++i, ++GTI) {
10560     if (isa<SequentialType>(*GTI)) {
10561       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10562         if (CI->getOpcode() == Instruction::ZExt ||
10563             CI->getOpcode() == Instruction::SExt) {
10564           const Type *SrcTy = CI->getOperand(0)->getType();
10565           // We can eliminate a cast from i32 to i64 iff the target 
10566           // is a 32-bit pointer target.
10567           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10568             MadeChange = true;
10569             *i = CI->getOperand(0);
10570           }
10571         }
10572       }
10573       // If we are using a wider index than needed for this platform, shrink it
10574       // to what we need.  If narrower, sign-extend it to what we need.
10575       // If the incoming value needs a cast instruction,
10576       // insert it.  This explicit cast can make subsequent optimizations more
10577       // obvious.
10578       Value *Op = *i;
10579       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10580         if (Constant *C = dyn_cast<Constant>(Op)) {
10581           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10582           MadeChange = true;
10583         } else {
10584           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10585                                 GEP);
10586           *i = Op;
10587           MadeChange = true;
10588         }
10589       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10590         if (Constant *C = dyn_cast<Constant>(Op)) {
10591           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10592           MadeChange = true;
10593         } else {
10594           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10595                                 GEP);
10596           *i = Op;
10597           MadeChange = true;
10598         }
10599       }
10600     }
10601   }
10602   if (MadeChange) return &GEP;
10603
10604   // Combine Indices - If the source pointer to this getelementptr instruction
10605   // is a getelementptr instruction, combine the indices of the two
10606   // getelementptr instructions into a single instruction.
10607   //
10608   SmallVector<Value*, 8> SrcGEPOperands;
10609   if (User *Src = dyn_castGetElementPtr(PtrOp))
10610     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10611
10612   if (!SrcGEPOperands.empty()) {
10613     // Note that if our source is a gep chain itself that we wait for that
10614     // chain to be resolved before we perform this transformation.  This
10615     // avoids us creating a TON of code in some cases.
10616     //
10617     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10618         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10619       return 0;   // Wait until our source is folded to completion.
10620
10621     SmallVector<Value*, 8> Indices;
10622
10623     // Find out whether the last index in the source GEP is a sequential idx.
10624     bool EndsWithSequential = false;
10625     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10626            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10627       EndsWithSequential = !isa<StructType>(*I);
10628
10629     // Can we combine the two pointer arithmetics offsets?
10630     if (EndsWithSequential) {
10631       // Replace: gep (gep %P, long B), long A, ...
10632       // With:    T = long A+B; gep %P, T, ...
10633       //
10634       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10635       if (SO1 == Constant::getNullValue(SO1->getType())) {
10636         Sum = GO1;
10637       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10638         Sum = SO1;
10639       } else {
10640         // If they aren't the same type, convert both to an integer of the
10641         // target's pointer size.
10642         if (SO1->getType() != GO1->getType()) {
10643           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10644             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10645           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10646             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10647           } else {
10648             unsigned PS = TD->getPointerSizeInBits();
10649             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10650               // Convert GO1 to SO1's type.
10651               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10652
10653             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10654               // Convert SO1 to GO1's type.
10655               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10656             } else {
10657               const Type *PT = TD->getIntPtrType();
10658               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10659               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10660             }
10661           }
10662         }
10663         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10664           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10665         else {
10666           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10667           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10668         }
10669       }
10670
10671       // Recycle the GEP we already have if possible.
10672       if (SrcGEPOperands.size() == 2) {
10673         GEP.setOperand(0, SrcGEPOperands[0]);
10674         GEP.setOperand(1, Sum);
10675         return &GEP;
10676       } else {
10677         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10678                        SrcGEPOperands.end()-1);
10679         Indices.push_back(Sum);
10680         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10681       }
10682     } else if (isa<Constant>(*GEP.idx_begin()) &&
10683                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10684                SrcGEPOperands.size() != 1) {
10685       // Otherwise we can do the fold if the first index of the GEP is a zero
10686       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10687                      SrcGEPOperands.end());
10688       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10689     }
10690
10691     if (!Indices.empty())
10692       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10693                                        Indices.end(), GEP.getName());
10694
10695   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10696     // GEP of global variable.  If all of the indices for this GEP are
10697     // constants, we can promote this to a constexpr instead of an instruction.
10698
10699     // Scan for nonconstants...
10700     SmallVector<Constant*, 8> Indices;
10701     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10702     for (; I != E && isa<Constant>(*I); ++I)
10703       Indices.push_back(cast<Constant>(*I));
10704
10705     if (I == E) {  // If they are all constants...
10706       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10707                                                     &Indices[0],Indices.size());
10708
10709       // Replace all uses of the GEP with the new constexpr...
10710       return ReplaceInstUsesWith(GEP, CE);
10711     }
10712   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10713     if (!isa<PointerType>(X->getType())) {
10714       // Not interesting.  Source pointer must be a cast from pointer.
10715     } else if (HasZeroPointerIndex) {
10716       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10717       // into     : GEP [10 x i8]* X, i32 0, ...
10718       //
10719       // This occurs when the program declares an array extern like "int X[];"
10720       //
10721       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10722       const PointerType *XTy = cast<PointerType>(X->getType());
10723       if (const ArrayType *XATy =
10724           dyn_cast<ArrayType>(XTy->getElementType()))
10725         if (const ArrayType *CATy =
10726             dyn_cast<ArrayType>(CPTy->getElementType()))
10727           if (CATy->getElementType() == XATy->getElementType()) {
10728             // At this point, we know that the cast source type is a pointer
10729             // to an array of the same type as the destination pointer
10730             // array.  Because the array type is never stepped over (there
10731             // is a leading zero) we can fold the cast into this GEP.
10732             GEP.setOperand(0, X);
10733             return &GEP;
10734           }
10735     } else if (GEP.getNumOperands() == 2) {
10736       // Transform things like:
10737       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10738       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10739       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10740       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10741       if (isa<ArrayType>(SrcElTy) &&
10742           TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10743           TD->getTypePaddedSize(ResElTy)) {
10744         Value *Idx[2];
10745         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10746         Idx[1] = GEP.getOperand(1);
10747         Value *V = InsertNewInstBefore(
10748                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10749         // V and GEP are both pointer types --> BitCast
10750         return new BitCastInst(V, GEP.getType());
10751       }
10752       
10753       // Transform things like:
10754       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10755       //   (where tmp = 8*tmp2) into:
10756       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10757       
10758       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10759         uint64_t ArrayEltSize =
10760             TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
10761         
10762         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10763         // allow either a mul, shift, or constant here.
10764         Value *NewIdx = 0;
10765         ConstantInt *Scale = 0;
10766         if (ArrayEltSize == 1) {
10767           NewIdx = GEP.getOperand(1);
10768           Scale = ConstantInt::get(NewIdx->getType(), 1);
10769         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10770           NewIdx = ConstantInt::get(CI->getType(), 1);
10771           Scale = CI;
10772         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10773           if (Inst->getOpcode() == Instruction::Shl &&
10774               isa<ConstantInt>(Inst->getOperand(1))) {
10775             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10776             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10777             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10778             NewIdx = Inst->getOperand(0);
10779           } else if (Inst->getOpcode() == Instruction::Mul &&
10780                      isa<ConstantInt>(Inst->getOperand(1))) {
10781             Scale = cast<ConstantInt>(Inst->getOperand(1));
10782             NewIdx = Inst->getOperand(0);
10783           }
10784         }
10785         
10786         // If the index will be to exactly the right offset with the scale taken
10787         // out, perform the transformation. Note, we don't know whether Scale is
10788         // signed or not. We'll use unsigned version of division/modulo
10789         // operation after making sure Scale doesn't have the sign bit set.
10790         if (Scale && Scale->getSExtValue() >= 0LL &&
10791             Scale->getZExtValue() % ArrayEltSize == 0) {
10792           Scale = ConstantInt::get(Scale->getType(),
10793                                    Scale->getZExtValue() / ArrayEltSize);
10794           if (Scale->getZExtValue() != 1) {
10795             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10796                                                        false /*ZExt*/);
10797             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10798             NewIdx = InsertNewInstBefore(Sc, GEP);
10799           }
10800
10801           // Insert the new GEP instruction.
10802           Value *Idx[2];
10803           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10804           Idx[1] = NewIdx;
10805           Instruction *NewGEP =
10806             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10807           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10808           // The NewGEP must be pointer typed, so must the old one -> BitCast
10809           return new BitCastInst(NewGEP, GEP.getType());
10810         }
10811       }
10812     }
10813   }
10814   
10815   /// See if we can simplify:
10816   ///   X = bitcast A to B*
10817   ///   Y = gep X, <...constant indices...>
10818   /// into a gep of the original struct.  This is important for SROA and alias
10819   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
10820   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
10821     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10822       // Determine how much the GEP moves the pointer.  We are guaranteed to get
10823       // a constant back from EmitGEPOffset.
10824       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10825       int64_t Offset = OffsetV->getSExtValue();
10826       
10827       // If this GEP instruction doesn't move the pointer, just replace the GEP
10828       // with a bitcast of the real input to the dest type.
10829       if (Offset == 0) {
10830         // If the bitcast is of an allocation, and the allocation will be
10831         // converted to match the type of the cast, don't touch this.
10832         if (isa<AllocationInst>(BCI->getOperand(0))) {
10833           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10834           if (Instruction *I = visitBitCast(*BCI)) {
10835             if (I != BCI) {
10836               I->takeName(BCI);
10837               BCI->getParent()->getInstList().insert(BCI, I);
10838               ReplaceInstUsesWith(*BCI, I);
10839             }
10840             return &GEP;
10841           }
10842         }
10843         return new BitCastInst(BCI->getOperand(0), GEP.getType());
10844       }
10845       
10846       // Otherwise, if the offset is non-zero, we need to find out if there is a
10847       // field at Offset in 'A's type.  If so, we can pull the cast through the
10848       // GEP.
10849       SmallVector<Value*, 8> NewIndices;
10850       const Type *InTy =
10851         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10852       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10853         Instruction *NGEP =
10854            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10855                                      NewIndices.end());
10856         if (NGEP->getType() == GEP.getType()) return NGEP;
10857         InsertNewInstBefore(NGEP, GEP);
10858         NGEP->takeName(&GEP);
10859         return new BitCastInst(NGEP, GEP.getType());
10860       }
10861     }
10862   }    
10863     
10864   return 0;
10865 }
10866
10867 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10868   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10869   if (AI.isArrayAllocation()) {  // Check C != 1
10870     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10871       const Type *NewTy = 
10872         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10873       AllocationInst *New = 0;
10874
10875       // Create and insert the replacement instruction...
10876       if (isa<MallocInst>(AI))
10877         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10878       else {
10879         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10880         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10881       }
10882
10883       InsertNewInstBefore(New, AI);
10884
10885       // Scan to the end of the allocation instructions, to skip over a block of
10886       // allocas if possible...
10887       //
10888       BasicBlock::iterator It = New;
10889       while (isa<AllocationInst>(*It)) ++It;
10890
10891       // Now that I is pointing to the first non-allocation-inst in the block,
10892       // insert our getelementptr instruction...
10893       //
10894       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10895       Value *Idx[2];
10896       Idx[0] = NullIdx;
10897       Idx[1] = NullIdx;
10898       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10899                                            New->getName()+".sub", It);
10900
10901       // Now make everything use the getelementptr instead of the original
10902       // allocation.
10903       return ReplaceInstUsesWith(AI, V);
10904     } else if (isa<UndefValue>(AI.getArraySize())) {
10905       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10906     }
10907   }
10908
10909   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10910     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10911     // Note that we only do this for alloca's, because malloc should allocate and
10912     // return a unique pointer, even for a zero byte allocation.
10913     if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10914       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10915
10916     // If the alignment is 0 (unspecified), assign it the preferred alignment.
10917     if (AI.getAlignment() == 0)
10918       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10919   }
10920
10921   return 0;
10922 }
10923
10924 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10925   Value *Op = FI.getOperand(0);
10926
10927   // free undef -> unreachable.
10928   if (isa<UndefValue>(Op)) {
10929     // Insert a new store to null because we cannot modify the CFG here.
10930     new StoreInst(ConstantInt::getTrue(),
10931                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10932     return EraseInstFromFunction(FI);
10933   }
10934   
10935   // If we have 'free null' delete the instruction.  This can happen in stl code
10936   // when lots of inlining happens.
10937   if (isa<ConstantPointerNull>(Op))
10938     return EraseInstFromFunction(FI);
10939   
10940   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10941   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10942     FI.setOperand(0, CI->getOperand(0));
10943     return &FI;
10944   }
10945   
10946   // Change free (gep X, 0,0,0,0) into free(X)
10947   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10948     if (GEPI->hasAllZeroIndices()) {
10949       AddToWorkList(GEPI);
10950       FI.setOperand(0, GEPI->getOperand(0));
10951       return &FI;
10952     }
10953   }
10954   
10955   // Change free(malloc) into nothing, if the malloc has a single use.
10956   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10957     if (MI->hasOneUse()) {
10958       EraseInstFromFunction(FI);
10959       return EraseInstFromFunction(*MI);
10960     }
10961
10962   return 0;
10963 }
10964
10965
10966 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10967 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10968                                         const TargetData *TD) {
10969   User *CI = cast<User>(LI.getOperand(0));
10970   Value *CastOp = CI->getOperand(0);
10971
10972   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10973     // Instead of loading constant c string, use corresponding integer value
10974     // directly if string length is small enough.
10975     std::string Str;
10976     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10977       unsigned len = Str.length();
10978       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10979       unsigned numBits = Ty->getPrimitiveSizeInBits();
10980       // Replace LI with immediate integer store.
10981       if ((numBits >> 3) == len + 1) {
10982         APInt StrVal(numBits, 0);
10983         APInt SingleChar(numBits, 0);
10984         if (TD->isLittleEndian()) {
10985           for (signed i = len-1; i >= 0; i--) {
10986             SingleChar = (uint64_t) Str[i];
10987             StrVal = (StrVal << 8) | SingleChar;
10988           }
10989         } else {
10990           for (unsigned i = 0; i < len; i++) {
10991             SingleChar = (uint64_t) Str[i];
10992             StrVal = (StrVal << 8) | SingleChar;
10993           }
10994           // Append NULL at the end.
10995           SingleChar = 0;
10996           StrVal = (StrVal << 8) | SingleChar;
10997         }
10998         Value *NL = ConstantInt::get(StrVal);
10999         return IC.ReplaceInstUsesWith(LI, NL);
11000       }
11001     }
11002   }
11003
11004   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11005   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11006     const Type *SrcPTy = SrcTy->getElementType();
11007
11008     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11009          isa<VectorType>(DestPTy)) {
11010       // If the source is an array, the code below will not succeed.  Check to
11011       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11012       // constants.
11013       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11014         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11015           if (ASrcTy->getNumElements() != 0) {
11016             Value *Idxs[2];
11017             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11018             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11019             SrcTy = cast<PointerType>(CastOp->getType());
11020             SrcPTy = SrcTy->getElementType();
11021           }
11022
11023       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11024             isa<VectorType>(SrcPTy)) &&
11025           // Do not allow turning this into a load of an integer, which is then
11026           // casted to a pointer, this pessimizes pointer analysis a lot.
11027           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11028           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11029                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11030
11031         // Okay, we are casting from one integer or pointer type to another of
11032         // the same size.  Instead of casting the pointer before the load, cast
11033         // the result of the loaded value.
11034         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11035                                                              CI->getName(),
11036                                                          LI.isVolatile()),LI);
11037         // Now cast the result of the load.
11038         return new BitCastInst(NewLoad, LI.getType());
11039       }
11040     }
11041   }
11042   return 0;
11043 }
11044
11045 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
11046 /// from this value cannot trap.  If it is not obviously safe to load from the
11047 /// specified pointer, we do a quick local scan of the basic block containing
11048 /// ScanFrom, to determine if the address is already accessed.
11049 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
11050   // If it is an alloca it is always safe to load from.
11051   if (isa<AllocaInst>(V)) return true;
11052
11053   // If it is a global variable it is mostly safe to load from.
11054   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
11055     // Don't try to evaluate aliases.  External weak GV can be null.
11056     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
11057
11058   // Otherwise, be a little bit agressive by scanning the local block where we
11059   // want to check to see if the pointer is already being loaded or stored
11060   // from/to.  If so, the previous load or store would have already trapped,
11061   // so there is no harm doing an extra load (also, CSE will later eliminate
11062   // the load entirely).
11063   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11064
11065   while (BBI != E) {
11066     --BBI;
11067
11068     // If we see a free or a call (which might do a free) the pointer could be
11069     // marked invalid.
11070     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
11071       return false;
11072     
11073     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11074       if (LI->getOperand(0) == V) return true;
11075     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11076       if (SI->getOperand(1) == V) return true;
11077     }
11078
11079   }
11080   return false;
11081 }
11082
11083 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11084   Value *Op = LI.getOperand(0);
11085
11086   // Attempt to improve the alignment.
11087   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
11088   if (KnownAlign >
11089       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11090                                 LI.getAlignment()))
11091     LI.setAlignment(KnownAlign);
11092
11093   // load (cast X) --> cast (load X) iff safe
11094   if (isa<CastInst>(Op))
11095     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11096       return Res;
11097
11098   // None of the following transforms are legal for volatile loads.
11099   if (LI.isVolatile()) return 0;
11100   
11101   // Do really simple store-to-load forwarding and load CSE, to catch cases
11102   // where there are several consequtive memory accesses to the same location,
11103   // separated by a few arithmetic operations.
11104   BasicBlock::iterator BBI = &LI;
11105   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11106     return ReplaceInstUsesWith(LI, AvailableVal);
11107
11108   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11109     const Value *GEPI0 = GEPI->getOperand(0);
11110     // TODO: Consider a target hook for valid address spaces for this xform.
11111     if (isa<ConstantPointerNull>(GEPI0) &&
11112         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11113       // Insert a new store to null instruction before the load to indicate
11114       // that this code is not reachable.  We do this instead of inserting
11115       // an unreachable instruction directly because we cannot modify the
11116       // CFG.
11117       new StoreInst(UndefValue::get(LI.getType()),
11118                     Constant::getNullValue(Op->getType()), &LI);
11119       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11120     }
11121   } 
11122
11123   if (Constant *C = dyn_cast<Constant>(Op)) {
11124     // load null/undef -> undef
11125     // TODO: Consider a target hook for valid address spaces for this xform.
11126     if (isa<UndefValue>(C) || (C->isNullValue() && 
11127         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11128       // Insert a new store to null instruction before the load to indicate that
11129       // this code is not reachable.  We do this instead of inserting an
11130       // unreachable instruction directly because we cannot modify the CFG.
11131       new StoreInst(UndefValue::get(LI.getType()),
11132                     Constant::getNullValue(Op->getType()), &LI);
11133       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11134     }
11135
11136     // Instcombine load (constant global) into the value loaded.
11137     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11138       if (GV->isConstant() && !GV->isDeclaration())
11139         return ReplaceInstUsesWith(LI, GV->getInitializer());
11140
11141     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11142     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11143       if (CE->getOpcode() == Instruction::GetElementPtr) {
11144         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11145           if (GV->isConstant() && !GV->isDeclaration())
11146             if (Constant *V = 
11147                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11148               return ReplaceInstUsesWith(LI, V);
11149         if (CE->getOperand(0)->isNullValue()) {
11150           // Insert a new store to null instruction before the load to indicate
11151           // that this code is not reachable.  We do this instead of inserting
11152           // an unreachable instruction directly because we cannot modify the
11153           // CFG.
11154           new StoreInst(UndefValue::get(LI.getType()),
11155                         Constant::getNullValue(Op->getType()), &LI);
11156           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11157         }
11158
11159       } else if (CE->isCast()) {
11160         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11161           return Res;
11162       }
11163     }
11164   }
11165     
11166   // If this load comes from anywhere in a constant global, and if the global
11167   // is all undef or zero, we know what it loads.
11168   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11169     if (GV->isConstant() && GV->hasInitializer()) {
11170       if (GV->getInitializer()->isNullValue())
11171         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11172       else if (isa<UndefValue>(GV->getInitializer()))
11173         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11174     }
11175   }
11176
11177   if (Op->hasOneUse()) {
11178     // Change select and PHI nodes to select values instead of addresses: this
11179     // helps alias analysis out a lot, allows many others simplifications, and
11180     // exposes redundancy in the code.
11181     //
11182     // Note that we cannot do the transformation unless we know that the
11183     // introduced loads cannot trap!  Something like this is valid as long as
11184     // the condition is always false: load (select bool %C, int* null, int* %G),
11185     // but it would not be valid if we transformed it to load from null
11186     // unconditionally.
11187     //
11188     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11189       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11190       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11191           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11192         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11193                                      SI->getOperand(1)->getName()+".val"), LI);
11194         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11195                                      SI->getOperand(2)->getName()+".val"), LI);
11196         return SelectInst::Create(SI->getCondition(), V1, V2);
11197       }
11198
11199       // load (select (cond, null, P)) -> load P
11200       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11201         if (C->isNullValue()) {
11202           LI.setOperand(0, SI->getOperand(2));
11203           return &LI;
11204         }
11205
11206       // load (select (cond, P, null)) -> load P
11207       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11208         if (C->isNullValue()) {
11209           LI.setOperand(0, SI->getOperand(1));
11210           return &LI;
11211         }
11212     }
11213   }
11214   return 0;
11215 }
11216
11217 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11218 /// when possible.  This makes it generally easy to do alias analysis and/or
11219 /// SROA/mem2reg of the memory object.
11220 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11221   User *CI = cast<User>(SI.getOperand(1));
11222   Value *CastOp = CI->getOperand(0);
11223
11224   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11225   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11226   if (SrcTy == 0) return 0;
11227   
11228   const Type *SrcPTy = SrcTy->getElementType();
11229
11230   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11231     return 0;
11232   
11233   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11234   /// to its first element.  This allows us to handle things like:
11235   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11236   /// on 32-bit hosts.
11237   SmallVector<Value*, 4> NewGEPIndices;
11238   
11239   // If the source is an array, the code below will not succeed.  Check to
11240   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11241   // constants.
11242   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11243     // Index through pointer.
11244     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11245     NewGEPIndices.push_back(Zero);
11246     
11247     while (1) {
11248       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11249         if (!STy->getNumElements()) /* Struct can be empty {} */
11250           break;
11251         NewGEPIndices.push_back(Zero);
11252         SrcPTy = STy->getElementType(0);
11253       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11254         NewGEPIndices.push_back(Zero);
11255         SrcPTy = ATy->getElementType();
11256       } else {
11257         break;
11258       }
11259     }
11260     
11261     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11262   }
11263
11264   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11265     return 0;
11266   
11267   // If the pointers point into different address spaces or if they point to
11268   // values with different sizes, we can't do the transformation.
11269   if (SrcTy->getAddressSpace() != 
11270         cast<PointerType>(CI->getType())->getAddressSpace() ||
11271       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11272       IC.getTargetData().getTypeSizeInBits(DestPTy))
11273     return 0;
11274
11275   // Okay, we are casting from one integer or pointer type to another of
11276   // the same size.  Instead of casting the pointer before 
11277   // the store, cast the value to be stored.
11278   Value *NewCast;
11279   Value *SIOp0 = SI.getOperand(0);
11280   Instruction::CastOps opcode = Instruction::BitCast;
11281   const Type* CastSrcTy = SIOp0->getType();
11282   const Type* CastDstTy = SrcPTy;
11283   if (isa<PointerType>(CastDstTy)) {
11284     if (CastSrcTy->isInteger())
11285       opcode = Instruction::IntToPtr;
11286   } else if (isa<IntegerType>(CastDstTy)) {
11287     if (isa<PointerType>(SIOp0->getType()))
11288       opcode = Instruction::PtrToInt;
11289   }
11290   
11291   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11292   // emit a GEP to index into its first field.
11293   if (!NewGEPIndices.empty()) {
11294     if (Constant *C = dyn_cast<Constant>(CastOp))
11295       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11296                                               NewGEPIndices.size());
11297     else
11298       CastOp = IC.InsertNewInstBefore(
11299               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11300                                         NewGEPIndices.end()), SI);
11301   }
11302   
11303   if (Constant *C = dyn_cast<Constant>(SIOp0))
11304     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11305   else
11306     NewCast = IC.InsertNewInstBefore(
11307       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11308       SI);
11309   return new StoreInst(NewCast, CastOp);
11310 }
11311
11312 /// equivalentAddressValues - Test if A and B will obviously have the same
11313 /// value. This includes recognizing that %t0 and %t1 will have the same
11314 /// value in code like this:
11315 ///   %t0 = getelementptr @a, 0, 3
11316 ///   store i32 0, i32* %t0
11317 ///   %t1 = getelementptr @a, 0, 3
11318 ///   %t2 = load i32* %t1
11319 ///
11320 static bool equivalentAddressValues(Value *A, Value *B) {
11321   // Test if the values are trivially equivalent.
11322   if (A == B) return true;
11323   
11324   // Test if the values come form identical arithmetic instructions.
11325   if (isa<BinaryOperator>(A) ||
11326       isa<CastInst>(A) ||
11327       isa<PHINode>(A) ||
11328       isa<GetElementPtrInst>(A))
11329     if (Instruction *BI = dyn_cast<Instruction>(B))
11330       if (cast<Instruction>(A)->isIdenticalTo(BI))
11331         return true;
11332   
11333   // Otherwise they may not be equivalent.
11334   return false;
11335 }
11336
11337 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11338   Value *Val = SI.getOperand(0);
11339   Value *Ptr = SI.getOperand(1);
11340
11341   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11342     EraseInstFromFunction(SI);
11343     ++NumCombined;
11344     return 0;
11345   }
11346   
11347   // If the RHS is an alloca with a single use, zapify the store, making the
11348   // alloca dead.
11349   if (Ptr->hasOneUse() && !SI.isVolatile()) {
11350     if (isa<AllocaInst>(Ptr)) {
11351       EraseInstFromFunction(SI);
11352       ++NumCombined;
11353       return 0;
11354     }
11355     
11356     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11357       if (isa<AllocaInst>(GEP->getOperand(0)) &&
11358           GEP->getOperand(0)->hasOneUse()) {
11359         EraseInstFromFunction(SI);
11360         ++NumCombined;
11361         return 0;
11362       }
11363   }
11364
11365   // Attempt to improve the alignment.
11366   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11367   if (KnownAlign >
11368       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11369                                 SI.getAlignment()))
11370     SI.setAlignment(KnownAlign);
11371
11372   // Do really simple DSE, to catch cases where there are several consequtive
11373   // stores to the same location, separated by a few arithmetic operations. This
11374   // situation often occurs with bitfield accesses.
11375   BasicBlock::iterator BBI = &SI;
11376   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11377        --ScanInsts) {
11378     --BBI;
11379     
11380     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11381       // Prev store isn't volatile, and stores to the same location?
11382       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11383                                                           SI.getOperand(1))) {
11384         ++NumDeadStore;
11385         ++BBI;
11386         EraseInstFromFunction(*PrevSI);
11387         continue;
11388       }
11389       break;
11390     }
11391     
11392     // If this is a load, we have to stop.  However, if the loaded value is from
11393     // the pointer we're loading and is producing the pointer we're storing,
11394     // then *this* store is dead (X = load P; store X -> P).
11395     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11396       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11397           !SI.isVolatile()) {
11398         EraseInstFromFunction(SI);
11399         ++NumCombined;
11400         return 0;
11401       }
11402       // Otherwise, this is a load from some other location.  Stores before it
11403       // may not be dead.
11404       break;
11405     }
11406     
11407     // Don't skip over loads or things that can modify memory.
11408     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11409       break;
11410   }
11411   
11412   
11413   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11414
11415   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11416   if (isa<ConstantPointerNull>(Ptr)) {
11417     if (!isa<UndefValue>(Val)) {
11418       SI.setOperand(0, UndefValue::get(Val->getType()));
11419       if (Instruction *U = dyn_cast<Instruction>(Val))
11420         AddToWorkList(U);  // Dropped a use.
11421       ++NumCombined;
11422     }
11423     return 0;  // Do not modify these!
11424   }
11425
11426   // store undef, Ptr -> noop
11427   if (isa<UndefValue>(Val)) {
11428     EraseInstFromFunction(SI);
11429     ++NumCombined;
11430     return 0;
11431   }
11432
11433   // If the pointer destination is a cast, see if we can fold the cast into the
11434   // source instead.
11435   if (isa<CastInst>(Ptr))
11436     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11437       return Res;
11438   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11439     if (CE->isCast())
11440       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11441         return Res;
11442
11443   
11444   // If this store is the last instruction in the basic block, and if the block
11445   // ends with an unconditional branch, try to move it to the successor block.
11446   BBI = &SI; ++BBI;
11447   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11448     if (BI->isUnconditional())
11449       if (SimplifyStoreAtEndOfBlock(SI))
11450         return 0;  // xform done!
11451   
11452   return 0;
11453 }
11454
11455 /// SimplifyStoreAtEndOfBlock - Turn things like:
11456 ///   if () { *P = v1; } else { *P = v2 }
11457 /// into a phi node with a store in the successor.
11458 ///
11459 /// Simplify things like:
11460 ///   *P = v1; if () { *P = v2; }
11461 /// into a phi node with a store in the successor.
11462 ///
11463 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11464   BasicBlock *StoreBB = SI.getParent();
11465   
11466   // Check to see if the successor block has exactly two incoming edges.  If
11467   // so, see if the other predecessor contains a store to the same location.
11468   // if so, insert a PHI node (if needed) and move the stores down.
11469   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11470   
11471   // Determine whether Dest has exactly two predecessors and, if so, compute
11472   // the other predecessor.
11473   pred_iterator PI = pred_begin(DestBB);
11474   BasicBlock *OtherBB = 0;
11475   if (*PI != StoreBB)
11476     OtherBB = *PI;
11477   ++PI;
11478   if (PI == pred_end(DestBB))
11479     return false;
11480   
11481   if (*PI != StoreBB) {
11482     if (OtherBB)
11483       return false;
11484     OtherBB = *PI;
11485   }
11486   if (++PI != pred_end(DestBB))
11487     return false;
11488
11489   // Bail out if all the relevant blocks aren't distinct (this can happen,
11490   // for example, if SI is in an infinite loop)
11491   if (StoreBB == DestBB || OtherBB == DestBB)
11492     return false;
11493
11494   // Verify that the other block ends in a branch and is not otherwise empty.
11495   BasicBlock::iterator BBI = OtherBB->getTerminator();
11496   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11497   if (!OtherBr || BBI == OtherBB->begin())
11498     return false;
11499   
11500   // If the other block ends in an unconditional branch, check for the 'if then
11501   // else' case.  there is an instruction before the branch.
11502   StoreInst *OtherStore = 0;
11503   if (OtherBr->isUnconditional()) {
11504     // If this isn't a store, or isn't a store to the same location, bail out.
11505     --BBI;
11506     OtherStore = dyn_cast<StoreInst>(BBI);
11507     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11508       return false;
11509   } else {
11510     // Otherwise, the other block ended with a conditional branch. If one of the
11511     // destinations is StoreBB, then we have the if/then case.
11512     if (OtherBr->getSuccessor(0) != StoreBB && 
11513         OtherBr->getSuccessor(1) != StoreBB)
11514       return false;
11515     
11516     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11517     // if/then triangle.  See if there is a store to the same ptr as SI that
11518     // lives in OtherBB.
11519     for (;; --BBI) {
11520       // Check to see if we find the matching store.
11521       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11522         if (OtherStore->getOperand(1) != SI.getOperand(1))
11523           return false;
11524         break;
11525       }
11526       // If we find something that may be using or overwriting the stored
11527       // value, or if we run out of instructions, we can't do the xform.
11528       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11529           BBI == OtherBB->begin())
11530         return false;
11531     }
11532     
11533     // In order to eliminate the store in OtherBr, we have to
11534     // make sure nothing reads or overwrites the stored value in
11535     // StoreBB.
11536     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11537       // FIXME: This should really be AA driven.
11538       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11539         return false;
11540     }
11541   }
11542   
11543   // Insert a PHI node now if we need it.
11544   Value *MergedVal = OtherStore->getOperand(0);
11545   if (MergedVal != SI.getOperand(0)) {
11546     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11547     PN->reserveOperandSpace(2);
11548     PN->addIncoming(SI.getOperand(0), SI.getParent());
11549     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11550     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11551   }
11552   
11553   // Advance to a place where it is safe to insert the new store and
11554   // insert it.
11555   BBI = DestBB->getFirstNonPHI();
11556   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11557                                     OtherStore->isVolatile()), *BBI);
11558   
11559   // Nuke the old stores.
11560   EraseInstFromFunction(SI);
11561   EraseInstFromFunction(*OtherStore);
11562   ++NumCombined;
11563   return true;
11564 }
11565
11566
11567 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11568   // Change br (not X), label True, label False to: br X, label False, True
11569   Value *X = 0;
11570   BasicBlock *TrueDest;
11571   BasicBlock *FalseDest;
11572   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11573       !isa<Constant>(X)) {
11574     // Swap Destinations and condition...
11575     BI.setCondition(X);
11576     BI.setSuccessor(0, FalseDest);
11577     BI.setSuccessor(1, TrueDest);
11578     return &BI;
11579   }
11580
11581   // Cannonicalize fcmp_one -> fcmp_oeq
11582   FCmpInst::Predicate FPred; Value *Y;
11583   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11584                              TrueDest, FalseDest)))
11585     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11586          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11587       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11588       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11589       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11590       NewSCC->takeName(I);
11591       // Swap Destinations and condition...
11592       BI.setCondition(NewSCC);
11593       BI.setSuccessor(0, FalseDest);
11594       BI.setSuccessor(1, TrueDest);
11595       RemoveFromWorkList(I);
11596       I->eraseFromParent();
11597       AddToWorkList(NewSCC);
11598       return &BI;
11599     }
11600
11601   // Cannonicalize icmp_ne -> icmp_eq
11602   ICmpInst::Predicate IPred;
11603   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11604                       TrueDest, FalseDest)))
11605     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11606          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11607          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11608       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11609       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11610       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11611       NewSCC->takeName(I);
11612       // Swap Destinations and condition...
11613       BI.setCondition(NewSCC);
11614       BI.setSuccessor(0, FalseDest);
11615       BI.setSuccessor(1, TrueDest);
11616       RemoveFromWorkList(I);
11617       I->eraseFromParent();;
11618       AddToWorkList(NewSCC);
11619       return &BI;
11620     }
11621
11622   return 0;
11623 }
11624
11625 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11626   Value *Cond = SI.getCondition();
11627   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11628     if (I->getOpcode() == Instruction::Add)
11629       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11630         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11631         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11632           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11633                                                 AddRHS));
11634         SI.setOperand(0, I->getOperand(0));
11635         AddToWorkList(I);
11636         return &SI;
11637       }
11638   }
11639   return 0;
11640 }
11641
11642 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11643   Value *Agg = EV.getAggregateOperand();
11644
11645   if (!EV.hasIndices())
11646     return ReplaceInstUsesWith(EV, Agg);
11647
11648   if (Constant *C = dyn_cast<Constant>(Agg)) {
11649     if (isa<UndefValue>(C))
11650       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11651       
11652     if (isa<ConstantAggregateZero>(C))
11653       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11654
11655     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11656       // Extract the element indexed by the first index out of the constant
11657       Value *V = C->getOperand(*EV.idx_begin());
11658       if (EV.getNumIndices() > 1)
11659         // Extract the remaining indices out of the constant indexed by the
11660         // first index
11661         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11662       else
11663         return ReplaceInstUsesWith(EV, V);
11664     }
11665     return 0; // Can't handle other constants
11666   } 
11667   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11668     // We're extracting from an insertvalue instruction, compare the indices
11669     const unsigned *exti, *exte, *insi, *inse;
11670     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11671          exte = EV.idx_end(), inse = IV->idx_end();
11672          exti != exte && insi != inse;
11673          ++exti, ++insi) {
11674       if (*insi != *exti)
11675         // The insert and extract both reference distinctly different elements.
11676         // This means the extract is not influenced by the insert, and we can
11677         // replace the aggregate operand of the extract with the aggregate
11678         // operand of the insert. i.e., replace
11679         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11680         // %E = extractvalue { i32, { i32 } } %I, 0
11681         // with
11682         // %E = extractvalue { i32, { i32 } } %A, 0
11683         return ExtractValueInst::Create(IV->getAggregateOperand(),
11684                                         EV.idx_begin(), EV.idx_end());
11685     }
11686     if (exti == exte && insi == inse)
11687       // Both iterators are at the end: Index lists are identical. Replace
11688       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11689       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11690       // with "i32 42"
11691       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11692     if (exti == exte) {
11693       // The extract list is a prefix of the insert list. i.e. replace
11694       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11695       // %E = extractvalue { i32, { i32 } } %I, 1
11696       // with
11697       // %X = extractvalue { i32, { i32 } } %A, 1
11698       // %E = insertvalue { i32 } %X, i32 42, 0
11699       // by switching the order of the insert and extract (though the
11700       // insertvalue should be left in, since it may have other uses).
11701       Value *NewEV = InsertNewInstBefore(
11702         ExtractValueInst::Create(IV->getAggregateOperand(),
11703                                  EV.idx_begin(), EV.idx_end()),
11704         EV);
11705       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11706                                      insi, inse);
11707     }
11708     if (insi == inse)
11709       // The insert list is a prefix of the extract list
11710       // We can simply remove the common indices from the extract and make it
11711       // operate on the inserted value instead of the insertvalue result.
11712       // i.e., replace
11713       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11714       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11715       // with
11716       // %E extractvalue { i32 } { i32 42 }, 0
11717       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11718                                       exti, exte);
11719   }
11720   // Can't simplify extracts from other values. Note that nested extracts are
11721   // already simplified implicitely by the above (extract ( extract (insert) )
11722   // will be translated into extract ( insert ( extract ) ) first and then just
11723   // the value inserted, if appropriate).
11724   return 0;
11725 }
11726
11727 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11728 /// is to leave as a vector operation.
11729 static bool CheapToScalarize(Value *V, bool isConstant) {
11730   if (isa<ConstantAggregateZero>(V)) 
11731     return true;
11732   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11733     if (isConstant) return true;
11734     // If all elts are the same, we can extract.
11735     Constant *Op0 = C->getOperand(0);
11736     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11737       if (C->getOperand(i) != Op0)
11738         return false;
11739     return true;
11740   }
11741   Instruction *I = dyn_cast<Instruction>(V);
11742   if (!I) return false;
11743   
11744   // Insert element gets simplified to the inserted element or is deleted if
11745   // this is constant idx extract element and its a constant idx insertelt.
11746   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11747       isa<ConstantInt>(I->getOperand(2)))
11748     return true;
11749   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11750     return true;
11751   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11752     if (BO->hasOneUse() &&
11753         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11754          CheapToScalarize(BO->getOperand(1), isConstant)))
11755       return true;
11756   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11757     if (CI->hasOneUse() &&
11758         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11759          CheapToScalarize(CI->getOperand(1), isConstant)))
11760       return true;
11761   
11762   return false;
11763 }
11764
11765 /// Read and decode a shufflevector mask.
11766 ///
11767 /// It turns undef elements into values that are larger than the number of
11768 /// elements in the input.
11769 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11770   unsigned NElts = SVI->getType()->getNumElements();
11771   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11772     return std::vector<unsigned>(NElts, 0);
11773   if (isa<UndefValue>(SVI->getOperand(2)))
11774     return std::vector<unsigned>(NElts, 2*NElts);
11775
11776   std::vector<unsigned> Result;
11777   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11778   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11779     if (isa<UndefValue>(*i))
11780       Result.push_back(NElts*2);  // undef -> 8
11781     else
11782       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11783   return Result;
11784 }
11785
11786 /// FindScalarElement - Given a vector and an element number, see if the scalar
11787 /// value is already around as a register, for example if it were inserted then
11788 /// extracted from the vector.
11789 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11790   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11791   const VectorType *PTy = cast<VectorType>(V->getType());
11792   unsigned Width = PTy->getNumElements();
11793   if (EltNo >= Width)  // Out of range access.
11794     return UndefValue::get(PTy->getElementType());
11795   
11796   if (isa<UndefValue>(V))
11797     return UndefValue::get(PTy->getElementType());
11798   else if (isa<ConstantAggregateZero>(V))
11799     return Constant::getNullValue(PTy->getElementType());
11800   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11801     return CP->getOperand(EltNo);
11802   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11803     // If this is an insert to a variable element, we don't know what it is.
11804     if (!isa<ConstantInt>(III->getOperand(2))) 
11805       return 0;
11806     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11807     
11808     // If this is an insert to the element we are looking for, return the
11809     // inserted value.
11810     if (EltNo == IIElt) 
11811       return III->getOperand(1);
11812     
11813     // Otherwise, the insertelement doesn't modify the value, recurse on its
11814     // vector input.
11815     return FindScalarElement(III->getOperand(0), EltNo);
11816   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11817     unsigned LHSWidth =
11818       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11819     unsigned InEl = getShuffleMask(SVI)[EltNo];
11820     if (InEl < LHSWidth)
11821       return FindScalarElement(SVI->getOperand(0), InEl);
11822     else if (InEl < LHSWidth*2)
11823       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11824     else
11825       return UndefValue::get(PTy->getElementType());
11826   }
11827   
11828   // Otherwise, we don't know.
11829   return 0;
11830 }
11831
11832 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11833   // If vector val is undef, replace extract with scalar undef.
11834   if (isa<UndefValue>(EI.getOperand(0)))
11835     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11836
11837   // If vector val is constant 0, replace extract with scalar 0.
11838   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11839     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11840   
11841   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11842     // If vector val is constant with all elements the same, replace EI with
11843     // that element. When the elements are not identical, we cannot replace yet
11844     // (we do that below, but only when the index is constant).
11845     Constant *op0 = C->getOperand(0);
11846     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11847       if (C->getOperand(i) != op0) {
11848         op0 = 0; 
11849         break;
11850       }
11851     if (op0)
11852       return ReplaceInstUsesWith(EI, op0);
11853   }
11854   
11855   // If extracting a specified index from the vector, see if we can recursively
11856   // find a previously computed scalar that was inserted into the vector.
11857   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11858     unsigned IndexVal = IdxC->getZExtValue();
11859     unsigned VectorWidth = 
11860       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11861       
11862     // If this is extracting an invalid index, turn this into undef, to avoid
11863     // crashing the code below.
11864     if (IndexVal >= VectorWidth)
11865       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11866     
11867     // This instruction only demands the single element from the input vector.
11868     // If the input vector has a single use, simplify it based on this use
11869     // property.
11870     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11871       uint64_t UndefElts;
11872       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11873                                                 1 << IndexVal,
11874                                                 UndefElts)) {
11875         EI.setOperand(0, V);
11876         return &EI;
11877       }
11878     }
11879     
11880     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11881       return ReplaceInstUsesWith(EI, Elt);
11882     
11883     // If the this extractelement is directly using a bitcast from a vector of
11884     // the same number of elements, see if we can find the source element from
11885     // it.  In this case, we will end up needing to bitcast the scalars.
11886     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11887       if (const VectorType *VT = 
11888               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11889         if (VT->getNumElements() == VectorWidth)
11890           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11891             return new BitCastInst(Elt, EI.getType());
11892     }
11893   }
11894   
11895   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11896     if (I->hasOneUse()) {
11897       // Push extractelement into predecessor operation if legal and
11898       // profitable to do so
11899       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11900         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11901         if (CheapToScalarize(BO, isConstantElt)) {
11902           ExtractElementInst *newEI0 = 
11903             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11904                                    EI.getName()+".lhs");
11905           ExtractElementInst *newEI1 =
11906             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11907                                    EI.getName()+".rhs");
11908           InsertNewInstBefore(newEI0, EI);
11909           InsertNewInstBefore(newEI1, EI);
11910           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11911         }
11912       } else if (isa<LoadInst>(I)) {
11913         unsigned AS = 
11914           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11915         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11916                                          PointerType::get(EI.getType(), AS),EI);
11917         GetElementPtrInst *GEP =
11918           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11919         InsertNewInstBefore(GEP, EI);
11920         return new LoadInst(GEP);
11921       }
11922     }
11923     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11924       // Extracting the inserted element?
11925       if (IE->getOperand(2) == EI.getOperand(1))
11926         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11927       // If the inserted and extracted elements are constants, they must not
11928       // be the same value, extract from the pre-inserted value instead.
11929       if (isa<Constant>(IE->getOperand(2)) &&
11930           isa<Constant>(EI.getOperand(1))) {
11931         AddUsesToWorkList(EI);
11932         EI.setOperand(0, IE->getOperand(0));
11933         return &EI;
11934       }
11935     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11936       // If this is extracting an element from a shufflevector, figure out where
11937       // it came from and extract from the appropriate input element instead.
11938       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11939         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11940         Value *Src;
11941         unsigned LHSWidth =
11942           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11943
11944         if (SrcIdx < LHSWidth)
11945           Src = SVI->getOperand(0);
11946         else if (SrcIdx < LHSWidth*2) {
11947           SrcIdx -= LHSWidth;
11948           Src = SVI->getOperand(1);
11949         } else {
11950           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11951         }
11952         return new ExtractElementInst(Src, SrcIdx);
11953       }
11954     }
11955   }
11956   return 0;
11957 }
11958
11959 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11960 /// elements from either LHS or RHS, return the shuffle mask and true. 
11961 /// Otherwise, return false.
11962 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11963                                          std::vector<Constant*> &Mask) {
11964   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11965          "Invalid CollectSingleShuffleElements");
11966   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11967
11968   if (isa<UndefValue>(V)) {
11969     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11970     return true;
11971   } else if (V == LHS) {
11972     for (unsigned i = 0; i != NumElts; ++i)
11973       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11974     return true;
11975   } else if (V == RHS) {
11976     for (unsigned i = 0; i != NumElts; ++i)
11977       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11978     return true;
11979   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11980     // If this is an insert of an extract from some other vector, include it.
11981     Value *VecOp    = IEI->getOperand(0);
11982     Value *ScalarOp = IEI->getOperand(1);
11983     Value *IdxOp    = IEI->getOperand(2);
11984     
11985     if (!isa<ConstantInt>(IdxOp))
11986       return false;
11987     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11988     
11989     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11990       // Okay, we can handle this if the vector we are insertinting into is
11991       // transitively ok.
11992       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11993         // If so, update the mask to reflect the inserted undef.
11994         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11995         return true;
11996       }      
11997     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11998       if (isa<ConstantInt>(EI->getOperand(1)) &&
11999           EI->getOperand(0)->getType() == V->getType()) {
12000         unsigned ExtractedIdx =
12001           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12002         
12003         // This must be extracting from either LHS or RHS.
12004         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12005           // Okay, we can handle this if the vector we are insertinting into is
12006           // transitively ok.
12007           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12008             // If so, update the mask to reflect the inserted value.
12009             if (EI->getOperand(0) == LHS) {
12010               Mask[InsertedIdx % NumElts] = 
12011                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12012             } else {
12013               assert(EI->getOperand(0) == RHS);
12014               Mask[InsertedIdx % NumElts] = 
12015                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12016               
12017             }
12018             return true;
12019           }
12020         }
12021       }
12022     }
12023   }
12024   // TODO: Handle shufflevector here!
12025   
12026   return false;
12027 }
12028
12029 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12030 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12031 /// that computes V and the LHS value of the shuffle.
12032 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12033                                      Value *&RHS) {
12034   assert(isa<VectorType>(V->getType()) && 
12035          (RHS == 0 || V->getType() == RHS->getType()) &&
12036          "Invalid shuffle!");
12037   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12038
12039   if (isa<UndefValue>(V)) {
12040     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12041     return V;
12042   } else if (isa<ConstantAggregateZero>(V)) {
12043     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12044     return V;
12045   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12046     // If this is an insert of an extract from some other vector, include it.
12047     Value *VecOp    = IEI->getOperand(0);
12048     Value *ScalarOp = IEI->getOperand(1);
12049     Value *IdxOp    = IEI->getOperand(2);
12050     
12051     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12052       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12053           EI->getOperand(0)->getType() == V->getType()) {
12054         unsigned ExtractedIdx =
12055           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12056         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12057         
12058         // Either the extracted from or inserted into vector must be RHSVec,
12059         // otherwise we'd end up with a shuffle of three inputs.
12060         if (EI->getOperand(0) == RHS || RHS == 0) {
12061           RHS = EI->getOperand(0);
12062           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12063           Mask[InsertedIdx % NumElts] = 
12064             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12065           return V;
12066         }
12067         
12068         if (VecOp == RHS) {
12069           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12070           // Everything but the extracted element is replaced with the RHS.
12071           for (unsigned i = 0; i != NumElts; ++i) {
12072             if (i != InsertedIdx)
12073               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12074           }
12075           return V;
12076         }
12077         
12078         // If this insertelement is a chain that comes from exactly these two
12079         // vectors, return the vector and the effective shuffle.
12080         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12081           return EI->getOperand(0);
12082         
12083       }
12084     }
12085   }
12086   // TODO: Handle shufflevector here!
12087   
12088   // Otherwise, can't do anything fancy.  Return an identity vector.
12089   for (unsigned i = 0; i != NumElts; ++i)
12090     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12091   return V;
12092 }
12093
12094 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12095   Value *VecOp    = IE.getOperand(0);
12096   Value *ScalarOp = IE.getOperand(1);
12097   Value *IdxOp    = IE.getOperand(2);
12098   
12099   // Inserting an undef or into an undefined place, remove this.
12100   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12101     ReplaceInstUsesWith(IE, VecOp);
12102   
12103   // If the inserted element was extracted from some other vector, and if the 
12104   // indexes are constant, try to turn this into a shufflevector operation.
12105   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12106     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12107         EI->getOperand(0)->getType() == IE.getType()) {
12108       unsigned NumVectorElts = IE.getType()->getNumElements();
12109       unsigned ExtractedIdx =
12110         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12111       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12112       
12113       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12114         return ReplaceInstUsesWith(IE, VecOp);
12115       
12116       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12117         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12118       
12119       // If we are extracting a value from a vector, then inserting it right
12120       // back into the same place, just use the input vector.
12121       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12122         return ReplaceInstUsesWith(IE, VecOp);      
12123       
12124       // We could theoretically do this for ANY input.  However, doing so could
12125       // turn chains of insertelement instructions into a chain of shufflevector
12126       // instructions, and right now we do not merge shufflevectors.  As such,
12127       // only do this in a situation where it is clear that there is benefit.
12128       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12129         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12130         // the values of VecOp, except then one read from EIOp0.
12131         // Build a new shuffle mask.
12132         std::vector<Constant*> Mask;
12133         if (isa<UndefValue>(VecOp))
12134           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12135         else {
12136           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12137           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12138                                                        NumVectorElts));
12139         } 
12140         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12141         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12142                                      ConstantVector::get(Mask));
12143       }
12144       
12145       // If this insertelement isn't used by some other insertelement, turn it
12146       // (and any insertelements it points to), into one big shuffle.
12147       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12148         std::vector<Constant*> Mask;
12149         Value *RHS = 0;
12150         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12151         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12152         // We now have a shuffle of LHS, RHS, Mask.
12153         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12154       }
12155     }
12156   }
12157
12158   return 0;
12159 }
12160
12161
12162 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12163   Value *LHS = SVI.getOperand(0);
12164   Value *RHS = SVI.getOperand(1);
12165   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12166
12167   bool MadeChange = false;
12168
12169   // Undefined shuffle mask -> undefined value.
12170   if (isa<UndefValue>(SVI.getOperand(2)))
12171     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12172
12173   uint64_t UndefElts;
12174   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12175
12176   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12177     return 0;
12178
12179   uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
12180   if (VWidth <= 64 &&
12181       SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12182     LHS = SVI.getOperand(0);
12183     RHS = SVI.getOperand(1);
12184     MadeChange = true;
12185   }
12186   
12187   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12188   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12189   if (LHS == RHS || isa<UndefValue>(LHS)) {
12190     if (isa<UndefValue>(LHS) && LHS == RHS) {
12191       // shuffle(undef,undef,mask) -> undef.
12192       return ReplaceInstUsesWith(SVI, LHS);
12193     }
12194     
12195     // Remap any references to RHS to use LHS.
12196     std::vector<Constant*> Elts;
12197     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12198       if (Mask[i] >= 2*e)
12199         Elts.push_back(UndefValue::get(Type::Int32Ty));
12200       else {
12201         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12202             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12203           Mask[i] = 2*e;     // Turn into undef.
12204           Elts.push_back(UndefValue::get(Type::Int32Ty));
12205         } else {
12206           Mask[i] = Mask[i] % e;  // Force to LHS.
12207           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12208         }
12209       }
12210     }
12211     SVI.setOperand(0, SVI.getOperand(1));
12212     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12213     SVI.setOperand(2, ConstantVector::get(Elts));
12214     LHS = SVI.getOperand(0);
12215     RHS = SVI.getOperand(1);
12216     MadeChange = true;
12217   }
12218   
12219   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12220   bool isLHSID = true, isRHSID = true;
12221     
12222   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12223     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12224     // Is this an identity shuffle of the LHS value?
12225     isLHSID &= (Mask[i] == i);
12226       
12227     // Is this an identity shuffle of the RHS value?
12228     isRHSID &= (Mask[i]-e == i);
12229   }
12230
12231   // Eliminate identity shuffles.
12232   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12233   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12234   
12235   // If the LHS is a shufflevector itself, see if we can combine it with this
12236   // one without producing an unusual shuffle.  Here we are really conservative:
12237   // we are absolutely afraid of producing a shuffle mask not in the input
12238   // program, because the code gen may not be smart enough to turn a merged
12239   // shuffle into two specific shuffles: it may produce worse code.  As such,
12240   // we only merge two shuffles if the result is one of the two input shuffle
12241   // masks.  In this case, merging the shuffles just removes one instruction,
12242   // which we know is safe.  This is good for things like turning:
12243   // (splat(splat)) -> splat.
12244   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12245     if (isa<UndefValue>(RHS)) {
12246       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12247
12248       std::vector<unsigned> NewMask;
12249       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12250         if (Mask[i] >= 2*e)
12251           NewMask.push_back(2*e);
12252         else
12253           NewMask.push_back(LHSMask[Mask[i]]);
12254       
12255       // If the result mask is equal to the src shuffle or this shuffle mask, do
12256       // the replacement.
12257       if (NewMask == LHSMask || NewMask == Mask) {
12258         unsigned LHSInNElts =
12259           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12260         std::vector<Constant*> Elts;
12261         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12262           if (NewMask[i] >= LHSInNElts*2) {
12263             Elts.push_back(UndefValue::get(Type::Int32Ty));
12264           } else {
12265             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12266           }
12267         }
12268         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12269                                      LHSSVI->getOperand(1),
12270                                      ConstantVector::get(Elts));
12271       }
12272     }
12273   }
12274
12275   return MadeChange ? &SVI : 0;
12276 }
12277
12278
12279
12280
12281 /// TryToSinkInstruction - Try to move the specified instruction from its
12282 /// current block into the beginning of DestBlock, which can only happen if it's
12283 /// safe to move the instruction past all of the instructions between it and the
12284 /// end of its block.
12285 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12286   assert(I->hasOneUse() && "Invariants didn't hold!");
12287
12288   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12289   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12290     return false;
12291
12292   // Do not sink alloca instructions out of the entry block.
12293   if (isa<AllocaInst>(I) && I->getParent() ==
12294         &DestBlock->getParent()->getEntryBlock())
12295     return false;
12296
12297   // We can only sink load instructions if there is nothing between the load and
12298   // the end of block that could change the value.
12299   if (I->mayReadFromMemory()) {
12300     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12301          Scan != E; ++Scan)
12302       if (Scan->mayWriteToMemory())
12303         return false;
12304   }
12305
12306   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12307
12308   I->moveBefore(InsertPos);
12309   ++NumSunkInst;
12310   return true;
12311 }
12312
12313
12314 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12315 /// all reachable code to the worklist.
12316 ///
12317 /// This has a couple of tricks to make the code faster and more powerful.  In
12318 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12319 /// them to the worklist (this significantly speeds up instcombine on code where
12320 /// many instructions are dead or constant).  Additionally, if we find a branch
12321 /// whose condition is a known constant, we only visit the reachable successors.
12322 ///
12323 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12324                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12325                                        InstCombiner &IC,
12326                                        const TargetData *TD) {
12327   SmallVector<BasicBlock*, 256> Worklist;
12328   Worklist.push_back(BB);
12329
12330   while (!Worklist.empty()) {
12331     BB = Worklist.back();
12332     Worklist.pop_back();
12333     
12334     // We have now visited this block!  If we've already been here, ignore it.
12335     if (!Visited.insert(BB)) continue;
12336
12337     DbgInfoIntrinsic *DBI_Prev = NULL;
12338     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12339       Instruction *Inst = BBI++;
12340       
12341       // DCE instruction if trivially dead.
12342       if (isInstructionTriviallyDead(Inst)) {
12343         ++NumDeadInst;
12344         DOUT << "IC: DCE: " << *Inst;
12345         Inst->eraseFromParent();
12346         continue;
12347       }
12348       
12349       // ConstantProp instruction if trivially constant.
12350       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12351         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12352         Inst->replaceAllUsesWith(C);
12353         ++NumConstProp;
12354         Inst->eraseFromParent();
12355         continue;
12356       }
12357      
12358       // If there are two consecutive llvm.dbg.stoppoint calls then
12359       // it is likely that the optimizer deleted code in between these
12360       // two intrinsics. 
12361       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12362       if (DBI_Next) {
12363         if (DBI_Prev
12364             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12365             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12366           IC.RemoveFromWorkList(DBI_Prev);
12367           DBI_Prev->eraseFromParent();
12368         }
12369         DBI_Prev = DBI_Next;
12370       }
12371
12372       IC.AddToWorkList(Inst);
12373     }
12374
12375     // Recursively visit successors.  If this is a branch or switch on a
12376     // constant, only visit the reachable successor.
12377     TerminatorInst *TI = BB->getTerminator();
12378     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12379       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12380         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12381         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12382         Worklist.push_back(ReachableBB);
12383         continue;
12384       }
12385     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12386       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12387         // See if this is an explicit destination.
12388         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12389           if (SI->getCaseValue(i) == Cond) {
12390             BasicBlock *ReachableBB = SI->getSuccessor(i);
12391             Worklist.push_back(ReachableBB);
12392             continue;
12393           }
12394         
12395         // Otherwise it is the default destination.
12396         Worklist.push_back(SI->getSuccessor(0));
12397         continue;
12398       }
12399     }
12400     
12401     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12402       Worklist.push_back(TI->getSuccessor(i));
12403   }
12404 }
12405
12406 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12407   bool Changed = false;
12408   TD = &getAnalysis<TargetData>();
12409   
12410   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12411              << F.getNameStr() << "\n");
12412
12413   {
12414     // Do a depth-first traversal of the function, populate the worklist with
12415     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12416     // track of which blocks we visit.
12417     SmallPtrSet<BasicBlock*, 64> Visited;
12418     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12419
12420     // Do a quick scan over the function.  If we find any blocks that are
12421     // unreachable, remove any instructions inside of them.  This prevents
12422     // the instcombine code from having to deal with some bad special cases.
12423     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12424       if (!Visited.count(BB)) {
12425         Instruction *Term = BB->getTerminator();
12426         while (Term != BB->begin()) {   // Remove instrs bottom-up
12427           BasicBlock::iterator I = Term; --I;
12428
12429           DOUT << "IC: DCE: " << *I;
12430           ++NumDeadInst;
12431
12432           if (!I->use_empty())
12433             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12434           I->eraseFromParent();
12435           Changed = true;
12436         }
12437       }
12438   }
12439
12440   while (!Worklist.empty()) {
12441     Instruction *I = RemoveOneFromWorkList();
12442     if (I == 0) continue;  // skip null values.
12443
12444     // Check to see if we can DCE the instruction.
12445     if (isInstructionTriviallyDead(I)) {
12446       // Add operands to the worklist.
12447       if (I->getNumOperands() < 4)
12448         AddUsesToWorkList(*I);
12449       ++NumDeadInst;
12450
12451       DOUT << "IC: DCE: " << *I;
12452
12453       I->eraseFromParent();
12454       RemoveFromWorkList(I);
12455       Changed = true;
12456       continue;
12457     }
12458
12459     // Instruction isn't dead, see if we can constant propagate it.
12460     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12461       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12462
12463       // Add operands to the worklist.
12464       AddUsesToWorkList(*I);
12465       ReplaceInstUsesWith(*I, C);
12466
12467       ++NumConstProp;
12468       I->eraseFromParent();
12469       RemoveFromWorkList(I);
12470       Changed = true;
12471       continue;
12472     }
12473
12474     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12475       // See if we can constant fold its operands.
12476       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12477         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12478           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12479             if (NewC != CE) {
12480               i->set(NewC);
12481               Changed = true;
12482             }
12483     }
12484
12485     // See if we can trivially sink this instruction to a successor basic block.
12486     if (I->hasOneUse()) {
12487       BasicBlock *BB = I->getParent();
12488       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12489       if (UserParent != BB) {
12490         bool UserIsSuccessor = false;
12491         // See if the user is one of our successors.
12492         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12493           if (*SI == UserParent) {
12494             UserIsSuccessor = true;
12495             break;
12496           }
12497
12498         // If the user is one of our immediate successors, and if that successor
12499         // only has us as a predecessors (we'd have to split the critical edge
12500         // otherwise), we can keep going.
12501         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12502             next(pred_begin(UserParent)) == pred_end(UserParent))
12503           // Okay, the CFG is simple enough, try to sink this instruction.
12504           Changed |= TryToSinkInstruction(I, UserParent);
12505       }
12506     }
12507
12508     // Now that we have an instruction, try combining it to simplify it...
12509 #ifndef NDEBUG
12510     std::string OrigI;
12511 #endif
12512     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12513     if (Instruction *Result = visit(*I)) {
12514       ++NumCombined;
12515       // Should we replace the old instruction with a new one?
12516       if (Result != I) {
12517         DOUT << "IC: Old = " << *I
12518              << "    New = " << *Result;
12519
12520         // Everything uses the new instruction now.
12521         I->replaceAllUsesWith(Result);
12522
12523         // Push the new instruction and any users onto the worklist.
12524         AddToWorkList(Result);
12525         AddUsersToWorkList(*Result);
12526
12527         // Move the name to the new instruction first.
12528         Result->takeName(I);
12529
12530         // Insert the new instruction into the basic block...
12531         BasicBlock *InstParent = I->getParent();
12532         BasicBlock::iterator InsertPos = I;
12533
12534         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12535           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12536             ++InsertPos;
12537
12538         InstParent->getInstList().insert(InsertPos, Result);
12539
12540         // Make sure that we reprocess all operands now that we reduced their
12541         // use counts.
12542         AddUsesToWorkList(*I);
12543
12544         // Instructions can end up on the worklist more than once.  Make sure
12545         // we do not process an instruction that has been deleted.
12546         RemoveFromWorkList(I);
12547
12548         // Erase the old instruction.
12549         InstParent->getInstList().erase(I);
12550       } else {
12551 #ifndef NDEBUG
12552         DOUT << "IC: Mod = " << OrigI
12553              << "    New = " << *I;
12554 #endif
12555
12556         // If the instruction was modified, it's possible that it is now dead.
12557         // if so, remove it.
12558         if (isInstructionTriviallyDead(I)) {
12559           // Make sure we process all operands now that we are reducing their
12560           // use counts.
12561           AddUsesToWorkList(*I);
12562
12563           // Instructions may end up in the worklist more than once.  Erase all
12564           // occurrences of this instruction.
12565           RemoveFromWorkList(I);
12566           I->eraseFromParent();
12567         } else {
12568           AddToWorkList(I);
12569           AddUsersToWorkList(*I);
12570         }
12571       }
12572       Changed = true;
12573     }
12574   }
12575
12576   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12577     
12578   // Do an explicit clear, this shrinks the map if needed.
12579   WorklistMap.clear();
12580   return Changed;
12581 }
12582
12583
12584 bool InstCombiner::runOnFunction(Function &F) {
12585   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12586   
12587   bool EverMadeChange = false;
12588
12589   // Iterate while there is work to do.
12590   unsigned Iteration = 0;
12591   while (DoOneIteration(F, Iteration++))
12592     EverMadeChange = true;
12593   return EverMadeChange;
12594 }
12595
12596 FunctionPass *llvm::createInstructionCombiningPass() {
12597   return new InstCombiner();
12598 }