From Hacker's Delight:
[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 *visitOr (BinaryOperator &I);
187     Instruction *visitXor(BinaryOperator &I);
188     Instruction *visitShl(BinaryOperator &I);
189     Instruction *visitAShr(BinaryOperator &I);
190     Instruction *visitLShr(BinaryOperator &I);
191     Instruction *commonShiftTransforms(BinaryOperator &I);
192     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
193                                       Constant *RHSC);
194     Instruction *visitFCmpInst(FCmpInst &I);
195     Instruction *visitICmpInst(ICmpInst &I);
196     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
197     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
198                                                 Instruction *LHS,
199                                                 ConstantInt *RHS);
200     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
201                                 ConstantInt *DivRHS);
202
203     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
204                              ICmpInst::Predicate Cond, Instruction &I);
205     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
206                                      BinaryOperator &I);
207     Instruction *commonCastTransforms(CastInst &CI);
208     Instruction *commonIntCastTransforms(CastInst &CI);
209     Instruction *commonPointerCastTransforms(CastInst &CI);
210     Instruction *visitTrunc(TruncInst &CI);
211     Instruction *visitZExt(ZExtInst &CI);
212     Instruction *visitSExt(SExtInst &CI);
213     Instruction *visitFPTrunc(FPTruncInst &CI);
214     Instruction *visitFPExt(CastInst &CI);
215     Instruction *visitFPToUI(FPToUIInst &FI);
216     Instruction *visitFPToSI(FPToSIInst &FI);
217     Instruction *visitUIToFP(CastInst &CI);
218     Instruction *visitSIToFP(CastInst &CI);
219     Instruction *visitPtrToInt(CastInst &CI);
220     Instruction *visitIntToPtr(IntToPtrInst &CI);
221     Instruction *visitBitCast(BitCastInst &CI);
222     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
223                                 Instruction *FI);
224     Instruction *visitSelectInst(SelectInst &SI);
225     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
226     Instruction *visitCallInst(CallInst &CI);
227     Instruction *visitInvokeInst(InvokeInst &II);
228     Instruction *visitPHINode(PHINode &PN);
229     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
230     Instruction *visitAllocationInst(AllocationInst &AI);
231     Instruction *visitFreeInst(FreeInst &FI);
232     Instruction *visitLoadInst(LoadInst &LI);
233     Instruction *visitStoreInst(StoreInst &SI);
234     Instruction *visitBranchInst(BranchInst &BI);
235     Instruction *visitSwitchInst(SwitchInst &SI);
236     Instruction *visitInsertElementInst(InsertElementInst &IE);
237     Instruction *visitExtractElementInst(ExtractElementInst &EI);
238     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
239     Instruction *visitExtractValueInst(ExtractValueInst &EV);
240
241     // visitInstruction - Specify what to return for unhandled instructions...
242     Instruction *visitInstruction(Instruction &I) { return 0; }
243
244   private:
245     Instruction *visitCallSite(CallSite CS);
246     bool transformConstExprCastCall(CallSite CS);
247     Instruction *transformCallThroughTrampoline(CallSite CS);
248     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
249                                    bool DoXform = true);
250     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
251
252   public:
253     // InsertNewInstBefore - insert an instruction New before instruction Old
254     // in the program.  Add the new instruction to the worklist.
255     //
256     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
257       assert(New && New->getParent() == 0 &&
258              "New instruction already inserted into a basic block!");
259       BasicBlock *BB = Old.getParent();
260       BB->getInstList().insert(&Old, New);  // Insert inst
261       AddToWorkList(New);
262       return New;
263     }
264
265     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
266     /// This also adds the cast to the worklist.  Finally, this returns the
267     /// cast.
268     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
269                             Instruction &Pos) {
270       if (V->getType() == Ty) return V;
271
272       if (Constant *CV = dyn_cast<Constant>(V))
273         return ConstantExpr::getCast(opc, CV, Ty);
274       
275       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
276       AddToWorkList(C);
277       return C;
278     }
279         
280     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
281       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
282     }
283
284
285     // ReplaceInstUsesWith - This method is to be used when an instruction is
286     // found to be dead, replacable with another preexisting expression.  Here
287     // we add all uses of I to the worklist, replace all uses of I with the new
288     // value, then return I, so that the inst combiner will know that I was
289     // modified.
290     //
291     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
292       AddUsersToWorkList(I);         // Add all modified instrs to worklist
293       if (&I != V) {
294         I.replaceAllUsesWith(V);
295         return &I;
296       } else {
297         // If we are replacing the instruction with itself, this must be in a
298         // segment of unreachable code, so just clobber the instruction.
299         I.replaceAllUsesWith(UndefValue::get(I.getType()));
300         return &I;
301       }
302     }
303
304     // UpdateValueUsesWith - This method is to be used when an value is
305     // found to be replacable with another preexisting expression or was
306     // updated.  Here we add all uses of I to the worklist, replace all uses of
307     // I with the new value (unless the instruction was just updated), then
308     // return true, so that the inst combiner will know that I was modified.
309     //
310     bool UpdateValueUsesWith(Value *Old, Value *New) {
311       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
312       if (Old != New)
313         Old->replaceAllUsesWith(New);
314       if (Instruction *I = dyn_cast<Instruction>(Old))
315         AddToWorkList(I);
316       if (Instruction *I = dyn_cast<Instruction>(New))
317         AddToWorkList(I);
318       return true;
319     }
320     
321     // EraseInstFromFunction - When dealing with an instruction that has side
322     // effects or produces a void value, we can't rely on DCE to delete the
323     // instruction.  Instead, visit methods should return the value returned by
324     // this function.
325     Instruction *EraseInstFromFunction(Instruction &I) {
326       assert(I.use_empty() && "Cannot erase instruction that is used!");
327       AddUsesToWorkList(I);
328       RemoveFromWorkList(&I);
329       I.eraseFromParent();
330       return 0;  // Don't do anything with FI
331     }
332         
333     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
334                            APInt &KnownOne, unsigned Depth = 0) const {
335       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
336     }
337     
338     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
339                            unsigned Depth = 0) const {
340       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
341     }
342     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
343       return llvm::ComputeNumSignBits(Op, TD, Depth);
344     }
345
346   private:
347     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
348     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
349     /// casts that are known to not do anything...
350     ///
351     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
352                                    Value *V, const Type *DestTy,
353                                    Instruction *InsertBefore);
354
355     /// SimplifyCommutative - This performs a few simplifications for 
356     /// commutative operators.
357     bool SimplifyCommutative(BinaryOperator &I);
358
359     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
360     /// most-complex to least-complex order.
361     bool SimplifyCompare(CmpInst &I);
362
363     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
364     /// on the demanded bits.
365     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
366                               APInt& KnownZero, APInt& KnownOne,
367                               unsigned Depth = 0);
368
369     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
370                                       uint64_t &UndefElts, unsigned Depth = 0);
371       
372     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373     // PHI node as operand #0, see if we can fold the instruction into the PHI
374     // (which is only possible if all operands to the PHI are constants).
375     Instruction *FoldOpIntoPhi(Instruction &I);
376
377     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378     // operator and they all are only used by the PHI, PHI together their
379     // inputs, and do the operation once, to the result of the PHI.
380     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
381     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
382     
383     
384     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
385                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
386     
387     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
388                               bool isSub, Instruction &I);
389     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
390                                  bool isSigned, bool Inside, Instruction &IB);
391     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
392     Instruction *MatchBSwap(BinaryOperator &I);
393     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
394     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
395     Instruction *SimplifyMemSet(MemSetInst *MI);
396
397
398     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
399
400     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
401                                     unsigned CastOpc,
402                                     int &NumCastsRemoved);
403     unsigned GetOrEnforceKnownAlignment(Value *V,
404                                         unsigned PrefAlign = 0);
405
406   };
407 }
408
409 char InstCombiner::ID = 0;
410 static RegisterPass<InstCombiner>
411 X("instcombine", "Combine redundant instructions");
412
413 // getComplexity:  Assign a complexity or rank value to LLVM Values...
414 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
415 static unsigned getComplexity(Value *V) {
416   if (isa<Instruction>(V)) {
417     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
418       return 3;
419     return 4;
420   }
421   if (isa<Argument>(V)) return 3;
422   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
423 }
424
425 // isOnlyUse - Return true if this instruction will be deleted if we stop using
426 // it.
427 static bool isOnlyUse(Value *V) {
428   return V->hasOneUse() || isa<Constant>(V);
429 }
430
431 // getPromotedType - Return the specified type promoted as it would be to pass
432 // though a va_arg area...
433 static const Type *getPromotedType(const Type *Ty) {
434   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
435     if (ITy->getBitWidth() < 32)
436       return Type::Int32Ty;
437   }
438   return Ty;
439 }
440
441 /// getBitCastOperand - If the specified operand is a CastInst, a constant
442 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
443 /// operand value, otherwise return null.
444 static Value *getBitCastOperand(Value *V) {
445   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
446     // BitCastInst?
447     return I->getOperand(0);
448   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
449     // GetElementPtrInst?
450     if (GEP->hasAllZeroIndices())
451       return GEP->getOperand(0);
452   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
453     if (CE->getOpcode() == Instruction::BitCast)
454       // BitCast ConstantExp?
455       return CE->getOperand(0);
456     else if (CE->getOpcode() == Instruction::GetElementPtr) {
457       // GetElementPtr ConstantExp?
458       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
459            I != E; ++I) {
460         ConstantInt *CI = dyn_cast<ConstantInt>(I);
461         if (!CI || !CI->isZero())
462           // Any non-zero indices? Not cast-like.
463           return 0;
464       }
465       // All-zero indices? This is just like casting.
466       return CE->getOperand(0);
467     }
468   }
469   return 0;
470 }
471
472 /// This function is a wrapper around CastInst::isEliminableCastPair. It
473 /// simply extracts arguments and returns what that function returns.
474 static Instruction::CastOps 
475 isEliminableCastPair(
476   const CastInst *CI, ///< The first cast instruction
477   unsigned opcode,       ///< The opcode of the second cast instruction
478   const Type *DstTy,     ///< The target type for the second cast instruction
479   TargetData *TD         ///< The target data for pointer size
480 ) {
481   
482   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
483   const Type *MidTy = CI->getType();                  // B from above
484
485   // Get the opcodes of the two Cast instructions
486   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
487   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
488
489   return Instruction::CastOps(
490       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
491                                      DstTy, TD->getIntPtrType()));
492 }
493
494 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
495 /// in any code being generated.  It does not require codegen if V is simple
496 /// enough or if the cast can be folded into other casts.
497 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
498                               const Type *Ty, TargetData *TD) {
499   if (V->getType() == Ty || isa<Constant>(V)) return false;
500   
501   // If this is another cast that can be eliminated, it isn't codegen either.
502   if (const CastInst *CI = dyn_cast<CastInst>(V))
503     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
504       return false;
505   return true;
506 }
507
508 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
509 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
510 /// casts that are known to not do anything...
511 ///
512 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
513                                              Value *V, const Type *DestTy,
514                                              Instruction *InsertBefore) {
515   if (V->getType() == DestTy) return V;
516   if (Constant *C = dyn_cast<Constant>(V))
517     return ConstantExpr::getCast(opcode, C, DestTy);
518   
519   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
520 }
521
522 // SimplifyCommutative - This performs a few simplifications for commutative
523 // operators:
524 //
525 //  1. Order operands such that they are listed from right (least complex) to
526 //     left (most complex).  This puts constants before unary operators before
527 //     binary operators.
528 //
529 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
530 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
531 //
532 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
533   bool Changed = false;
534   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
535     Changed = !I.swapOperands();
536
537   if (!I.isAssociative()) return Changed;
538   Instruction::BinaryOps Opcode = I.getOpcode();
539   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
540     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
541       if (isa<Constant>(I.getOperand(1))) {
542         Constant *Folded = ConstantExpr::get(I.getOpcode(),
543                                              cast<Constant>(I.getOperand(1)),
544                                              cast<Constant>(Op->getOperand(1)));
545         I.setOperand(0, Op->getOperand(0));
546         I.setOperand(1, Folded);
547         return true;
548       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
549         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
550             isOnlyUse(Op) && isOnlyUse(Op1)) {
551           Constant *C1 = cast<Constant>(Op->getOperand(1));
552           Constant *C2 = cast<Constant>(Op1->getOperand(1));
553
554           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
555           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
556           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
557                                                     Op1->getOperand(0),
558                                                     Op1->getName(), &I);
559           AddToWorkList(New);
560           I.setOperand(0, New);
561           I.setOperand(1, Folded);
562           return true;
563         }
564     }
565   return Changed;
566 }
567
568 /// SimplifyCompare - For a CmpInst this function just orders the operands
569 /// so that theyare listed from right (least complex) to left (most complex).
570 /// This puts constants before unary operators before binary operators.
571 bool InstCombiner::SimplifyCompare(CmpInst &I) {
572   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
573     return false;
574   I.swapOperands();
575   // Compare instructions are not associative so there's nothing else we can do.
576   return true;
577 }
578
579 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
580 // if the LHS is a constant zero (which is the 'negate' form).
581 //
582 static inline Value *dyn_castNegVal(Value *V) {
583   if (BinaryOperator::isNeg(V))
584     return BinaryOperator::getNegArgument(V);
585
586   // Constants can be considered to be negated values if they can be folded.
587   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
588     return ConstantExpr::getNeg(C);
589
590   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591     if (C->getType()->getElementType()->isInteger())
592       return ConstantExpr::getNeg(C);
593
594   return 0;
595 }
596
597 static inline Value *dyn_castNotVal(Value *V) {
598   if (BinaryOperator::isNot(V))
599     return BinaryOperator::getNotArgument(V);
600
601   // Constants can be considered to be not'ed values...
602   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
603     return ConstantInt::get(~C->getValue());
604   return 0;
605 }
606
607 // dyn_castFoldableMul - If this value is a multiply that can be folded into
608 // other computations (because it has a constant operand), return the
609 // non-constant operand of the multiply, and set CST to point to the multiplier.
610 // Otherwise, return null.
611 //
612 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
613   if (V->hasOneUse() && V->getType()->isInteger())
614     if (Instruction *I = dyn_cast<Instruction>(V)) {
615       if (I->getOpcode() == Instruction::Mul)
616         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
617           return I->getOperand(0);
618       if (I->getOpcode() == Instruction::Shl)
619         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
620           // The multiplier is really 1 << CST.
621           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
622           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
623           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
624           return I->getOperand(0);
625         }
626     }
627   return 0;
628 }
629
630 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
631 /// expression, return it.
632 static User *dyn_castGetElementPtr(Value *V) {
633   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
634   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
635     if (CE->getOpcode() == Instruction::GetElementPtr)
636       return cast<User>(V);
637   return false;
638 }
639
640 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
641 /// opcode value. Otherwise return UserOp1.
642 static unsigned getOpcode(const Value *V) {
643   if (const Instruction *I = dyn_cast<Instruction>(V))
644     return I->getOpcode();
645   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
646     return CE->getOpcode();
647   // Use UserOp1 to mean there's no opcode.
648   return Instruction::UserOp1;
649 }
650
651 /// AddOne - Add one to a ConstantInt
652 static ConstantInt *AddOne(ConstantInt *C) {
653   APInt Val(C->getValue());
654   return ConstantInt::get(++Val);
655 }
656 /// SubOne - Subtract one from a ConstantInt
657 static ConstantInt *SubOne(ConstantInt *C) {
658   APInt Val(C->getValue());
659   return ConstantInt::get(--Val);
660 }
661 /// Add - Add two ConstantInts together
662 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
663   return ConstantInt::get(C1->getValue() + C2->getValue());
664 }
665 /// And - Bitwise AND two ConstantInts together
666 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
667   return ConstantInt::get(C1->getValue() & C2->getValue());
668 }
669 /// Subtract - Subtract one ConstantInt from another
670 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
671   return ConstantInt::get(C1->getValue() - C2->getValue());
672 }
673 /// Multiply - Multiply two ConstantInts together
674 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
675   return ConstantInt::get(C1->getValue() * C2->getValue());
676 }
677 /// MultiplyOverflows - True if the multiply can not be expressed in an int
678 /// this size.
679 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
680   uint32_t W = C1->getBitWidth();
681   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
682   if (sign) {
683     LHSExt.sext(W * 2);
684     RHSExt.sext(W * 2);
685   } else {
686     LHSExt.zext(W * 2);
687     RHSExt.zext(W * 2);
688   }
689
690   APInt MulExt = LHSExt * RHSExt;
691
692   if (sign) {
693     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
694     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
695     return MulExt.slt(Min) || MulExt.sgt(Max);
696   } else 
697     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
698 }
699
700
701 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
702 /// specified instruction is a constant integer.  If so, check to see if there
703 /// are any bits set in the constant that are not demanded.  If so, shrink the
704 /// constant and return true.
705 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
706                                    APInt Demanded) {
707   assert(I && "No instruction?");
708   assert(OpNo < I->getNumOperands() && "Operand index too large");
709
710   // If the operand is not a constant integer, nothing to do.
711   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
712   if (!OpC) return false;
713
714   // If there are no bits set that aren't demanded, nothing to do.
715   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
716   if ((~Demanded & OpC->getValue()) == 0)
717     return false;
718
719   // This instruction is producing bits that are not demanded. Shrink the RHS.
720   Demanded &= OpC->getValue();
721   I->setOperand(OpNo, ConstantInt::get(Demanded));
722   return true;
723 }
724
725 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
726 // set of known zero and one bits, compute the maximum and minimum values that
727 // could have the specified known zero and known one bits, returning them in
728 // min/max.
729 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
730                                                    const APInt& KnownZero,
731                                                    const APInt& KnownOne,
732                                                    APInt& Min, APInt& Max) {
733   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
734   assert(KnownZero.getBitWidth() == BitWidth && 
735          KnownOne.getBitWidth() == BitWidth &&
736          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
737          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
738   APInt UnknownBits = ~(KnownZero|KnownOne);
739
740   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
741   // bit if it is unknown.
742   Min = KnownOne;
743   Max = KnownOne|UnknownBits;
744   
745   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
746     Min.set(BitWidth-1);
747     Max.clear(BitWidth-1);
748   }
749 }
750
751 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
752 // a set of known zero and one bits, compute the maximum and minimum values that
753 // could have the specified known zero and known one bits, returning them in
754 // min/max.
755 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
756                                                      const APInt &KnownZero,
757                                                      const APInt &KnownOne,
758                                                      APInt &Min, APInt &Max) {
759   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
760   assert(KnownZero.getBitWidth() == BitWidth && 
761          KnownOne.getBitWidth() == BitWidth &&
762          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
763          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
764   APInt UnknownBits = ~(KnownZero|KnownOne);
765   
766   // The minimum value is when the unknown bits are all zeros.
767   Min = KnownOne;
768   // The maximum value is when the unknown bits are all ones.
769   Max = KnownOne|UnknownBits;
770 }
771
772 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
773 /// value based on the demanded bits. When this function is called, it is known
774 /// that only the bits set in DemandedMask of the result of V are ever used
775 /// downstream. Consequently, depending on the mask and V, it may be possible
776 /// to replace V with a constant or one of its operands. In such cases, this
777 /// function does the replacement and returns true. In all other cases, it
778 /// returns false after analyzing the expression and setting KnownOne and known
779 /// to be one in the expression. KnownZero contains all the bits that are known
780 /// to be zero in the expression. These are provided to potentially allow the
781 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
782 /// the expression. KnownOne and KnownZero always follow the invariant that 
783 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
784 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
785 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
786 /// and KnownOne must all be the same.
787 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
788                                         APInt& KnownZero, APInt& KnownOne,
789                                         unsigned Depth) {
790   assert(V != 0 && "Null pointer of Value???");
791   assert(Depth <= 6 && "Limit Search Depth");
792   uint32_t BitWidth = DemandedMask.getBitWidth();
793   const IntegerType *VTy = cast<IntegerType>(V->getType());
794   assert(VTy->getBitWidth() == BitWidth && 
795          KnownZero.getBitWidth() == BitWidth && 
796          KnownOne.getBitWidth() == BitWidth &&
797          "Value *V, DemandedMask, KnownZero and KnownOne \
798           must have same BitWidth");
799   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
800     // We know all of the bits for a constant!
801     KnownOne = CI->getValue() & DemandedMask;
802     KnownZero = ~KnownOne & DemandedMask;
803     return false;
804   }
805   
806   KnownZero.clear(); 
807   KnownOne.clear();
808   if (!V->hasOneUse()) {    // Other users may use these bits.
809     if (Depth != 0) {       // Not at the root.
810       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
811       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
812       return false;
813     }
814     // If this is the root being simplified, allow it to have multiple uses,
815     // just set the DemandedMask to all bits.
816     DemandedMask = APInt::getAllOnesValue(BitWidth);
817   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
818     if (V != UndefValue::get(VTy))
819       return UpdateValueUsesWith(V, UndefValue::get(VTy));
820     return false;
821   } else if (Depth == 6) {        // Limit search depth.
822     return false;
823   }
824   
825   Instruction *I = dyn_cast<Instruction>(V);
826   if (!I) return false;        // Only analyze instructions.
827
828   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
829   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
830   switch (I->getOpcode()) {
831   default:
832     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
833     break;
834   case Instruction::And:
835     // If either the LHS or the RHS are Zero, the result is zero.
836     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
837                              RHSKnownZero, RHSKnownOne, Depth+1))
838       return true;
839     assert((RHSKnownZero & RHSKnownOne) == 0 && 
840            "Bits known to be one AND zero?"); 
841
842     // If something is known zero on the RHS, the bits aren't demanded on the
843     // LHS.
844     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
845                              LHSKnownZero, LHSKnownOne, Depth+1))
846       return true;
847     assert((LHSKnownZero & LHSKnownOne) == 0 && 
848            "Bits known to be one AND zero?"); 
849
850     // If all of the demanded bits are known 1 on one side, return the other.
851     // These bits cannot contribute to the result of the 'and'.
852     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
853         (DemandedMask & ~LHSKnownZero))
854       return UpdateValueUsesWith(I, I->getOperand(0));
855     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
856         (DemandedMask & ~RHSKnownZero))
857       return UpdateValueUsesWith(I, I->getOperand(1));
858     
859     // If all of the demanded bits in the inputs are known zeros, return zero.
860     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
861       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
862       
863     // If the RHS is a constant, see if we can simplify it.
864     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
865       return UpdateValueUsesWith(I, I);
866       
867     // Output known-1 bits are only known if set in both the LHS & RHS.
868     RHSKnownOne &= LHSKnownOne;
869     // Output known-0 are known to be clear if zero in either the LHS | RHS.
870     RHSKnownZero |= LHSKnownZero;
871     break;
872   case Instruction::Or:
873     // If either the LHS or the RHS are One, the result is One.
874     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
875                              RHSKnownZero, RHSKnownOne, Depth+1))
876       return true;
877     assert((RHSKnownZero & RHSKnownOne) == 0 && 
878            "Bits known to be one AND zero?"); 
879     // If something is known one on the RHS, the bits aren't demanded on the
880     // LHS.
881     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
882                              LHSKnownZero, LHSKnownOne, Depth+1))
883       return true;
884     assert((LHSKnownZero & LHSKnownOne) == 0 && 
885            "Bits known to be one AND zero?"); 
886     
887     // If all of the demanded bits are known zero on one side, return the other.
888     // These bits cannot contribute to the result of the 'or'.
889     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
890         (DemandedMask & ~LHSKnownOne))
891       return UpdateValueUsesWith(I, I->getOperand(0));
892     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
893         (DemandedMask & ~RHSKnownOne))
894       return UpdateValueUsesWith(I, I->getOperand(1));
895
896     // If all of the potentially set bits on one side are known to be set on
897     // the other side, just use the 'other' side.
898     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
899         (DemandedMask & (~RHSKnownZero)))
900       return UpdateValueUsesWith(I, I->getOperand(0));
901     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
902         (DemandedMask & (~LHSKnownZero)))
903       return UpdateValueUsesWith(I, I->getOperand(1));
904         
905     // If the RHS is a constant, see if we can simplify it.
906     if (ShrinkDemandedConstant(I, 1, DemandedMask))
907       return UpdateValueUsesWith(I, I);
908           
909     // Output known-0 bits are only known if clear in both the LHS & RHS.
910     RHSKnownZero &= LHSKnownZero;
911     // Output known-1 are known to be set if set in either the LHS | RHS.
912     RHSKnownOne |= LHSKnownOne;
913     break;
914   case Instruction::Xor: {
915     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
916                              RHSKnownZero, RHSKnownOne, Depth+1))
917       return true;
918     assert((RHSKnownZero & RHSKnownOne) == 0 && 
919            "Bits known to be one AND zero?"); 
920     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
921                              LHSKnownZero, LHSKnownOne, Depth+1))
922       return true;
923     assert((LHSKnownZero & LHSKnownOne) == 0 && 
924            "Bits known to be one AND zero?"); 
925     
926     // If all of the demanded bits are known zero on one side, return the other.
927     // These bits cannot contribute to the result of the 'xor'.
928     if ((DemandedMask & RHSKnownZero) == DemandedMask)
929       return UpdateValueUsesWith(I, I->getOperand(0));
930     if ((DemandedMask & LHSKnownZero) == DemandedMask)
931       return UpdateValueUsesWith(I, I->getOperand(1));
932     
933     // Output known-0 bits are known if clear or set in both the LHS & RHS.
934     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
935                          (RHSKnownOne & LHSKnownOne);
936     // Output known-1 are known to be set if set in only one of the LHS, RHS.
937     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
938                         (RHSKnownOne & LHSKnownZero);
939     
940     // If all of the demanded bits are known to be zero on one side or the
941     // other, turn this into an *inclusive* or.
942     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
943     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
944       Instruction *Or =
945         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
946                                  I->getName());
947       InsertNewInstBefore(Or, *I);
948       return UpdateValueUsesWith(I, Or);
949     }
950     
951     // If all of the demanded bits on one side are known, and all of the set
952     // bits on that side are also known to be set on the other side, turn this
953     // into an AND, as we know the bits will be cleared.
954     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
955     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
956       // all known
957       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
958         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
959         Instruction *And = 
960           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
961         InsertNewInstBefore(And, *I);
962         return UpdateValueUsesWith(I, And);
963       }
964     }
965     
966     // If the RHS is a constant, see if we can simplify it.
967     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
968     if (ShrinkDemandedConstant(I, 1, DemandedMask))
969       return UpdateValueUsesWith(I, I);
970     
971     RHSKnownZero = KnownZeroOut;
972     RHSKnownOne  = KnownOneOut;
973     break;
974   }
975   case Instruction::Select:
976     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
977                              RHSKnownZero, RHSKnownOne, Depth+1))
978       return true;
979     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
980                              LHSKnownZero, LHSKnownOne, Depth+1))
981       return true;
982     assert((RHSKnownZero & RHSKnownOne) == 0 && 
983            "Bits known to be one AND zero?"); 
984     assert((LHSKnownZero & LHSKnownOne) == 0 && 
985            "Bits known to be one AND zero?"); 
986     
987     // If the operands are constants, see if we can simplify them.
988     if (ShrinkDemandedConstant(I, 1, DemandedMask))
989       return UpdateValueUsesWith(I, I);
990     if (ShrinkDemandedConstant(I, 2, DemandedMask))
991       return UpdateValueUsesWith(I, I);
992     
993     // Only known if known in both the LHS and RHS.
994     RHSKnownOne &= LHSKnownOne;
995     RHSKnownZero &= LHSKnownZero;
996     break;
997   case Instruction::Trunc: {
998     uint32_t truncBf = 
999       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1000     DemandedMask.zext(truncBf);
1001     RHSKnownZero.zext(truncBf);
1002     RHSKnownOne.zext(truncBf);
1003     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1004                              RHSKnownZero, RHSKnownOne, Depth+1))
1005       return true;
1006     DemandedMask.trunc(BitWidth);
1007     RHSKnownZero.trunc(BitWidth);
1008     RHSKnownOne.trunc(BitWidth);
1009     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1010            "Bits known to be one AND zero?"); 
1011     break;
1012   }
1013   case Instruction::BitCast:
1014     if (!I->getOperand(0)->getType()->isInteger())
1015       return false;
1016       
1017     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1018                              RHSKnownZero, RHSKnownOne, Depth+1))
1019       return true;
1020     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1021            "Bits known to be one AND zero?"); 
1022     break;
1023   case Instruction::ZExt: {
1024     // Compute the bits in the result that are not present in the input.
1025     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1026     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1027     
1028     DemandedMask.trunc(SrcBitWidth);
1029     RHSKnownZero.trunc(SrcBitWidth);
1030     RHSKnownOne.trunc(SrcBitWidth);
1031     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1032                              RHSKnownZero, RHSKnownOne, Depth+1))
1033       return true;
1034     DemandedMask.zext(BitWidth);
1035     RHSKnownZero.zext(BitWidth);
1036     RHSKnownOne.zext(BitWidth);
1037     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1038            "Bits known to be one AND zero?"); 
1039     // The top bits are known to be zero.
1040     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1041     break;
1042   }
1043   case Instruction::SExt: {
1044     // Compute the bits in the result that are not present in the input.
1045     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1046     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1047     
1048     APInt InputDemandedBits = DemandedMask & 
1049                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1050
1051     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1052     // If any of the sign extended bits are demanded, we know that the sign
1053     // bit is demanded.
1054     if ((NewBits & DemandedMask) != 0)
1055       InputDemandedBits.set(SrcBitWidth-1);
1056       
1057     InputDemandedBits.trunc(SrcBitWidth);
1058     RHSKnownZero.trunc(SrcBitWidth);
1059     RHSKnownOne.trunc(SrcBitWidth);
1060     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1061                              RHSKnownZero, RHSKnownOne, Depth+1))
1062       return true;
1063     InputDemandedBits.zext(BitWidth);
1064     RHSKnownZero.zext(BitWidth);
1065     RHSKnownOne.zext(BitWidth);
1066     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1067            "Bits known to be one AND zero?"); 
1068       
1069     // If the sign bit of the input is known set or clear, then we know the
1070     // top bits of the result.
1071
1072     // If the input sign bit is known zero, or if the NewBits are not demanded
1073     // convert this into a zero extension.
1074     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1075     {
1076       // Convert to ZExt cast
1077       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1078       return UpdateValueUsesWith(I, NewCast);
1079     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1080       RHSKnownOne |= NewBits;
1081     }
1082     break;
1083   }
1084   case Instruction::Add: {
1085     // Figure out what the input bits are.  If the top bits of the and result
1086     // are not demanded, then the add doesn't demand them from its input
1087     // either.
1088     uint32_t NLZ = DemandedMask.countLeadingZeros();
1089       
1090     // If there is a constant on the RHS, there are a variety of xformations
1091     // we can do.
1092     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1093       // If null, this should be simplified elsewhere.  Some of the xforms here
1094       // won't work if the RHS is zero.
1095       if (RHS->isZero())
1096         break;
1097       
1098       // If the top bit of the output is demanded, demand everything from the
1099       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1100       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1101
1102       // Find information about known zero/one bits in the input.
1103       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1104                                LHSKnownZero, LHSKnownOne, Depth+1))
1105         return true;
1106
1107       // If the RHS of the add has bits set that can't affect the input, reduce
1108       // the constant.
1109       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1110         return UpdateValueUsesWith(I, I);
1111       
1112       // Avoid excess work.
1113       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1114         break;
1115       
1116       // Turn it into OR if input bits are zero.
1117       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1118         Instruction *Or =
1119           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1120                                    I->getName());
1121         InsertNewInstBefore(Or, *I);
1122         return UpdateValueUsesWith(I, Or);
1123       }
1124       
1125       // We can say something about the output known-zero and known-one bits,
1126       // depending on potential carries from the input constant and the
1127       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1128       // bits set and the RHS constant is 0x01001, then we know we have a known
1129       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1130       
1131       // To compute this, we first compute the potential carry bits.  These are
1132       // the bits which may be modified.  I'm not aware of a better way to do
1133       // this scan.
1134       const APInt& RHSVal = RHS->getValue();
1135       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1136       
1137       // Now that we know which bits have carries, compute the known-1/0 sets.
1138       
1139       // Bits are known one if they are known zero in one operand and one in the
1140       // other, and there is no input carry.
1141       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1142                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1143       
1144       // Bits are known zero if they are known zero in both operands and there
1145       // is no input carry.
1146       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1147     } else {
1148       // If the high-bits of this ADD are not demanded, then it does not demand
1149       // the high bits of its LHS or RHS.
1150       if (DemandedMask[BitWidth-1] == 0) {
1151         // Right fill the mask of bits for this ADD to demand the most
1152         // significant bit and all those below it.
1153         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1154         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1155                                  LHSKnownZero, LHSKnownOne, Depth+1))
1156           return true;
1157         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1158                                  LHSKnownZero, LHSKnownOne, Depth+1))
1159           return true;
1160       }
1161     }
1162     break;
1163   }
1164   case Instruction::Sub:
1165     // If the high-bits of this SUB are not demanded, then it does not demand
1166     // the high bits of its LHS or RHS.
1167     if (DemandedMask[BitWidth-1] == 0) {
1168       // Right fill the mask of bits for this SUB to demand the most
1169       // significant bit and all those below it.
1170       uint32_t NLZ = DemandedMask.countLeadingZeros();
1171       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1172       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1173                                LHSKnownZero, LHSKnownOne, Depth+1))
1174         return true;
1175       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1176                                LHSKnownZero, LHSKnownOne, Depth+1))
1177         return true;
1178     }
1179     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1180     // the known zeros and ones.
1181     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1182     break;
1183   case Instruction::Shl:
1184     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1186       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1187       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1188                                RHSKnownZero, RHSKnownOne, Depth+1))
1189         return true;
1190       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1191              "Bits known to be one AND zero?"); 
1192       RHSKnownZero <<= ShiftAmt;
1193       RHSKnownOne  <<= ShiftAmt;
1194       // low bits known zero.
1195       if (ShiftAmt)
1196         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1197     }
1198     break;
1199   case Instruction::LShr:
1200     // For a logical shift right
1201     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1202       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1203       
1204       // Unsigned shift right.
1205       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1206       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1207                                RHSKnownZero, RHSKnownOne, Depth+1))
1208         return true;
1209       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1210              "Bits known to be one AND zero?"); 
1211       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1212       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1213       if (ShiftAmt) {
1214         // Compute the new bits that are at the top now.
1215         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1216         RHSKnownZero |= HighBits;  // high bits known zero.
1217       }
1218     }
1219     break;
1220   case Instruction::AShr:
1221     // If this is an arithmetic shift right and only the low-bit is set, we can
1222     // always convert this into a logical shr, even if the shift amount is
1223     // variable.  The low bit of the shift cannot be an input sign bit unless
1224     // the shift amount is >= the size of the datatype, which is undefined.
1225     if (DemandedMask == 1) {
1226       // Perform the logical shift right.
1227       Value *NewVal = BinaryOperator::CreateLShr(
1228                         I->getOperand(0), I->getOperand(1), I->getName());
1229       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1230       return UpdateValueUsesWith(I, NewVal);
1231     }    
1232
1233     // If the sign bit is the only bit demanded by this ashr, then there is no
1234     // need to do it, the shift doesn't change the high bit.
1235     if (DemandedMask.isSignBit())
1236       return UpdateValueUsesWith(I, I->getOperand(0));
1237     
1238     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1239       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1240       
1241       // Signed shift right.
1242       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1243       // If any of the "high bits" are demanded, we should set the sign bit as
1244       // demanded.
1245       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1246         DemandedMaskIn.set(BitWidth-1);
1247       if (SimplifyDemandedBits(I->getOperand(0),
1248                                DemandedMaskIn,
1249                                RHSKnownZero, RHSKnownOne, Depth+1))
1250         return true;
1251       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1252              "Bits known to be one AND zero?"); 
1253       // Compute the new bits that are at the top now.
1254       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1255       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1256       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1257         
1258       // Handle the sign bits.
1259       APInt SignBit(APInt::getSignBit(BitWidth));
1260       // Adjust to where it is now in the mask.
1261       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1262         
1263       // If the input sign bit is known to be zero, or if none of the top bits
1264       // are demanded, turn this into an unsigned shift right.
1265       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1266           (HighBits & ~DemandedMask) == HighBits) {
1267         // Perform the logical shift right.
1268         Value *NewVal = BinaryOperator::CreateLShr(
1269                           I->getOperand(0), SA, I->getName());
1270         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1271         return UpdateValueUsesWith(I, NewVal);
1272       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1273         RHSKnownOne |= HighBits;
1274       }
1275     }
1276     break;
1277   case Instruction::SRem:
1278     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1279       APInt RA = Rem->getValue().abs();
1280       if (RA.isPowerOf2()) {
1281         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1282           return UpdateValueUsesWith(I, I->getOperand(0));
1283
1284         APInt LowBits = RA - 1;
1285         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1286         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1287                                  LHSKnownZero, LHSKnownOne, Depth+1))
1288           return true;
1289
1290         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1291           LHSKnownZero |= ~LowBits;
1292
1293         KnownZero |= LHSKnownZero & DemandedMask;
1294
1295         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1296       }
1297     }
1298     break;
1299   case Instruction::URem: {
1300     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1301     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1302     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1303                              KnownZero2, KnownOne2, Depth+1))
1304       return true;
1305
1306     uint32_t Leaders = KnownZero2.countLeadingOnes();
1307     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1308                              KnownZero2, KnownOne2, Depth+1))
1309       return true;
1310
1311     Leaders = std::max(Leaders,
1312                        KnownZero2.countLeadingOnes());
1313     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1314     break;
1315   }
1316   case Instruction::Call:
1317     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1318       switch (II->getIntrinsicID()) {
1319       default: break;
1320       case Intrinsic::bswap: {
1321         // If the only bits demanded come from one byte of the bswap result,
1322         // just shift the input byte into position to eliminate the bswap.
1323         unsigned NLZ = DemandedMask.countLeadingZeros();
1324         unsigned NTZ = DemandedMask.countTrailingZeros();
1325           
1326         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1327         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1328         // have 14 leading zeros, round to 8.
1329         NLZ &= ~7;
1330         NTZ &= ~7;
1331         // If we need exactly one byte, we can do this transformation.
1332         if (BitWidth-NLZ-NTZ == 8) {
1333           unsigned ResultBit = NTZ;
1334           unsigned InputBit = BitWidth-NTZ-8;
1335           
1336           // Replace this with either a left or right shift to get the byte into
1337           // the right place.
1338           Instruction *NewVal;
1339           if (InputBit > ResultBit)
1340             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1341                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1342           else
1343             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1344                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1345           NewVal->takeName(I);
1346           InsertNewInstBefore(NewVal, *I);
1347           return UpdateValueUsesWith(I, NewVal);
1348         }
1349           
1350         // TODO: Could compute known zero/one bits based on the input.
1351         break;
1352       }
1353       }
1354     }
1355     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1356     break;
1357   }
1358   
1359   // If the client is only demanding bits that we know, return the known
1360   // constant.
1361   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1362     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1363   return false;
1364 }
1365
1366
1367 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1368 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1369 /// actually used by the caller.  This method analyzes which elements of the
1370 /// operand are undef and returns that information in UndefElts.
1371 ///
1372 /// If the information about demanded elements can be used to simplify the
1373 /// operation, the operation is simplified, then the resultant value is
1374 /// returned.  This returns null if no change was made.
1375 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1376                                                 uint64_t &UndefElts,
1377                                                 unsigned Depth) {
1378   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1379   assert(VWidth <= 64 && "Vector too wide to analyze!");
1380   uint64_t EltMask = ~0ULL >> (64-VWidth);
1381   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1382
1383   if (isa<UndefValue>(V)) {
1384     // If the entire vector is undefined, just return this info.
1385     UndefElts = EltMask;
1386     return 0;
1387   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1388     UndefElts = EltMask;
1389     return UndefValue::get(V->getType());
1390   }
1391
1392   UndefElts = 0;
1393   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1394     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1395     Constant *Undef = UndefValue::get(EltTy);
1396
1397     std::vector<Constant*> Elts;
1398     for (unsigned i = 0; i != VWidth; ++i)
1399       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1400         Elts.push_back(Undef);
1401         UndefElts |= (1ULL << i);
1402       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1403         Elts.push_back(Undef);
1404         UndefElts |= (1ULL << i);
1405       } else {                               // Otherwise, defined.
1406         Elts.push_back(CP->getOperand(i));
1407       }
1408
1409     // If we changed the constant, return it.
1410     Constant *NewCP = ConstantVector::get(Elts);
1411     return NewCP != CP ? NewCP : 0;
1412   } else if (isa<ConstantAggregateZero>(V)) {
1413     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1414     // set to undef.
1415     
1416     // Check if this is identity. If so, return 0 since we are not simplifying
1417     // anything.
1418     if (DemandedElts == ((1ULL << VWidth) -1))
1419       return 0;
1420     
1421     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1422     Constant *Zero = Constant::getNullValue(EltTy);
1423     Constant *Undef = UndefValue::get(EltTy);
1424     std::vector<Constant*> Elts;
1425     for (unsigned i = 0; i != VWidth; ++i)
1426       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1427     UndefElts = DemandedElts ^ EltMask;
1428     return ConstantVector::get(Elts);
1429   }
1430   
1431   // Limit search depth.
1432   if (Depth == 10)
1433     return false;
1434
1435   // If multiple users are using the root value, procede with
1436   // simplification conservatively assuming that all elements
1437   // are needed.
1438   if (!V->hasOneUse()) {
1439     // Quit if we find multiple users of a non-root value though.
1440     // They'll be handled when it's their turn to be visited by
1441     // the main instcombine process.
1442     if (Depth != 0)
1443       // TODO: Just compute the UndefElts information recursively.
1444       return false;
1445
1446     // Conservatively assume that all elements are needed.
1447     DemandedElts = EltMask;
1448   }
1449   
1450   Instruction *I = dyn_cast<Instruction>(V);
1451   if (!I) return false;        // Only analyze instructions.
1452   
1453   bool MadeChange = false;
1454   uint64_t UndefElts2;
1455   Value *TmpV;
1456   switch (I->getOpcode()) {
1457   default: break;
1458     
1459   case Instruction::InsertElement: {
1460     // If this is a variable index, we don't know which element it overwrites.
1461     // demand exactly the same input as we produce.
1462     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1463     if (Idx == 0) {
1464       // Note that we can't propagate undef elt info, because we don't know
1465       // which elt is getting updated.
1466       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1467                                         UndefElts2, Depth+1);
1468       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1469       break;
1470     }
1471     
1472     // If this is inserting an element that isn't demanded, remove this
1473     // insertelement.
1474     unsigned IdxNo = Idx->getZExtValue();
1475     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1476       return AddSoonDeadInstToWorklist(*I, 0);
1477     
1478     // Otherwise, the element inserted overwrites whatever was there, so the
1479     // input demanded set is simpler than the output set.
1480     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1481                                       DemandedElts & ~(1ULL << IdxNo),
1482                                       UndefElts, Depth+1);
1483     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1484
1485     // The inserted element is defined.
1486     UndefElts &= ~(1ULL << IdxNo);
1487     break;
1488   }
1489   case Instruction::ShuffleVector: {
1490     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1491     uint64_t LHSVWidth =
1492       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1493     uint64_t LeftDemanded = 0, RightDemanded = 0;
1494     for (unsigned i = 0; i < VWidth; i++) {
1495       if (DemandedElts & (1ULL << i)) {
1496         unsigned MaskVal = Shuffle->getMaskValue(i);
1497         if (MaskVal != -1u) {
1498           assert(MaskVal < LHSVWidth * 2 &&
1499                  "shufflevector mask index out of range!");
1500           if (MaskVal < LHSVWidth)
1501             LeftDemanded |= 1ULL << MaskVal;
1502           else
1503             RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
1504         }
1505       }
1506     }
1507
1508     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1509                                       UndefElts2, Depth+1);
1510     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1511
1512     uint64_t UndefElts3;
1513     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1514                                       UndefElts3, Depth+1);
1515     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1516
1517     bool NewUndefElts = false;
1518     for (unsigned i = 0; i < VWidth; i++) {
1519       unsigned MaskVal = Shuffle->getMaskValue(i);
1520       if (MaskVal == -1u) {
1521         uint64_t NewBit = 1ULL << i;
1522         UndefElts |= NewBit;
1523       } else if (MaskVal < LHSVWidth) {
1524         uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1525         NewUndefElts |= NewBit;
1526         UndefElts |= NewBit;
1527       } else {
1528         uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
1529         NewUndefElts |= NewBit;
1530         UndefElts |= NewBit;
1531       }
1532     }
1533
1534     if (NewUndefElts) {
1535       // Add additional discovered undefs.
1536       std::vector<Constant*> Elts;
1537       for (unsigned i = 0; i < VWidth; ++i) {
1538         if (UndefElts & (1ULL << i))
1539           Elts.push_back(UndefValue::get(Type::Int32Ty));
1540         else
1541           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1542                                           Shuffle->getMaskValue(i)));
1543       }
1544       I->setOperand(2, ConstantVector::get(Elts));
1545       MadeChange = true;
1546     }
1547     break;
1548   }
1549   case Instruction::BitCast: {
1550     // Vector->vector casts only.
1551     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1552     if (!VTy) break;
1553     unsigned InVWidth = VTy->getNumElements();
1554     uint64_t InputDemandedElts = 0;
1555     unsigned Ratio;
1556
1557     if (VWidth == InVWidth) {
1558       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1559       // elements as are demanded of us.
1560       Ratio = 1;
1561       InputDemandedElts = DemandedElts;
1562     } else if (VWidth > InVWidth) {
1563       // Untested so far.
1564       break;
1565       
1566       // If there are more elements in the result than there are in the source,
1567       // then an input element is live if any of the corresponding output
1568       // elements are live.
1569       Ratio = VWidth/InVWidth;
1570       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1571         if (DemandedElts & (1ULL << OutIdx))
1572           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1573       }
1574     } else {
1575       // Untested so far.
1576       break;
1577       
1578       // If there are more elements in the source than there are in the result,
1579       // then an input element is live if the corresponding output element is
1580       // live.
1581       Ratio = InVWidth/VWidth;
1582       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1583         if (DemandedElts & (1ULL << InIdx/Ratio))
1584           InputDemandedElts |= 1ULL << InIdx;
1585     }
1586     
1587     // div/rem demand all inputs, because they don't want divide by zero.
1588     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1589                                       UndefElts2, Depth+1);
1590     if (TmpV) {
1591       I->setOperand(0, TmpV);
1592       MadeChange = true;
1593     }
1594     
1595     UndefElts = UndefElts2;
1596     if (VWidth > InVWidth) {
1597       assert(0 && "Unimp");
1598       // If there are more elements in the result than there are in the source,
1599       // then an output element is undef if the corresponding input element is
1600       // undef.
1601       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1602         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1603           UndefElts |= 1ULL << OutIdx;
1604     } else if (VWidth < InVWidth) {
1605       assert(0 && "Unimp");
1606       // If there are more elements in the source than there are in the result,
1607       // then a result element is undef if all of the corresponding input
1608       // elements are undef.
1609       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1610       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1611         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1612           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1613     }
1614     break;
1615   }
1616   case Instruction::And:
1617   case Instruction::Or:
1618   case Instruction::Xor:
1619   case Instruction::Add:
1620   case Instruction::Sub:
1621   case Instruction::Mul:
1622     // div/rem demand all inputs, because they don't want divide by zero.
1623     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1624                                       UndefElts, Depth+1);
1625     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1626     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1627                                       UndefElts2, Depth+1);
1628     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1629       
1630     // Output elements are undefined if both are undefined.  Consider things
1631     // like undef&0.  The result is known zero, not undef.
1632     UndefElts &= UndefElts2;
1633     break;
1634     
1635   case Instruction::Call: {
1636     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1637     if (!II) break;
1638     switch (II->getIntrinsicID()) {
1639     default: break;
1640       
1641     // Binary vector operations that work column-wise.  A dest element is a
1642     // function of the corresponding input elements from the two inputs.
1643     case Intrinsic::x86_sse_sub_ss:
1644     case Intrinsic::x86_sse_mul_ss:
1645     case Intrinsic::x86_sse_min_ss:
1646     case Intrinsic::x86_sse_max_ss:
1647     case Intrinsic::x86_sse2_sub_sd:
1648     case Intrinsic::x86_sse2_mul_sd:
1649     case Intrinsic::x86_sse2_min_sd:
1650     case Intrinsic::x86_sse2_max_sd:
1651       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1652                                         UndefElts, Depth+1);
1653       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1654       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1655                                         UndefElts2, Depth+1);
1656       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1657
1658       // If only the low elt is demanded and this is a scalarizable intrinsic,
1659       // scalarize it now.
1660       if (DemandedElts == 1) {
1661         switch (II->getIntrinsicID()) {
1662         default: break;
1663         case Intrinsic::x86_sse_sub_ss:
1664         case Intrinsic::x86_sse_mul_ss:
1665         case Intrinsic::x86_sse2_sub_sd:
1666         case Intrinsic::x86_sse2_mul_sd:
1667           // TODO: Lower MIN/MAX/ABS/etc
1668           Value *LHS = II->getOperand(1);
1669           Value *RHS = II->getOperand(2);
1670           // Extract the element as scalars.
1671           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1672           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1673           
1674           switch (II->getIntrinsicID()) {
1675           default: assert(0 && "Case stmts out of sync!");
1676           case Intrinsic::x86_sse_sub_ss:
1677           case Intrinsic::x86_sse2_sub_sd:
1678             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1679                                                         II->getName()), *II);
1680             break;
1681           case Intrinsic::x86_sse_mul_ss:
1682           case Intrinsic::x86_sse2_mul_sd:
1683             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1684                                                          II->getName()), *II);
1685             break;
1686           }
1687           
1688           Instruction *New =
1689             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1690                                       II->getName());
1691           InsertNewInstBefore(New, *II);
1692           AddSoonDeadInstToWorklist(*II, 0);
1693           return New;
1694         }            
1695       }
1696         
1697       // Output elements are undefined if both are undefined.  Consider things
1698       // like undef&0.  The result is known zero, not undef.
1699       UndefElts &= UndefElts2;
1700       break;
1701     }
1702     break;
1703   }
1704   }
1705   return MadeChange ? I : 0;
1706 }
1707
1708
1709 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1710 /// function is designed to check a chain of associative operators for a
1711 /// potential to apply a certain optimization.  Since the optimization may be
1712 /// applicable if the expression was reassociated, this checks the chain, then
1713 /// reassociates the expression as necessary to expose the optimization
1714 /// opportunity.  This makes use of a special Functor, which must define
1715 /// 'shouldApply' and 'apply' methods.
1716 ///
1717 template<typename Functor>
1718 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1719   unsigned Opcode = Root.getOpcode();
1720   Value *LHS = Root.getOperand(0);
1721
1722   // Quick check, see if the immediate LHS matches...
1723   if (F.shouldApply(LHS))
1724     return F.apply(Root);
1725
1726   // Otherwise, if the LHS is not of the same opcode as the root, return.
1727   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1728   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1729     // Should we apply this transform to the RHS?
1730     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1731
1732     // If not to the RHS, check to see if we should apply to the LHS...
1733     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1734       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1735       ShouldApply = true;
1736     }
1737
1738     // If the functor wants to apply the optimization to the RHS of LHSI,
1739     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1740     if (ShouldApply) {
1741       // Now all of the instructions are in the current basic block, go ahead
1742       // and perform the reassociation.
1743       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1744
1745       // First move the selected RHS to the LHS of the root...
1746       Root.setOperand(0, LHSI->getOperand(1));
1747
1748       // Make what used to be the LHS of the root be the user of the root...
1749       Value *ExtraOperand = TmpLHSI->getOperand(1);
1750       if (&Root == TmpLHSI) {
1751         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1752         return 0;
1753       }
1754       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1755       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1756       BasicBlock::iterator ARI = &Root; ++ARI;
1757       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1758       ARI = Root;
1759
1760       // Now propagate the ExtraOperand down the chain of instructions until we
1761       // get to LHSI.
1762       while (TmpLHSI != LHSI) {
1763         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1764         // Move the instruction to immediately before the chain we are
1765         // constructing to avoid breaking dominance properties.
1766         NextLHSI->moveBefore(ARI);
1767         ARI = NextLHSI;
1768
1769         Value *NextOp = NextLHSI->getOperand(1);
1770         NextLHSI->setOperand(1, ExtraOperand);
1771         TmpLHSI = NextLHSI;
1772         ExtraOperand = NextOp;
1773       }
1774
1775       // Now that the instructions are reassociated, have the functor perform
1776       // the transformation...
1777       return F.apply(Root);
1778     }
1779
1780     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1781   }
1782   return 0;
1783 }
1784
1785 namespace {
1786
1787 // AddRHS - Implements: X + X --> X << 1
1788 struct AddRHS {
1789   Value *RHS;
1790   AddRHS(Value *rhs) : RHS(rhs) {}
1791   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1792   Instruction *apply(BinaryOperator &Add) const {
1793     return BinaryOperator::CreateShl(Add.getOperand(0),
1794                                      ConstantInt::get(Add.getType(), 1));
1795   }
1796 };
1797
1798 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1799 //                 iff C1&C2 == 0
1800 struct AddMaskingAnd {
1801   Constant *C2;
1802   AddMaskingAnd(Constant *c) : C2(c) {}
1803   bool shouldApply(Value *LHS) const {
1804     ConstantInt *C1;
1805     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1806            ConstantExpr::getAnd(C1, C2)->isNullValue();
1807   }
1808   Instruction *apply(BinaryOperator &Add) const {
1809     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1810   }
1811 };
1812
1813 }
1814
1815 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1816                                              InstCombiner *IC) {
1817   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1818     if (Constant *SOC = dyn_cast<Constant>(SO))
1819       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1820
1821     return IC->InsertNewInstBefore(CastInst::Create(
1822           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1823   }
1824
1825   // Figure out if the constant is the left or the right argument.
1826   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1827   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1828
1829   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1830     if (ConstIsRHS)
1831       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1832     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1833   }
1834
1835   Value *Op0 = SO, *Op1 = ConstOperand;
1836   if (!ConstIsRHS)
1837     std::swap(Op0, Op1);
1838   Instruction *New;
1839   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1840     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1841   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1842     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1843                           SO->getName()+".cmp");
1844   else {
1845     assert(0 && "Unknown binary instruction type!");
1846     abort();
1847   }
1848   return IC->InsertNewInstBefore(New, I);
1849 }
1850
1851 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1852 // constant as the other operand, try to fold the binary operator into the
1853 // select arguments.  This also works for Cast instructions, which obviously do
1854 // not have a second operand.
1855 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1856                                      InstCombiner *IC) {
1857   // Don't modify shared select instructions
1858   if (!SI->hasOneUse()) return 0;
1859   Value *TV = SI->getOperand(1);
1860   Value *FV = SI->getOperand(2);
1861
1862   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1863     // Bool selects with constant operands can be folded to logical ops.
1864     if (SI->getType() == Type::Int1Ty) return 0;
1865
1866     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1867     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1868
1869     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1870                               SelectFalseVal);
1871   }
1872   return 0;
1873 }
1874
1875
1876 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1877 /// node as operand #0, see if we can fold the instruction into the PHI (which
1878 /// is only possible if all operands to the PHI are constants).
1879 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1880   PHINode *PN = cast<PHINode>(I.getOperand(0));
1881   unsigned NumPHIValues = PN->getNumIncomingValues();
1882   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1883
1884   // Check to see if all of the operands of the PHI are constants.  If there is
1885   // one non-constant value, remember the BB it is.  If there is more than one
1886   // or if *it* is a PHI, bail out.
1887   BasicBlock *NonConstBB = 0;
1888   for (unsigned i = 0; i != NumPHIValues; ++i)
1889     if (!isa<Constant>(PN->getIncomingValue(i))) {
1890       if (NonConstBB) return 0;  // More than one non-const value.
1891       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1892       NonConstBB = PN->getIncomingBlock(i);
1893       
1894       // If the incoming non-constant value is in I's block, we have an infinite
1895       // loop.
1896       if (NonConstBB == I.getParent())
1897         return 0;
1898     }
1899   
1900   // If there is exactly one non-constant value, we can insert a copy of the
1901   // operation in that block.  However, if this is a critical edge, we would be
1902   // inserting the computation one some other paths (e.g. inside a loop).  Only
1903   // do this if the pred block is unconditionally branching into the phi block.
1904   if (NonConstBB) {
1905     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1906     if (!BI || !BI->isUnconditional()) return 0;
1907   }
1908
1909   // Okay, we can do the transformation: create the new PHI node.
1910   PHINode *NewPN = PHINode::Create(I.getType(), "");
1911   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1912   InsertNewInstBefore(NewPN, *PN);
1913   NewPN->takeName(PN);
1914
1915   // Next, add all of the operands to the PHI.
1916   if (I.getNumOperands() == 2) {
1917     Constant *C = cast<Constant>(I.getOperand(1));
1918     for (unsigned i = 0; i != NumPHIValues; ++i) {
1919       Value *InV = 0;
1920       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1921         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1922           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1923         else
1924           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1925       } else {
1926         assert(PN->getIncomingBlock(i) == NonConstBB);
1927         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1928           InV = BinaryOperator::Create(BO->getOpcode(),
1929                                        PN->getIncomingValue(i), C, "phitmp",
1930                                        NonConstBB->getTerminator());
1931         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1932           InV = CmpInst::Create(CI->getOpcode(), 
1933                                 CI->getPredicate(),
1934                                 PN->getIncomingValue(i), C, "phitmp",
1935                                 NonConstBB->getTerminator());
1936         else
1937           assert(0 && "Unknown binop!");
1938         
1939         AddToWorkList(cast<Instruction>(InV));
1940       }
1941       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1942     }
1943   } else { 
1944     CastInst *CI = cast<CastInst>(&I);
1945     const Type *RetTy = CI->getType();
1946     for (unsigned i = 0; i != NumPHIValues; ++i) {
1947       Value *InV;
1948       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1949         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1950       } else {
1951         assert(PN->getIncomingBlock(i) == NonConstBB);
1952         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1953                                I.getType(), "phitmp", 
1954                                NonConstBB->getTerminator());
1955         AddToWorkList(cast<Instruction>(InV));
1956       }
1957       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1958     }
1959   }
1960   return ReplaceInstUsesWith(I, NewPN);
1961 }
1962
1963
1964 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1965 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1966 /// This basically requires proving that the add in the original type would not
1967 /// overflow to change the sign bit or have a carry out.
1968 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1969   // There are different heuristics we can use for this.  Here are some simple
1970   // ones.
1971   
1972   // Add has the property that adding any two 2's complement numbers can only 
1973   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1974   // have at least two sign bits, we know that the addition of the two values will
1975   // sign extend fine.
1976   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1977     return true;
1978   
1979   
1980   // If one of the operands only has one non-zero bit, and if the other operand
1981   // has a known-zero bit in a more significant place than it (not including the
1982   // sign bit) the ripple may go up to and fill the zero, but won't change the
1983   // sign.  For example, (X & ~4) + 1.
1984   
1985   // TODO: Implement.
1986   
1987   return false;
1988 }
1989
1990
1991 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1992   bool Changed = SimplifyCommutative(I);
1993   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1994
1995   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1996     // X + undef -> undef
1997     if (isa<UndefValue>(RHS))
1998       return ReplaceInstUsesWith(I, RHS);
1999
2000     // X + 0 --> X
2001     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2002       if (RHSC->isNullValue())
2003         return ReplaceInstUsesWith(I, LHS);
2004     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2005       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2006                               (I.getType())->getValueAPF()))
2007         return ReplaceInstUsesWith(I, LHS);
2008     }
2009
2010     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2011       // X + (signbit) --> X ^ signbit
2012       const APInt& Val = CI->getValue();
2013       uint32_t BitWidth = Val.getBitWidth();
2014       if (Val == APInt::getSignBit(BitWidth))
2015         return BinaryOperator::CreateXor(LHS, RHS);
2016       
2017       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2018       // (X & 254)+1 -> (X&254)|1
2019       if (!isa<VectorType>(I.getType())) {
2020         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2021         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2022                                  KnownZero, KnownOne))
2023           return &I;
2024       }
2025
2026       // zext(i1) - 1  ->  select i1, 0, -1
2027       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2028         if (CI->isAllOnesValue() &&
2029             ZI->getOperand(0)->getType() == Type::Int1Ty)
2030           return SelectInst::Create(ZI->getOperand(0),
2031                                     Constant::getNullValue(I.getType()),
2032                                     ConstantInt::getAllOnesValue(I.getType()));
2033     }
2034
2035     if (isa<PHINode>(LHS))
2036       if (Instruction *NV = FoldOpIntoPhi(I))
2037         return NV;
2038     
2039     ConstantInt *XorRHS = 0;
2040     Value *XorLHS = 0;
2041     if (isa<ConstantInt>(RHSC) &&
2042         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2043       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2044       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2045       
2046       uint32_t Size = TySizeBits / 2;
2047       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2048       APInt CFF80Val(-C0080Val);
2049       do {
2050         if (TySizeBits > Size) {
2051           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2052           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2053           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2054               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2055             // This is a sign extend if the top bits are known zero.
2056             if (!MaskedValueIsZero(XorLHS, 
2057                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2058               Size = 0;  // Not a sign ext, but can't be any others either.
2059             break;
2060           }
2061         }
2062         Size >>= 1;
2063         C0080Val = APIntOps::lshr(C0080Val, Size);
2064         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2065       } while (Size >= 1);
2066       
2067       // FIXME: This shouldn't be necessary. When the backends can handle types
2068       // with funny bit widths then this switch statement should be removed. It
2069       // is just here to get the size of the "middle" type back up to something
2070       // that the back ends can handle.
2071       const Type *MiddleType = 0;
2072       switch (Size) {
2073         default: break;
2074         case 32: MiddleType = Type::Int32Ty; break;
2075         case 16: MiddleType = Type::Int16Ty; break;
2076         case  8: MiddleType = Type::Int8Ty; break;
2077       }
2078       if (MiddleType) {
2079         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2080         InsertNewInstBefore(NewTrunc, I);
2081         return new SExtInst(NewTrunc, I.getType(), I.getName());
2082       }
2083     }
2084   }
2085
2086   if (I.getType() == Type::Int1Ty)
2087     return BinaryOperator::CreateXor(LHS, RHS);
2088
2089   // X + X --> X << 1
2090   if (I.getType()->isInteger()) {
2091     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2092
2093     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2094       if (RHSI->getOpcode() == Instruction::Sub)
2095         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2096           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2097     }
2098     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2099       if (LHSI->getOpcode() == Instruction::Sub)
2100         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2101           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2102     }
2103   }
2104
2105   // -A + B  -->  B - A
2106   // -A + -B  -->  -(A + B)
2107   if (Value *LHSV = dyn_castNegVal(LHS)) {
2108     if (LHS->getType()->isIntOrIntVector()) {
2109       if (Value *RHSV = dyn_castNegVal(RHS)) {
2110         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2111         InsertNewInstBefore(NewAdd, I);
2112         return BinaryOperator::CreateNeg(NewAdd);
2113       }
2114     }
2115     
2116     return BinaryOperator::CreateSub(RHS, LHSV);
2117   }
2118
2119   // A + -B  -->  A - B
2120   if (!isa<Constant>(RHS))
2121     if (Value *V = dyn_castNegVal(RHS))
2122       return BinaryOperator::CreateSub(LHS, V);
2123
2124
2125   ConstantInt *C2;
2126   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2127     if (X == RHS)   // X*C + X --> X * (C+1)
2128       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2129
2130     // X*C1 + X*C2 --> X * (C1+C2)
2131     ConstantInt *C1;
2132     if (X == dyn_castFoldableMul(RHS, C1))
2133       return BinaryOperator::CreateMul(X, Add(C1, C2));
2134   }
2135
2136   // X + X*C --> X * (C+1)
2137   if (dyn_castFoldableMul(RHS, C2) == LHS)
2138     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2139
2140   // X + ~X --> -1   since   ~X = -X-1
2141   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2142     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2143   
2144
2145   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2146   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2147     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2148       return R;
2149   
2150   // A+B --> A|B iff A and B have no bits set in common.
2151   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2152     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2153     APInt LHSKnownOne(IT->getBitWidth(), 0);
2154     APInt LHSKnownZero(IT->getBitWidth(), 0);
2155     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2156     if (LHSKnownZero != 0) {
2157       APInt RHSKnownOne(IT->getBitWidth(), 0);
2158       APInt RHSKnownZero(IT->getBitWidth(), 0);
2159       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2160       
2161       // No bits in common -> bitwise or.
2162       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2163         return BinaryOperator::CreateOr(LHS, RHS);
2164     }
2165   }
2166
2167   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2168   if (I.getType()->isIntOrIntVector()) {
2169     Value *W, *X, *Y, *Z;
2170     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2171         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2172       if (W != Y) {
2173         if (W == Z) {
2174           std::swap(Y, Z);
2175         } else if (Y == X) {
2176           std::swap(W, X);
2177         } else if (X == Z) {
2178           std::swap(Y, Z);
2179           std::swap(W, X);
2180         }
2181       }
2182
2183       if (W == Y) {
2184         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2185                                                             LHS->getName()), I);
2186         return BinaryOperator::CreateMul(W, NewAdd);
2187       }
2188     }
2189   }
2190
2191   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2192     Value *X = 0;
2193     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2194       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2195
2196     // (X & FF00) + xx00  -> (X+xx00) & FF00
2197     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2198       Constant *Anded = And(CRHS, C2);
2199       if (Anded == CRHS) {
2200         // See if all bits from the first bit set in the Add RHS up are included
2201         // in the mask.  First, get the rightmost bit.
2202         const APInt& AddRHSV = CRHS->getValue();
2203
2204         // Form a mask of all bits from the lowest bit added through the top.
2205         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2206
2207         // See if the and mask includes all of these bits.
2208         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2209
2210         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2211           // Okay, the xform is safe.  Insert the new add pronto.
2212           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2213                                                             LHS->getName()), I);
2214           return BinaryOperator::CreateAnd(NewAdd, C2);
2215         }
2216       }
2217     }
2218
2219     // Try to fold constant add into select arguments.
2220     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2221       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2222         return R;
2223   }
2224
2225   // add (cast *A to intptrtype) B -> 
2226   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2227   {
2228     CastInst *CI = dyn_cast<CastInst>(LHS);
2229     Value *Other = RHS;
2230     if (!CI) {
2231       CI = dyn_cast<CastInst>(RHS);
2232       Other = LHS;
2233     }
2234     if (CI && CI->getType()->isSized() && 
2235         (CI->getType()->getPrimitiveSizeInBits() == 
2236          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2237         && isa<PointerType>(CI->getOperand(0)->getType())) {
2238       unsigned AS =
2239         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2240       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2241                                       PointerType::get(Type::Int8Ty, AS), I);
2242       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2243       return new PtrToIntInst(I2, CI->getType());
2244     }
2245   }
2246   
2247   // add (select X 0 (sub n A)) A  -->  select X A n
2248   {
2249     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2250     Value *A = RHS;
2251     if (!SI) {
2252       SI = dyn_cast<SelectInst>(RHS);
2253       A = LHS;
2254     }
2255     if (SI && SI->hasOneUse()) {
2256       Value *TV = SI->getTrueValue();
2257       Value *FV = SI->getFalseValue();
2258       Value *N;
2259
2260       // Can we fold the add into the argument of the select?
2261       // We check both true and false select arguments for a matching subtract.
2262       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2263         // Fold the add into the true select value.
2264         return SelectInst::Create(SI->getCondition(), N, A);
2265       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2266         // Fold the add into the false select value.
2267         return SelectInst::Create(SI->getCondition(), A, N);
2268     }
2269   }
2270   
2271   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2272   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2273     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2274       return ReplaceInstUsesWith(I, LHS);
2275
2276   // Check for (add (sext x), y), see if we can merge this into an
2277   // integer add followed by a sext.
2278   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2279     // (add (sext x), cst) --> (sext (add x, cst'))
2280     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2281       Constant *CI = 
2282         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2283       if (LHSConv->hasOneUse() &&
2284           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2285           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2286         // Insert the new, smaller add.
2287         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2288                                                         CI, "addconv");
2289         InsertNewInstBefore(NewAdd, I);
2290         return new SExtInst(NewAdd, I.getType());
2291       }
2292     }
2293     
2294     // (add (sext x), (sext y)) --> (sext (add int x, y))
2295     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2296       // Only do this if x/y have the same type, if at last one of them has a
2297       // single use (so we don't increase the number of sexts), and if the
2298       // integer add will not overflow.
2299       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2300           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2301           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2302                                    RHSConv->getOperand(0))) {
2303         // Insert the new integer add.
2304         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2305                                                         RHSConv->getOperand(0),
2306                                                         "addconv");
2307         InsertNewInstBefore(NewAdd, I);
2308         return new SExtInst(NewAdd, I.getType());
2309       }
2310     }
2311   }
2312   
2313   // Check for (add double (sitofp x), y), see if we can merge this into an
2314   // integer add followed by a promotion.
2315   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2316     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2317     // ... if the constant fits in the integer value.  This is useful for things
2318     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2319     // requires a constant pool load, and generally allows the add to be better
2320     // instcombined.
2321     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2322       Constant *CI = 
2323       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2324       if (LHSConv->hasOneUse() &&
2325           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2326           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2327         // Insert the new integer add.
2328         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2329                                                         CI, "addconv");
2330         InsertNewInstBefore(NewAdd, I);
2331         return new SIToFPInst(NewAdd, I.getType());
2332       }
2333     }
2334     
2335     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2336     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2337       // Only do this if x/y have the same type, if at last one of them has a
2338       // single use (so we don't increase the number of int->fp conversions),
2339       // and if the integer add will not overflow.
2340       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2341           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2342           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2343                                    RHSConv->getOperand(0))) {
2344         // Insert the new integer add.
2345         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2346                                                         RHSConv->getOperand(0),
2347                                                         "addconv");
2348         InsertNewInstBefore(NewAdd, I);
2349         return new SIToFPInst(NewAdd, I.getType());
2350       }
2351     }
2352   }
2353   
2354   return Changed ? &I : 0;
2355 }
2356
2357 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2358   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2359
2360   if (Op0 == Op1 &&                        // sub X, X  -> 0
2361       !I.getType()->isFPOrFPVector())
2362     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2363
2364   // If this is a 'B = x-(-A)', change to B = x+A...
2365   if (Value *V = dyn_castNegVal(Op1))
2366     return BinaryOperator::CreateAdd(Op0, V);
2367
2368   if (isa<UndefValue>(Op0))
2369     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2370   if (isa<UndefValue>(Op1))
2371     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2372
2373   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2374     // Replace (-1 - A) with (~A)...
2375     if (C->isAllOnesValue())
2376       return BinaryOperator::CreateNot(Op1);
2377
2378     // C - ~X == X + (1+C)
2379     Value *X = 0;
2380     if (match(Op1, m_Not(m_Value(X))))
2381       return BinaryOperator::CreateAdd(X, AddOne(C));
2382
2383     // -(X >>u 31) -> (X >>s 31)
2384     // -(X >>s 31) -> (X >>u 31)
2385     if (C->isZero()) {
2386       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2387         if (SI->getOpcode() == Instruction::LShr) {
2388           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2389             // Check to see if we are shifting out everything but the sign bit.
2390             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2391                 SI->getType()->getPrimitiveSizeInBits()-1) {
2392               // Ok, the transformation is safe.  Insert AShr.
2393               return BinaryOperator::Create(Instruction::AShr, 
2394                                           SI->getOperand(0), CU, SI->getName());
2395             }
2396           }
2397         }
2398         else if (SI->getOpcode() == Instruction::AShr) {
2399           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2400             // Check to see if we are shifting out everything but the sign bit.
2401             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2402                 SI->getType()->getPrimitiveSizeInBits()-1) {
2403               // Ok, the transformation is safe.  Insert LShr. 
2404               return BinaryOperator::CreateLShr(
2405                                           SI->getOperand(0), CU, SI->getName());
2406             }
2407           }
2408         }
2409       }
2410     }
2411
2412     // Try to fold constant sub into select arguments.
2413     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2414       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2415         return R;
2416
2417     if (isa<PHINode>(Op0))
2418       if (Instruction *NV = FoldOpIntoPhi(I))
2419         return NV;
2420   }
2421
2422   if (I.getType() == Type::Int1Ty)
2423     return BinaryOperator::CreateXor(Op0, Op1);
2424
2425   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2426     if (Op1I->getOpcode() == Instruction::Add &&
2427         !Op0->getType()->isFPOrFPVector()) {
2428       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2429         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2430       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2431         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2432       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2433         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2434           // C1-(X+C2) --> (C1-C2)-X
2435           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2436                                            Op1I->getOperand(0));
2437       }
2438     }
2439
2440     if (Op1I->hasOneUse()) {
2441       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2442       // is not used by anyone else...
2443       //
2444       if (Op1I->getOpcode() == Instruction::Sub &&
2445           !Op1I->getType()->isFPOrFPVector()) {
2446         // Swap the two operands of the subexpr...
2447         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2448         Op1I->setOperand(0, IIOp1);
2449         Op1I->setOperand(1, IIOp0);
2450
2451         // Create the new top level add instruction...
2452         return BinaryOperator::CreateAdd(Op0, Op1);
2453       }
2454
2455       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2456       //
2457       if (Op1I->getOpcode() == Instruction::And &&
2458           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2459         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2460
2461         Value *NewNot =
2462           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2463         return BinaryOperator::CreateAnd(Op0, NewNot);
2464       }
2465
2466       // 0 - (X sdiv C)  -> (X sdiv -C)
2467       if (Op1I->getOpcode() == Instruction::SDiv)
2468         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2469           if (CSI->isZero())
2470             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2471               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2472                                                ConstantExpr::getNeg(DivRHS));
2473
2474       // X - X*C --> X * (1-C)
2475       ConstantInt *C2 = 0;
2476       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2477         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2478         return BinaryOperator::CreateMul(Op0, CP1);
2479       }
2480     }
2481   }
2482
2483   if (!Op0->getType()->isFPOrFPVector())
2484     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2485       if (Op0I->getOpcode() == Instruction::Add) {
2486         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2487           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2488         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2489           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2490       } else if (Op0I->getOpcode() == Instruction::Sub) {
2491         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2492           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2493       }
2494     }
2495
2496   ConstantInt *C1;
2497   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2498     if (X == Op1)  // X*C - X --> X * (C-1)
2499       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2500
2501     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2502     if (X == dyn_castFoldableMul(Op1, C2))
2503       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2504   }
2505   return 0;
2506 }
2507
2508 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2509 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2510 /// TrueIfSigned if the result of the comparison is true when the input value is
2511 /// signed.
2512 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2513                            bool &TrueIfSigned) {
2514   switch (pred) {
2515   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2516     TrueIfSigned = true;
2517     return RHS->isZero();
2518   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2519     TrueIfSigned = true;
2520     return RHS->isAllOnesValue();
2521   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2522     TrueIfSigned = false;
2523     return RHS->isAllOnesValue();
2524   case ICmpInst::ICMP_UGT:
2525     // True if LHS u> RHS and RHS == high-bit-mask - 1
2526     TrueIfSigned = true;
2527     return RHS->getValue() ==
2528       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2529   case ICmpInst::ICMP_UGE: 
2530     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2531     TrueIfSigned = true;
2532     return RHS->getValue().isSignBit();
2533   default:
2534     return false;
2535   }
2536 }
2537
2538 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2539   bool Changed = SimplifyCommutative(I);
2540   Value *Op0 = I.getOperand(0);
2541
2542   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2543     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2544
2545   // Simplify mul instructions with a constant RHS...
2546   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2547     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2548
2549       // ((X << C1)*C2) == (X * (C2 << C1))
2550       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2551         if (SI->getOpcode() == Instruction::Shl)
2552           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2553             return BinaryOperator::CreateMul(SI->getOperand(0),
2554                                              ConstantExpr::getShl(CI, ShOp));
2555
2556       if (CI->isZero())
2557         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2558       if (CI->equalsInt(1))                  // X * 1  == X
2559         return ReplaceInstUsesWith(I, Op0);
2560       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2561         return BinaryOperator::CreateNeg(Op0, I.getName());
2562
2563       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2564       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2565         return BinaryOperator::CreateShl(Op0,
2566                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2567       }
2568     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2569       if (Op1F->isNullValue())
2570         return ReplaceInstUsesWith(I, Op1);
2571
2572       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2573       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2574       if (Op1F->isExactlyValue(1.0))
2575         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2576     } else if (isa<VectorType>(Op1->getType())) {
2577       if (isa<ConstantAggregateZero>(Op1))
2578         return ReplaceInstUsesWith(I, Op1);
2579
2580       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2581         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2582           return BinaryOperator::CreateNeg(Op0, I.getName());
2583
2584         // As above, vector X*splat(1.0) -> X in all defined cases.
2585         if (Constant *Splat = Op1V->getSplatValue()) {
2586           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2587             if (F->isExactlyValue(1.0))
2588               return ReplaceInstUsesWith(I, Op0);
2589           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2590             if (CI->equalsInt(1))
2591               return ReplaceInstUsesWith(I, Op0);
2592         }
2593       }
2594     }
2595     
2596     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2597       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2598           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2599         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2600         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2601                                                      Op1, "tmp");
2602         InsertNewInstBefore(Add, I);
2603         Value *C1C2 = ConstantExpr::getMul(Op1, 
2604                                            cast<Constant>(Op0I->getOperand(1)));
2605         return BinaryOperator::CreateAdd(Add, C1C2);
2606         
2607       }
2608
2609     // Try to fold constant mul into select arguments.
2610     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2611       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2612         return R;
2613
2614     if (isa<PHINode>(Op0))
2615       if (Instruction *NV = FoldOpIntoPhi(I))
2616         return NV;
2617   }
2618
2619   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2620     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2621       return BinaryOperator::CreateMul(Op0v, Op1v);
2622
2623   // (X / Y) *  Y = X - (X % Y)
2624   // (X / Y) * -Y = (X % Y) - X
2625   {
2626     Value *Op1 = I.getOperand(1);
2627     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2628     if (!BO ||
2629         (BO->getOpcode() != Instruction::UDiv && 
2630          BO->getOpcode() != Instruction::SDiv)) {
2631       Op1 = Op0;
2632       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2633     }
2634     Value *Neg = dyn_castNegVal(Op1);
2635     if (BO && BO->hasOneUse() &&
2636         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2637         (BO->getOpcode() == Instruction::UDiv ||
2638          BO->getOpcode() == Instruction::SDiv)) {
2639       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2640
2641       Instruction *Rem;
2642       if (BO->getOpcode() == Instruction::UDiv)
2643         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2644       else
2645         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2646
2647       InsertNewInstBefore(Rem, I);
2648       Rem->takeName(BO);
2649
2650       if (Op1BO == Op1)
2651         return BinaryOperator::CreateSub(Op0BO, Rem);
2652       else
2653         return BinaryOperator::CreateSub(Rem, Op0BO);
2654     }
2655   }
2656
2657   if (I.getType() == Type::Int1Ty)
2658     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2659
2660   // If one of the operands of the multiply is a cast from a boolean value, then
2661   // we know the bool is either zero or one, so this is a 'masking' multiply.
2662   // See if we can simplify things based on how the boolean was originally
2663   // formed.
2664   CastInst *BoolCast = 0;
2665   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2666     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2667       BoolCast = CI;
2668   if (!BoolCast)
2669     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2670       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2671         BoolCast = CI;
2672   if (BoolCast) {
2673     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2674       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2675       const Type *SCOpTy = SCIOp0->getType();
2676       bool TIS = false;
2677       
2678       // If the icmp is true iff the sign bit of X is set, then convert this
2679       // multiply into a shift/and combination.
2680       if (isa<ConstantInt>(SCIOp1) &&
2681           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2682           TIS) {
2683         // Shift the X value right to turn it into "all signbits".
2684         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2685                                           SCOpTy->getPrimitiveSizeInBits()-1);
2686         Value *V =
2687           InsertNewInstBefore(
2688             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2689                                             BoolCast->getOperand(0)->getName()+
2690                                             ".mask"), I);
2691
2692         // If the multiply type is not the same as the source type, sign extend
2693         // or truncate to the multiply type.
2694         if (I.getType() != V->getType()) {
2695           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2696           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2697           Instruction::CastOps opcode = 
2698             (SrcBits == DstBits ? Instruction::BitCast : 
2699              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2700           V = InsertCastBefore(opcode, V, I.getType(), I);
2701         }
2702
2703         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2704         return BinaryOperator::CreateAnd(V, OtherOp);
2705       }
2706     }
2707   }
2708
2709   return Changed ? &I : 0;
2710 }
2711
2712 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2713 /// instruction.
2714 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2715   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2716   
2717   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2718   int NonNullOperand = -1;
2719   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2720     if (ST->isNullValue())
2721       NonNullOperand = 2;
2722   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2723   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2724     if (ST->isNullValue())
2725       NonNullOperand = 1;
2726   
2727   if (NonNullOperand == -1)
2728     return false;
2729   
2730   Value *SelectCond = SI->getOperand(0);
2731   
2732   // Change the div/rem to use 'Y' instead of the select.
2733   I.setOperand(1, SI->getOperand(NonNullOperand));
2734   
2735   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2736   // problem.  However, the select, or the condition of the select may have
2737   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2738   // propagate the known value for the select into other uses of it, and
2739   // propagate a known value of the condition into its other users.
2740   
2741   // If the select and condition only have a single use, don't bother with this,
2742   // early exit.
2743   if (SI->use_empty() && SelectCond->hasOneUse())
2744     return true;
2745   
2746   // Scan the current block backward, looking for other uses of SI.
2747   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2748   
2749   while (BBI != BBFront) {
2750     --BBI;
2751     // If we found a call to a function, we can't assume it will return, so
2752     // information from below it cannot be propagated above it.
2753     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2754       break;
2755     
2756     // Replace uses of the select or its condition with the known values.
2757     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2758          I != E; ++I) {
2759       if (*I == SI) {
2760         *I = SI->getOperand(NonNullOperand);
2761         AddToWorkList(BBI);
2762       } else if (*I == SelectCond) {
2763         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2764                                    ConstantInt::getFalse();
2765         AddToWorkList(BBI);
2766       }
2767     }
2768     
2769     // If we past the instruction, quit looking for it.
2770     if (&*BBI == SI)
2771       SI = 0;
2772     if (&*BBI == SelectCond)
2773       SelectCond = 0;
2774     
2775     // If we ran out of things to eliminate, break out of the loop.
2776     if (SelectCond == 0 && SI == 0)
2777       break;
2778     
2779   }
2780   return true;
2781 }
2782
2783
2784 /// This function implements the transforms on div instructions that work
2785 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2786 /// used by the visitors to those instructions.
2787 /// @brief Transforms common to all three div instructions
2788 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2789   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2790
2791   // undef / X -> 0        for integer.
2792   // undef / X -> undef    for FP (the undef could be a snan).
2793   if (isa<UndefValue>(Op0)) {
2794     if (Op0->getType()->isFPOrFPVector())
2795       return ReplaceInstUsesWith(I, Op0);
2796     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2797   }
2798
2799   // X / undef -> undef
2800   if (isa<UndefValue>(Op1))
2801     return ReplaceInstUsesWith(I, Op1);
2802
2803   return 0;
2804 }
2805
2806 /// This function implements the transforms common to both integer division
2807 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2808 /// division instructions.
2809 /// @brief Common integer divide transforms
2810 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2811   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2812
2813   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2814   if (Op0 == Op1) {
2815     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2816       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2817       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2818       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2819     }
2820
2821     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2822     return ReplaceInstUsesWith(I, CI);
2823   }
2824   
2825   if (Instruction *Common = commonDivTransforms(I))
2826     return Common;
2827   
2828   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2829   // This does not apply for fdiv.
2830   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2831     return &I;
2832
2833   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2834     // div X, 1 == X
2835     if (RHS->equalsInt(1))
2836       return ReplaceInstUsesWith(I, Op0);
2837
2838     // (X / C1) / C2  -> X / (C1*C2)
2839     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2840       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2841         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2842           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2843             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2844           else 
2845             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2846                                           Multiply(RHS, LHSRHS));
2847         }
2848
2849     if (!RHS->isZero()) { // avoid X udiv 0
2850       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2851         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2852           return R;
2853       if (isa<PHINode>(Op0))
2854         if (Instruction *NV = FoldOpIntoPhi(I))
2855           return NV;
2856     }
2857   }
2858
2859   // 0 / X == 0, we don't need to preserve faults!
2860   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2861     if (LHS->equalsInt(0))
2862       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2863
2864   // It can't be division by zero, hence it must be division by one.
2865   if (I.getType() == Type::Int1Ty)
2866     return ReplaceInstUsesWith(I, Op0);
2867
2868   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2869     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2870       // div X, 1 == X
2871       if (X->isOne())
2872         return ReplaceInstUsesWith(I, Op0);
2873   }
2874
2875   return 0;
2876 }
2877
2878 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2879   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2880
2881   // Handle the integer div common cases
2882   if (Instruction *Common = commonIDivTransforms(I))
2883     return Common;
2884
2885   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2886     // X udiv C^2 -> X >> C
2887     // Check to see if this is an unsigned division with an exact power of 2,
2888     // if so, convert to a right shift.
2889     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2890       return BinaryOperator::CreateLShr(Op0, 
2891                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2892
2893     // X udiv C, where C >= signbit
2894     if (C->getValue().isNegative()) {
2895       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2896                                       I);
2897       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2898                                 ConstantInt::get(I.getType(), 1));
2899     }
2900   }
2901
2902   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2903   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2904     if (RHSI->getOpcode() == Instruction::Shl &&
2905         isa<ConstantInt>(RHSI->getOperand(0))) {
2906       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2907       if (C1.isPowerOf2()) {
2908         Value *N = RHSI->getOperand(1);
2909         const Type *NTy = N->getType();
2910         if (uint32_t C2 = C1.logBase2()) {
2911           Constant *C2V = ConstantInt::get(NTy, C2);
2912           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2913         }
2914         return BinaryOperator::CreateLShr(Op0, N);
2915       }
2916     }
2917   }
2918   
2919   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2920   // where C1&C2 are powers of two.
2921   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2922     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2923       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2924         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2925         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2926           // Compute the shift amounts
2927           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2928           // Construct the "on true" case of the select
2929           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2930           Instruction *TSI = BinaryOperator::CreateLShr(
2931                                                  Op0, TC, SI->getName()+".t");
2932           TSI = InsertNewInstBefore(TSI, I);
2933   
2934           // Construct the "on false" case of the select
2935           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2936           Instruction *FSI = BinaryOperator::CreateLShr(
2937                                                  Op0, FC, SI->getName()+".f");
2938           FSI = InsertNewInstBefore(FSI, I);
2939
2940           // construct the select instruction and return it.
2941           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2942         }
2943       }
2944   return 0;
2945 }
2946
2947 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2948   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2949
2950   // Handle the integer div common cases
2951   if (Instruction *Common = commonIDivTransforms(I))
2952     return Common;
2953
2954   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2955     // sdiv X, -1 == -X
2956     if (RHS->isAllOnesValue())
2957       return BinaryOperator::CreateNeg(Op0);
2958
2959     ConstantInt *RHSNeg = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
2960     APInt RHSNegAPI(RHSNeg->getBitWidth(), RHSNeg->getSExtValue(), true);
2961
2962     APInt NegOne = -APInt(RHSNeg->getBitWidth(), 1, true);
2963     APInt TwoToExp(RHSNeg->getBitWidth(), 1 << (RHSNeg->getBitWidth() - 1),
2964                    true);
2965
2966     // -X/C -> X/-C, if and only if negation doesn't overflow.
2967     if ((RHS->getSExtValue() < 0 && RHSNegAPI.slt(TwoToExp - 1)) ||
2968         (RHS->getSExtValue() > 0 && RHSNegAPI.sgt(TwoToExp * NegOne))) {
2969       if (Value *LHSNeg = dyn_castNegVal(Op0)) {
2970         if (ConstantInt *CI = dyn_cast<ConstantInt>(LHSNeg)) {
2971           ConstantInt *CINeg = cast<ConstantInt>(ConstantExpr::getNeg(CI));
2972           APInt CINegAPI(CINeg->getBitWidth(), CINeg->getSExtValue(), true);
2973
2974           if ((CI->getSExtValue() < 0 && CINegAPI.slt(TwoToExp - 1)) ||
2975               (CI->getSExtValue() > 0 && CINegAPI.sgt(TwoToExp * NegOne)))
2976             return BinaryOperator::CreateSDiv(LHSNeg,
2977                                               ConstantExpr::getNeg(RHS));
2978         }
2979       }
2980     }
2981   }
2982
2983   // If the sign bits of both operands are zero (i.e. we can prove they are
2984   // unsigned inputs), turn this into a udiv.
2985   if (I.getType()->isInteger()) {
2986     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2987     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2988       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2989       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2990     }
2991   }      
2992   
2993   return 0;
2994 }
2995
2996 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2997   return commonDivTransforms(I);
2998 }
2999
3000 /// This function implements the transforms on rem instructions that work
3001 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3002 /// is used by the visitors to those instructions.
3003 /// @brief Transforms common to all three rem instructions
3004 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3005   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3006
3007   // 0 % X == 0 for integer, we don't need to preserve faults!
3008   if (Constant *LHS = dyn_cast<Constant>(Op0))
3009     if (LHS->isNullValue())
3010       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3011
3012   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3013     if (I.getType()->isFPOrFPVector())
3014       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3015     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3016   }
3017   if (isa<UndefValue>(Op1))
3018     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3019
3020   // Handle cases involving: rem X, (select Cond, Y, Z)
3021   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3022     return &I;
3023
3024   return 0;
3025 }
3026
3027 /// This function implements the transforms common to both integer remainder
3028 /// instructions (urem and srem). It is called by the visitors to those integer
3029 /// remainder instructions.
3030 /// @brief Common integer remainder transforms
3031 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3032   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3033
3034   if (Instruction *common = commonRemTransforms(I))
3035     return common;
3036
3037   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3038     // X % 0 == undef, we don't need to preserve faults!
3039     if (RHS->equalsInt(0))
3040       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3041     
3042     if (RHS->equalsInt(1))  // X % 1 == 0
3043       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3044
3045     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3046       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3047         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3048           return R;
3049       } else if (isa<PHINode>(Op0I)) {
3050         if (Instruction *NV = FoldOpIntoPhi(I))
3051           return NV;
3052       }
3053
3054       // See if we can fold away this rem instruction.
3055       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3056       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3057       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3058                                KnownZero, KnownOne))
3059         return &I;
3060     }
3061   }
3062
3063   return 0;
3064 }
3065
3066 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3067   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3068
3069   if (Instruction *common = commonIRemTransforms(I))
3070     return common;
3071   
3072   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3073     // X urem C^2 -> X and C
3074     // Check to see if this is an unsigned remainder with an exact power of 2,
3075     // if so, convert to a bitwise and.
3076     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3077       if (C->getValue().isPowerOf2())
3078         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3079   }
3080
3081   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3082     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3083     if (RHSI->getOpcode() == Instruction::Shl &&
3084         isa<ConstantInt>(RHSI->getOperand(0))) {
3085       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3086         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3087         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3088                                                                    "tmp"), I);
3089         return BinaryOperator::CreateAnd(Op0, Add);
3090       }
3091     }
3092   }
3093
3094   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3095   // where C1&C2 are powers of two.
3096   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3097     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3098       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3099         // STO == 0 and SFO == 0 handled above.
3100         if ((STO->getValue().isPowerOf2()) && 
3101             (SFO->getValue().isPowerOf2())) {
3102           Value *TrueAnd = InsertNewInstBefore(
3103             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3104           Value *FalseAnd = InsertNewInstBefore(
3105             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3106           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3107         }
3108       }
3109   }
3110   
3111   return 0;
3112 }
3113
3114 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3115   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3116
3117   // Handle the integer rem common cases
3118   if (Instruction *common = commonIRemTransforms(I))
3119     return common;
3120   
3121   if (Value *RHSNeg = dyn_castNegVal(Op1))
3122     if (!isa<Constant>(RHSNeg) ||
3123         (isa<ConstantInt>(RHSNeg) &&
3124          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3125       // X % -Y -> X % Y
3126       AddUsesToWorkList(I);
3127       I.setOperand(1, RHSNeg);
3128       return &I;
3129     }
3130
3131   // If the sign bits of both operands are zero (i.e. we can prove they are
3132   // unsigned inputs), turn this into a urem.
3133   if (I.getType()->isInteger()) {
3134     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3135     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3136       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3137       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3138     }
3139   }
3140
3141   return 0;
3142 }
3143
3144 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3145   return commonRemTransforms(I);
3146 }
3147
3148 // isOneBitSet - Return true if there is exactly one bit set in the specified
3149 // constant.
3150 static bool isOneBitSet(const ConstantInt *CI) {
3151   return CI->getValue().isPowerOf2();
3152 }
3153
3154 // isHighOnes - Return true if the constant is of the form 1+0+.
3155 // This is the same as lowones(~X).
3156 static bool isHighOnes(const ConstantInt *CI) {
3157   return (~CI->getValue() + 1).isPowerOf2();
3158 }
3159
3160 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3161 /// are carefully arranged to allow folding of expressions such as:
3162 ///
3163 ///      (A < B) | (A > B) --> (A != B)
3164 ///
3165 /// Note that this is only valid if the first and second predicates have the
3166 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3167 ///
3168 /// Three bits are used to represent the condition, as follows:
3169 ///   0  A > B
3170 ///   1  A == B
3171 ///   2  A < B
3172 ///
3173 /// <=>  Value  Definition
3174 /// 000     0   Always false
3175 /// 001     1   A >  B
3176 /// 010     2   A == B
3177 /// 011     3   A >= B
3178 /// 100     4   A <  B
3179 /// 101     5   A != B
3180 /// 110     6   A <= B
3181 /// 111     7   Always true
3182 ///  
3183 static unsigned getICmpCode(const ICmpInst *ICI) {
3184   switch (ICI->getPredicate()) {
3185     // False -> 0
3186   case ICmpInst::ICMP_UGT: return 1;  // 001
3187   case ICmpInst::ICMP_SGT: return 1;  // 001
3188   case ICmpInst::ICMP_EQ:  return 2;  // 010
3189   case ICmpInst::ICMP_UGE: return 3;  // 011
3190   case ICmpInst::ICMP_SGE: return 3;  // 011
3191   case ICmpInst::ICMP_ULT: return 4;  // 100
3192   case ICmpInst::ICMP_SLT: return 4;  // 100
3193   case ICmpInst::ICMP_NE:  return 5;  // 101
3194   case ICmpInst::ICMP_ULE: return 6;  // 110
3195   case ICmpInst::ICMP_SLE: return 6;  // 110
3196     // True -> 7
3197   default:
3198     assert(0 && "Invalid ICmp predicate!");
3199     return 0;
3200   }
3201 }
3202
3203 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3204 /// predicate into a three bit mask. It also returns whether it is an ordered
3205 /// predicate by reference.
3206 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3207   isOrdered = false;
3208   switch (CC) {
3209   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3210   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3211   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3212   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3213   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3214   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3215   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3216   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3217   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3218   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3219   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3220   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3221   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3222   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3223     // True -> 7
3224   default:
3225     // Not expecting FCMP_FALSE and FCMP_TRUE;
3226     assert(0 && "Unexpected FCmp predicate!");
3227     return 0;
3228   }
3229 }
3230
3231 /// getICmpValue - This is the complement of getICmpCode, which turns an
3232 /// opcode and two operands into either a constant true or false, or a brand 
3233 /// new ICmp instruction. The sign is passed in to determine which kind
3234 /// of predicate to use in the new icmp instruction.
3235 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3236   switch (code) {
3237   default: assert(0 && "Illegal ICmp code!");
3238   case  0: return ConstantInt::getFalse();
3239   case  1: 
3240     if (sign)
3241       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3242     else
3243       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3244   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3245   case  3: 
3246     if (sign)
3247       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3248     else
3249       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3250   case  4: 
3251     if (sign)
3252       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3253     else
3254       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3255   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3256   case  6: 
3257     if (sign)
3258       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3259     else
3260       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3261   case  7: return ConstantInt::getTrue();
3262   }
3263 }
3264
3265 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3266 /// opcode and two operands into either a FCmp instruction. isordered is passed
3267 /// in to determine which kind of predicate to use in the new fcmp instruction.
3268 static Value *getFCmpValue(bool isordered, unsigned code,
3269                            Value *LHS, Value *RHS) {
3270   switch (code) {
3271   default: assert(0 && "Illegal FCmp code!");
3272   case  0:
3273     if (isordered)
3274       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3275     else
3276       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3277   case  1: 
3278     if (isordered)
3279       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3280     else
3281       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3282   case  2: 
3283     if (isordered)
3284       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3285     else
3286       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3287   case  3: 
3288     if (isordered)
3289       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3290     else
3291       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3292   case  4: 
3293     if (isordered)
3294       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3295     else
3296       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3297   case  5: 
3298     if (isordered)
3299       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3300     else
3301       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3302   case  6: 
3303     if (isordered)
3304       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3305     else
3306       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3307   case  7: return ConstantInt::getTrue();
3308   }
3309 }
3310
3311 /// PredicatesFoldable - Return true if both predicates match sign or if at
3312 /// least one of them is an equality comparison (which is signless).
3313 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3314   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3315          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3316          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3317 }
3318
3319 namespace { 
3320 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3321 struct FoldICmpLogical {
3322   InstCombiner &IC;
3323   Value *LHS, *RHS;
3324   ICmpInst::Predicate pred;
3325   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3326     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3327       pred(ICI->getPredicate()) {}
3328   bool shouldApply(Value *V) const {
3329     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3330       if (PredicatesFoldable(pred, ICI->getPredicate()))
3331         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3332                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3333     return false;
3334   }
3335   Instruction *apply(Instruction &Log) const {
3336     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3337     if (ICI->getOperand(0) != LHS) {
3338       assert(ICI->getOperand(1) == LHS);
3339       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3340     }
3341
3342     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3343     unsigned LHSCode = getICmpCode(ICI);
3344     unsigned RHSCode = getICmpCode(RHSICI);
3345     unsigned Code;
3346     switch (Log.getOpcode()) {
3347     case Instruction::And: Code = LHSCode & RHSCode; break;
3348     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3349     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3350     default: assert(0 && "Illegal logical opcode!"); return 0;
3351     }
3352
3353     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3354                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3355       
3356     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3357     if (Instruction *I = dyn_cast<Instruction>(RV))
3358       return I;
3359     // Otherwise, it's a constant boolean value...
3360     return IC.ReplaceInstUsesWith(Log, RV);
3361   }
3362 };
3363 } // end anonymous namespace
3364
3365 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3366 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3367 // guaranteed to be a binary operator.
3368 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3369                                     ConstantInt *OpRHS,
3370                                     ConstantInt *AndRHS,
3371                                     BinaryOperator &TheAnd) {
3372   Value *X = Op->getOperand(0);
3373   Constant *Together = 0;
3374   if (!Op->isShift())
3375     Together = And(AndRHS, OpRHS);
3376
3377   switch (Op->getOpcode()) {
3378   case Instruction::Xor:
3379     if (Op->hasOneUse()) {
3380       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3381       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3382       InsertNewInstBefore(And, TheAnd);
3383       And->takeName(Op);
3384       return BinaryOperator::CreateXor(And, Together);
3385     }
3386     break;
3387   case Instruction::Or:
3388     if (Together == AndRHS) // (X | C) & C --> C
3389       return ReplaceInstUsesWith(TheAnd, AndRHS);
3390
3391     if (Op->hasOneUse() && Together != OpRHS) {
3392       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3393       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3394       InsertNewInstBefore(Or, TheAnd);
3395       Or->takeName(Op);
3396       return BinaryOperator::CreateAnd(Or, AndRHS);
3397     }
3398     break;
3399   case Instruction::Add:
3400     if (Op->hasOneUse()) {
3401       // Adding a one to a single bit bit-field should be turned into an XOR
3402       // of the bit.  First thing to check is to see if this AND is with a
3403       // single bit constant.
3404       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3405
3406       // If there is only one bit set...
3407       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3408         // Ok, at this point, we know that we are masking the result of the
3409         // ADD down to exactly one bit.  If the constant we are adding has
3410         // no bits set below this bit, then we can eliminate the ADD.
3411         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3412
3413         // Check to see if any bits below the one bit set in AndRHSV are set.
3414         if ((AddRHS & (AndRHSV-1)) == 0) {
3415           // If not, the only thing that can effect the output of the AND is
3416           // the bit specified by AndRHSV.  If that bit is set, the effect of
3417           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3418           // no effect.
3419           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3420             TheAnd.setOperand(0, X);
3421             return &TheAnd;
3422           } else {
3423             // Pull the XOR out of the AND.
3424             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3425             InsertNewInstBefore(NewAnd, TheAnd);
3426             NewAnd->takeName(Op);
3427             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3428           }
3429         }
3430       }
3431     }
3432     break;
3433
3434   case Instruction::Shl: {
3435     // We know that the AND will not produce any of the bits shifted in, so if
3436     // the anded constant includes them, clear them now!
3437     //
3438     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3439     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3440     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3441     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3442
3443     if (CI->getValue() == ShlMask) { 
3444     // Masking out bits that the shift already masks
3445       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3446     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3447       TheAnd.setOperand(1, CI);
3448       return &TheAnd;
3449     }
3450     break;
3451   }
3452   case Instruction::LShr:
3453   {
3454     // We know that the AND will not produce any of the bits shifted in, so if
3455     // the anded constant includes them, clear them now!  This only applies to
3456     // unsigned shifts, because a signed shr may bring in set bits!
3457     //
3458     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3459     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3460     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3461     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3462
3463     if (CI->getValue() == ShrMask) {   
3464     // Masking out bits that the shift already masks.
3465       return ReplaceInstUsesWith(TheAnd, Op);
3466     } else if (CI != AndRHS) {
3467       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3468       return &TheAnd;
3469     }
3470     break;
3471   }
3472   case Instruction::AShr:
3473     // Signed shr.
3474     // See if this is shifting in some sign extension, then masking it out
3475     // with an and.
3476     if (Op->hasOneUse()) {
3477       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3478       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3479       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3480       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3481       if (C == AndRHS) {          // Masking out bits shifted in.
3482         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3483         // Make the argument unsigned.
3484         Value *ShVal = Op->getOperand(0);
3485         ShVal = InsertNewInstBefore(
3486             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3487                                    Op->getName()), TheAnd);
3488         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3489       }
3490     }
3491     break;
3492   }
3493   return 0;
3494 }
3495
3496
3497 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3498 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3499 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3500 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3501 /// insert new instructions.
3502 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3503                                            bool isSigned, bool Inside, 
3504                                            Instruction &IB) {
3505   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3506             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3507          "Lo is not <= Hi in range emission code!");
3508     
3509   if (Inside) {
3510     if (Lo == Hi)  // Trivially false.
3511       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3512
3513     // V >= Min && V < Hi --> V < Hi
3514     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3515       ICmpInst::Predicate pred = (isSigned ? 
3516         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3517       return new ICmpInst(pred, V, Hi);
3518     }
3519
3520     // Emit V-Lo <u Hi-Lo
3521     Constant *NegLo = ConstantExpr::getNeg(Lo);
3522     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3523     InsertNewInstBefore(Add, IB);
3524     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3525     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3526   }
3527
3528   if (Lo == Hi)  // Trivially true.
3529     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3530
3531   // V < Min || V >= Hi -> V > Hi-1
3532   Hi = SubOne(cast<ConstantInt>(Hi));
3533   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3534     ICmpInst::Predicate pred = (isSigned ? 
3535         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3536     return new ICmpInst(pred, V, Hi);
3537   }
3538
3539   // Emit V-Lo >u Hi-1-Lo
3540   // Note that Hi has already had one subtracted from it, above.
3541   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3542   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3543   InsertNewInstBefore(Add, IB);
3544   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3545   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3546 }
3547
3548 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3549 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3550 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3551 // not, since all 1s are not contiguous.
3552 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3553   const APInt& V = Val->getValue();
3554   uint32_t BitWidth = Val->getType()->getBitWidth();
3555   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3556
3557   // look for the first zero bit after the run of ones
3558   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3559   // look for the first non-zero bit
3560   ME = V.getActiveBits(); 
3561   return true;
3562 }
3563
3564 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3565 /// where isSub determines whether the operator is a sub.  If we can fold one of
3566 /// the following xforms:
3567 /// 
3568 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3569 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3570 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3571 ///
3572 /// return (A +/- B).
3573 ///
3574 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3575                                         ConstantInt *Mask, bool isSub,
3576                                         Instruction &I) {
3577   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3578   if (!LHSI || LHSI->getNumOperands() != 2 ||
3579       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3580
3581   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3582
3583   switch (LHSI->getOpcode()) {
3584   default: return 0;
3585   case Instruction::And:
3586     if (And(N, Mask) == Mask) {
3587       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3588       if ((Mask->getValue().countLeadingZeros() + 
3589            Mask->getValue().countPopulation()) == 
3590           Mask->getValue().getBitWidth())
3591         break;
3592
3593       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3594       // part, we don't need any explicit masks to take them out of A.  If that
3595       // is all N is, ignore it.
3596       uint32_t MB = 0, ME = 0;
3597       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3598         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3599         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3600         if (MaskedValueIsZero(RHS, Mask))
3601           break;
3602       }
3603     }
3604     return 0;
3605   case Instruction::Or:
3606   case Instruction::Xor:
3607     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3608     if ((Mask->getValue().countLeadingZeros() + 
3609          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3610         && And(N, Mask)->isZero())
3611       break;
3612     return 0;
3613   }
3614   
3615   Instruction *New;
3616   if (isSub)
3617     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3618   else
3619     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3620   return InsertNewInstBefore(New, I);
3621 }
3622
3623 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3624 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3625                                           ICmpInst *LHS, ICmpInst *RHS) {
3626   Value *Val, *Val2;
3627   ConstantInt *LHSCst, *RHSCst;
3628   ICmpInst::Predicate LHSCC, RHSCC;
3629   
3630   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3631   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3632       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3633     return 0;
3634   
3635   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3636   // where C is a power of 2
3637   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3638       LHSCst->getValue().isPowerOf2()) {
3639     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3640     InsertNewInstBefore(NewOr, I);
3641     return new ICmpInst(LHSCC, NewOr, LHSCst);
3642   }
3643   
3644   // From here on, we only handle:
3645   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3646   if (Val != Val2) return 0;
3647   
3648   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3649   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3650       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3651       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3652       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3653     return 0;
3654   
3655   // We can't fold (ugt x, C) & (sgt x, C2).
3656   if (!PredicatesFoldable(LHSCC, RHSCC))
3657     return 0;
3658     
3659   // Ensure that the larger constant is on the RHS.
3660   bool ShouldSwap;
3661   if (ICmpInst::isSignedPredicate(LHSCC) ||
3662       (ICmpInst::isEquality(LHSCC) && 
3663        ICmpInst::isSignedPredicate(RHSCC)))
3664     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3665   else
3666     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3667     
3668   if (ShouldSwap) {
3669     std::swap(LHS, RHS);
3670     std::swap(LHSCst, RHSCst);
3671     std::swap(LHSCC, RHSCC);
3672   }
3673
3674   // At this point, we know we have have two icmp instructions
3675   // comparing a value against two constants and and'ing the result
3676   // together.  Because of the above check, we know that we only have
3677   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3678   // (from the FoldICmpLogical check above), that the two constants 
3679   // are not equal and that the larger constant is on the RHS
3680   assert(LHSCst != RHSCst && "Compares not folded above?");
3681
3682   switch (LHSCC) {
3683   default: assert(0 && "Unknown integer condition code!");
3684   case ICmpInst::ICMP_EQ:
3685     switch (RHSCC) {
3686     default: assert(0 && "Unknown integer condition code!");
3687     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3688     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3689     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3690       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3691     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3692     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3693     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3694       return ReplaceInstUsesWith(I, LHS);
3695     }
3696   case ICmpInst::ICMP_NE:
3697     switch (RHSCC) {
3698     default: assert(0 && "Unknown integer condition code!");
3699     case ICmpInst::ICMP_ULT:
3700       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3701         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3702       break;                        // (X != 13 & X u< 15) -> no change
3703     case ICmpInst::ICMP_SLT:
3704       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3705         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3706       break;                        // (X != 13 & X s< 15) -> no change
3707     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3708     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3709     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3710       return ReplaceInstUsesWith(I, RHS);
3711     case ICmpInst::ICMP_NE:
3712       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3713         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3714         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3715                                                      Val->getName()+".off");
3716         InsertNewInstBefore(Add, I);
3717         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3718                             ConstantInt::get(Add->getType(), 1));
3719       }
3720       break;                        // (X != 13 & X != 15) -> no change
3721     }
3722     break;
3723   case ICmpInst::ICMP_ULT:
3724     switch (RHSCC) {
3725     default: assert(0 && "Unknown integer condition code!");
3726     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3727     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3728       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3729     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3730       break;
3731     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3732     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3733       return ReplaceInstUsesWith(I, LHS);
3734     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3735       break;
3736     }
3737     break;
3738   case ICmpInst::ICMP_SLT:
3739     switch (RHSCC) {
3740     default: assert(0 && "Unknown integer condition code!");
3741     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3742     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3743       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3744     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3745       break;
3746     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3747     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3748       return ReplaceInstUsesWith(I, LHS);
3749     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3750       break;
3751     }
3752     break;
3753   case ICmpInst::ICMP_UGT:
3754     switch (RHSCC) {
3755     default: assert(0 && "Unknown integer condition code!");
3756     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3757     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3758       return ReplaceInstUsesWith(I, RHS);
3759     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3760       break;
3761     case ICmpInst::ICMP_NE:
3762       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3763         return new ICmpInst(LHSCC, Val, RHSCst);
3764       break;                        // (X u> 13 & X != 15) -> no change
3765     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3766       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3767     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3768       break;
3769     }
3770     break;
3771   case ICmpInst::ICMP_SGT:
3772     switch (RHSCC) {
3773     default: assert(0 && "Unknown integer condition code!");
3774     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3775     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3776       return ReplaceInstUsesWith(I, RHS);
3777     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3778       break;
3779     case ICmpInst::ICMP_NE:
3780       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3781         return new ICmpInst(LHSCC, Val, RHSCst);
3782       break;                        // (X s> 13 & X != 15) -> no change
3783     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3784       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3785     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3786       break;
3787     }
3788     break;
3789   }
3790  
3791   return 0;
3792 }
3793
3794
3795 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3796   bool Changed = SimplifyCommutative(I);
3797   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3798
3799   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3800     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3801
3802   // and X, X = X
3803   if (Op0 == Op1)
3804     return ReplaceInstUsesWith(I, Op1);
3805
3806   // See if we can simplify any instructions used by the instruction whose sole 
3807   // purpose is to compute bits we don't care about.
3808   if (!isa<VectorType>(I.getType())) {
3809     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3810     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3811     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3812                              KnownZero, KnownOne))
3813       return &I;
3814   } else {
3815     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3816       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3817         return ReplaceInstUsesWith(I, I.getOperand(0));
3818     } else if (isa<ConstantAggregateZero>(Op1)) {
3819       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3820     }
3821   }
3822   
3823   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3824     const APInt& AndRHSMask = AndRHS->getValue();
3825     APInt NotAndRHS(~AndRHSMask);
3826
3827     // Optimize a variety of ((val OP C1) & C2) combinations...
3828     if (isa<BinaryOperator>(Op0)) {
3829       Instruction *Op0I = cast<Instruction>(Op0);
3830       Value *Op0LHS = Op0I->getOperand(0);
3831       Value *Op0RHS = Op0I->getOperand(1);
3832       switch (Op0I->getOpcode()) {
3833       case Instruction::Xor:
3834       case Instruction::Or:
3835         // If the mask is only needed on one incoming arm, push it up.
3836         if (Op0I->hasOneUse()) {
3837           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3838             // Not masking anything out for the LHS, move to RHS.
3839             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3840                                                    Op0RHS->getName()+".masked");
3841             InsertNewInstBefore(NewRHS, I);
3842             return BinaryOperator::Create(
3843                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3844           }
3845           if (!isa<Constant>(Op0RHS) &&
3846               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3847             // Not masking anything out for the RHS, move to LHS.
3848             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3849                                                    Op0LHS->getName()+".masked");
3850             InsertNewInstBefore(NewLHS, I);
3851             return BinaryOperator::Create(
3852                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3853           }
3854         }
3855
3856         break;
3857       case Instruction::Add:
3858         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3859         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3860         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3861         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3862           return BinaryOperator::CreateAnd(V, AndRHS);
3863         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3864           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3865         break;
3866
3867       case Instruction::Sub:
3868         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3869         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3870         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3871         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3872           return BinaryOperator::CreateAnd(V, AndRHS);
3873
3874         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3875         // has 1's for all bits that the subtraction with A might affect.
3876         if (Op0I->hasOneUse()) {
3877           uint32_t BitWidth = AndRHSMask.getBitWidth();
3878           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3879           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3880
3881           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3882           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3883               MaskedValueIsZero(Op0LHS, Mask)) {
3884             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3885             InsertNewInstBefore(NewNeg, I);
3886             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3887           }
3888         }
3889         break;
3890
3891       case Instruction::Shl:
3892       case Instruction::LShr:
3893         // (1 << x) & 1 --> zext(x == 0)
3894         // (1 >> x) & 1 --> zext(x == 0)
3895         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3896           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3897                                            Constant::getNullValue(I.getType()));
3898           InsertNewInstBefore(NewICmp, I);
3899           return new ZExtInst(NewICmp, I.getType());
3900         }
3901         break;
3902       }
3903
3904       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3905         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3906           return Res;
3907     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3908       // If this is an integer truncation or change from signed-to-unsigned, and
3909       // if the source is an and/or with immediate, transform it.  This
3910       // frequently occurs for bitfield accesses.
3911       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3912         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3913             CastOp->getNumOperands() == 2)
3914           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3915             if (CastOp->getOpcode() == Instruction::And) {
3916               // Change: and (cast (and X, C1) to T), C2
3917               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3918               // This will fold the two constants together, which may allow 
3919               // other simplifications.
3920               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3921                 CastOp->getOperand(0), I.getType(), 
3922                 CastOp->getName()+".shrunk");
3923               NewCast = InsertNewInstBefore(NewCast, I);
3924               // trunc_or_bitcast(C1)&C2
3925               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3926               C3 = ConstantExpr::getAnd(C3, AndRHS);
3927               return BinaryOperator::CreateAnd(NewCast, C3);
3928             } else if (CastOp->getOpcode() == Instruction::Or) {
3929               // Change: and (cast (or X, C1) to T), C2
3930               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3931               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3932               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3933                 return ReplaceInstUsesWith(I, AndRHS);
3934             }
3935           }
3936       }
3937     }
3938
3939     // Try to fold constant and into select arguments.
3940     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3941       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3942         return R;
3943     if (isa<PHINode>(Op0))
3944       if (Instruction *NV = FoldOpIntoPhi(I))
3945         return NV;
3946   }
3947
3948   Value *Op0NotVal = dyn_castNotVal(Op0);
3949   Value *Op1NotVal = dyn_castNotVal(Op1);
3950
3951   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3952     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3953
3954   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3955   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3956     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3957                                                I.getName()+".demorgan");
3958     InsertNewInstBefore(Or, I);
3959     return BinaryOperator::CreateNot(Or);
3960   }
3961   
3962   {
3963     Value *A = 0, *B = 0, *C = 0, *D = 0;
3964     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3965       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3966         return ReplaceInstUsesWith(I, Op1);
3967     
3968       // (A|B) & ~(A&B) -> A^B
3969       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3970         if ((A == C && B == D) || (A == D && B == C))
3971           return BinaryOperator::CreateXor(A, B);
3972       }
3973     }
3974     
3975     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3976       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3977         return ReplaceInstUsesWith(I, Op0);
3978
3979       // ~(A&B) & (A|B) -> A^B
3980       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3981         if ((A == C && B == D) || (A == D && B == C))
3982           return BinaryOperator::CreateXor(A, B);
3983       }
3984     }
3985     
3986     if (Op0->hasOneUse() &&
3987         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3988       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3989         I.swapOperands();     // Simplify below
3990         std::swap(Op0, Op1);
3991       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3992         cast<BinaryOperator>(Op0)->swapOperands();
3993         I.swapOperands();     // Simplify below
3994         std::swap(Op0, Op1);
3995       }
3996     }
3997     if (Op1->hasOneUse() &&
3998         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3999       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4000         cast<BinaryOperator>(Op1)->swapOperands();
4001         std::swap(A, B);
4002       }
4003       if (A == Op0) {                                // A&(A^B) -> A & ~B
4004         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4005         InsertNewInstBefore(NotB, I);
4006         return BinaryOperator::CreateAnd(A, NotB);
4007       }
4008     }
4009   }
4010   
4011   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4012     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4013     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4014       return R;
4015
4016     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4017       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4018         return Res;
4019   }
4020
4021   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4022   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4023     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4024       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4025         const Type *SrcTy = Op0C->getOperand(0)->getType();
4026         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4027             // Only do this if the casts both really cause code to be generated.
4028             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4029                               I.getType(), TD) &&
4030             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4031                               I.getType(), TD)) {
4032           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4033                                                          Op1C->getOperand(0),
4034                                                          I.getName());
4035           InsertNewInstBefore(NewOp, I);
4036           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4037         }
4038       }
4039     
4040   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4041   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4042     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4043       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4044           SI0->getOperand(1) == SI1->getOperand(1) &&
4045           (SI0->hasOneUse() || SI1->hasOneUse())) {
4046         Instruction *NewOp =
4047           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4048                                                         SI1->getOperand(0),
4049                                                         SI0->getName()), I);
4050         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4051                                       SI1->getOperand(1));
4052       }
4053   }
4054
4055   // If and'ing two fcmp, try combine them into one.
4056   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4057     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4058       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4059           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4060         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4061         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4062           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4063             // If either of the constants are nans, then the whole thing returns
4064             // false.
4065             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4066               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4067             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4068                                 RHS->getOperand(0));
4069           }
4070       } else {
4071         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4072         FCmpInst::Predicate Op0CC, Op1CC;
4073         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4074             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4075           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4076             // Swap RHS operands to match LHS.
4077             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4078             std::swap(Op1LHS, Op1RHS);
4079           }
4080           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4081             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4082             if (Op0CC == Op1CC)
4083               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4084             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4085                      Op1CC == FCmpInst::FCMP_FALSE)
4086               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4087             else if (Op0CC == FCmpInst::FCMP_TRUE)
4088               return ReplaceInstUsesWith(I, Op1);
4089             else if (Op1CC == FCmpInst::FCMP_TRUE)
4090               return ReplaceInstUsesWith(I, Op0);
4091             bool Op0Ordered;
4092             bool Op1Ordered;
4093             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4094             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4095             if (Op1Pred == 0) {
4096               std::swap(Op0, Op1);
4097               std::swap(Op0Pred, Op1Pred);
4098               std::swap(Op0Ordered, Op1Ordered);
4099             }
4100             if (Op0Pred == 0) {
4101               // uno && ueq -> uno && (uno || eq) -> ueq
4102               // ord && olt -> ord && (ord && lt) -> olt
4103               if (Op0Ordered == Op1Ordered)
4104                 return ReplaceInstUsesWith(I, Op1);
4105               // uno && oeq -> uno && (ord && eq) -> false
4106               // uno && ord -> false
4107               if (!Op0Ordered)
4108                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4109               // ord && ueq -> ord && (uno || eq) -> oeq
4110               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4111                                                     Op0LHS, Op0RHS));
4112             }
4113           }
4114         }
4115       }
4116     }
4117   }
4118
4119   return Changed ? &I : 0;
4120 }
4121
4122 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4123 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4124 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4125 /// the expression came from the corresponding "byte swapped" byte in some other
4126 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4127 /// we know that the expression deposits the low byte of %X into the high byte
4128 /// of the bswap result and that all other bytes are zero.  This expression is
4129 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4130 /// match.
4131 ///
4132 /// This function returns true if the match was unsuccessful and false if so.
4133 /// On entry to the function the "OverallLeftShift" is a signed integer value
4134 /// indicating the number of bytes that the subexpression is later shifted.  For
4135 /// example, if the expression is later right shifted by 16 bits, the
4136 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4137 /// byte of ByteValues is actually being set.
4138 ///
4139 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4140 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4141 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4142 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4143 /// always in the local (OverallLeftShift) coordinate space.
4144 ///
4145 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4146                               SmallVector<Value*, 8> &ByteValues) {
4147   if (Instruction *I = dyn_cast<Instruction>(V)) {
4148     // If this is an or instruction, it may be an inner node of the bswap.
4149     if (I->getOpcode() == Instruction::Or) {
4150       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4151                                ByteValues) ||
4152              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4153                                ByteValues);
4154     }
4155   
4156     // If this is a logical shift by a constant multiple of 8, recurse with
4157     // OverallLeftShift and ByteMask adjusted.
4158     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4159       unsigned ShAmt = 
4160         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4161       // Ensure the shift amount is defined and of a byte value.
4162       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4163         return true;
4164
4165       unsigned ByteShift = ShAmt >> 3;
4166       if (I->getOpcode() == Instruction::Shl) {
4167         // X << 2 -> collect(X, +2)
4168         OverallLeftShift += ByteShift;
4169         ByteMask >>= ByteShift;
4170       } else {
4171         // X >>u 2 -> collect(X, -2)
4172         OverallLeftShift -= ByteShift;
4173         ByteMask <<= ByteShift;
4174         ByteMask &= (~0U >> (32-ByteValues.size()));
4175       }
4176
4177       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4178       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4179
4180       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4181                                ByteValues);
4182     }
4183
4184     // If this is a logical 'and' with a mask that clears bytes, clear the
4185     // corresponding bytes in ByteMask.
4186     if (I->getOpcode() == Instruction::And &&
4187         isa<ConstantInt>(I->getOperand(1))) {
4188       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4189       unsigned NumBytes = ByteValues.size();
4190       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4191       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4192       
4193       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4194         // If this byte is masked out by a later operation, we don't care what
4195         // the and mask is.
4196         if ((ByteMask & (1 << i)) == 0)
4197           continue;
4198         
4199         // If the AndMask is all zeros for this byte, clear the bit.
4200         APInt MaskB = AndMask & Byte;
4201         if (MaskB == 0) {
4202           ByteMask &= ~(1U << i);
4203           continue;
4204         }
4205         
4206         // If the AndMask is not all ones for this byte, it's not a bytezap.
4207         if (MaskB != Byte)
4208           return true;
4209
4210         // Otherwise, this byte is kept.
4211       }
4212
4213       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4214                                ByteValues);
4215     }
4216   }
4217   
4218   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4219   // the input value to the bswap.  Some observations: 1) if more than one byte
4220   // is demanded from this input, then it could not be successfully assembled
4221   // into a byteswap.  At least one of the two bytes would not be aligned with
4222   // their ultimate destination.
4223   if (!isPowerOf2_32(ByteMask)) return true;
4224   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4225   
4226   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4227   // is demanded, it needs to go into byte 0 of the result.  This means that the
4228   // byte needs to be shifted until it lands in the right byte bucket.  The
4229   // shift amount depends on the position: if the byte is coming from the high
4230   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4231   // low part, it must be shifted left.
4232   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4233   if (InputByteNo < ByteValues.size()/2) {
4234     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4235       return true;
4236   } else {
4237     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4238       return true;
4239   }
4240   
4241   // If the destination byte value is already defined, the values are or'd
4242   // together, which isn't a bswap (unless it's an or of the same bits).
4243   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4244     return true;
4245   ByteValues[DestByteNo] = V;
4246   return false;
4247 }
4248
4249 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4250 /// If so, insert the new bswap intrinsic and return it.
4251 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4252   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4253   if (!ITy || ITy->getBitWidth() % 16 || 
4254       // ByteMask only allows up to 32-byte values.
4255       ITy->getBitWidth() > 32*8) 
4256     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4257   
4258   /// ByteValues - For each byte of the result, we keep track of which value
4259   /// defines each byte.
4260   SmallVector<Value*, 8> ByteValues;
4261   ByteValues.resize(ITy->getBitWidth()/8);
4262     
4263   // Try to find all the pieces corresponding to the bswap.
4264   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4265   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4266     return 0;
4267   
4268   // Check to see if all of the bytes come from the same value.
4269   Value *V = ByteValues[0];
4270   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4271   
4272   // Check to make sure that all of the bytes come from the same value.
4273   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4274     if (ByteValues[i] != V)
4275       return 0;
4276   const Type *Tys[] = { ITy };
4277   Module *M = I.getParent()->getParent()->getParent();
4278   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4279   return CallInst::Create(F, V);
4280 }
4281
4282 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4283 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4284 /// we can simplify this expression to "cond ? C : D or B".
4285 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4286                                          Value *C, Value *D) {
4287   // If A is not a select of -1/0, this cannot match.
4288   Value *Cond = 0;
4289   if (!match(A, m_SelectCst(m_Value(Cond), -1, 0)))
4290     return 0;
4291
4292   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4293   if (match(D, m_SelectCst(m_Specific(Cond), 0, -1)))
4294     return SelectInst::Create(Cond, C, B);
4295   if (match(D, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4296     return SelectInst::Create(Cond, C, B);
4297   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4298   if (match(B, m_SelectCst(m_Specific(Cond), 0, -1)))
4299     return SelectInst::Create(Cond, C, D);
4300   if (match(B, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4301     return SelectInst::Create(Cond, C, D);
4302   return 0;
4303 }
4304
4305 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4306 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4307                                          ICmpInst *LHS, ICmpInst *RHS) {
4308   Value *Val, *Val2;
4309   ConstantInt *LHSCst, *RHSCst;
4310   ICmpInst::Predicate LHSCC, RHSCC;
4311   
4312   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4313   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4314       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4315     return 0;
4316   
4317   // From here on, we only handle:
4318   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4319   if (Val != Val2) return 0;
4320   
4321   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4322   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4323       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4324       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4325       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4326     return 0;
4327   
4328   // We can't fold (ugt x, C) | (sgt x, C2).
4329   if (!PredicatesFoldable(LHSCC, RHSCC))
4330     return 0;
4331   
4332   // Ensure that the larger constant is on the RHS.
4333   bool ShouldSwap;
4334   if (ICmpInst::isSignedPredicate(LHSCC) ||
4335       (ICmpInst::isEquality(LHSCC) && 
4336        ICmpInst::isSignedPredicate(RHSCC)))
4337     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4338   else
4339     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4340   
4341   if (ShouldSwap) {
4342     std::swap(LHS, RHS);
4343     std::swap(LHSCst, RHSCst);
4344     std::swap(LHSCC, RHSCC);
4345   }
4346   
4347   // At this point, we know we have have two icmp instructions
4348   // comparing a value against two constants and or'ing the result
4349   // together.  Because of the above check, we know that we only have
4350   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4351   // FoldICmpLogical check above), that the two constants are not
4352   // equal.
4353   assert(LHSCst != RHSCst && "Compares not folded above?");
4354
4355   switch (LHSCC) {
4356   default: assert(0 && "Unknown integer condition code!");
4357   case ICmpInst::ICMP_EQ:
4358     switch (RHSCC) {
4359     default: assert(0 && "Unknown integer condition code!");
4360     case ICmpInst::ICMP_EQ:
4361       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4362         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4363         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4364                                                      Val->getName()+".off");
4365         InsertNewInstBefore(Add, I);
4366         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4367         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4368       }
4369       break;                         // (X == 13 | X == 15) -> no change
4370     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4371     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4372       break;
4373     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4374     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4375     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4376       return ReplaceInstUsesWith(I, RHS);
4377     }
4378     break;
4379   case ICmpInst::ICMP_NE:
4380     switch (RHSCC) {
4381     default: assert(0 && "Unknown integer condition code!");
4382     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4383     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4384     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4385       return ReplaceInstUsesWith(I, LHS);
4386     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4387     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4388     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4389       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4390     }
4391     break;
4392   case ICmpInst::ICMP_ULT:
4393     switch (RHSCC) {
4394     default: assert(0 && "Unknown integer condition code!");
4395     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4396       break;
4397     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4398       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4399       // this can cause overflow.
4400       if (RHSCst->isMaxValue(false))
4401         return ReplaceInstUsesWith(I, LHS);
4402       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4403     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4404       break;
4405     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4406     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4407       return ReplaceInstUsesWith(I, RHS);
4408     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4409       break;
4410     }
4411     break;
4412   case ICmpInst::ICMP_SLT:
4413     switch (RHSCC) {
4414     default: assert(0 && "Unknown integer condition code!");
4415     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4416       break;
4417     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4418       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4419       // this can cause overflow.
4420       if (RHSCst->isMaxValue(true))
4421         return ReplaceInstUsesWith(I, LHS);
4422       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4423     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4424       break;
4425     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4426     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4427       return ReplaceInstUsesWith(I, RHS);
4428     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4429       break;
4430     }
4431     break;
4432   case ICmpInst::ICMP_UGT:
4433     switch (RHSCC) {
4434     default: assert(0 && "Unknown integer condition code!");
4435     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4436     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4437       return ReplaceInstUsesWith(I, LHS);
4438     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4439       break;
4440     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4441     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4442       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4443     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4444       break;
4445     }
4446     break;
4447   case ICmpInst::ICMP_SGT:
4448     switch (RHSCC) {
4449     default: assert(0 && "Unknown integer condition code!");
4450     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4451     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4452       return ReplaceInstUsesWith(I, LHS);
4453     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4454       break;
4455     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4456     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4457       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4458     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4459       break;
4460     }
4461     break;
4462   }
4463   return 0;
4464 }
4465
4466 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4467   bool Changed = SimplifyCommutative(I);
4468   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4469
4470   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4471     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4472
4473   // or X, X = X
4474   if (Op0 == Op1)
4475     return ReplaceInstUsesWith(I, Op0);
4476
4477   // See if we can simplify any instructions used by the instruction whose sole 
4478   // purpose is to compute bits we don't care about.
4479   if (!isa<VectorType>(I.getType())) {
4480     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4481     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4482     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4483                              KnownZero, KnownOne))
4484       return &I;
4485   } else if (isa<ConstantAggregateZero>(Op1)) {
4486     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4487   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4488     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4489       return ReplaceInstUsesWith(I, I.getOperand(1));
4490   }
4491     
4492
4493   
4494   // or X, -1 == -1
4495   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4496     ConstantInt *C1 = 0; Value *X = 0;
4497     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4498     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4499       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4500       InsertNewInstBefore(Or, I);
4501       Or->takeName(Op0);
4502       return BinaryOperator::CreateAnd(Or, 
4503                ConstantInt::get(RHS->getValue() | C1->getValue()));
4504     }
4505
4506     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4507     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4508       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4509       InsertNewInstBefore(Or, I);
4510       Or->takeName(Op0);
4511       return BinaryOperator::CreateXor(Or,
4512                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4513     }
4514
4515     // Try to fold constant and into select arguments.
4516     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4517       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4518         return R;
4519     if (isa<PHINode>(Op0))
4520       if (Instruction *NV = FoldOpIntoPhi(I))
4521         return NV;
4522   }
4523
4524   Value *A = 0, *B = 0;
4525   ConstantInt *C1 = 0, *C2 = 0;
4526
4527   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4528     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4529       return ReplaceInstUsesWith(I, Op1);
4530   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4531     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4532       return ReplaceInstUsesWith(I, Op0);
4533
4534   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4535   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4536   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4537       match(Op1, m_Or(m_Value(), m_Value())) ||
4538       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4539        match(Op1, m_Shift(m_Value(), m_Value())))) {
4540     if (Instruction *BSwap = MatchBSwap(I))
4541       return BSwap;
4542   }
4543   
4544   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4545   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4546       MaskedValueIsZero(Op1, C1->getValue())) {
4547     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4548     InsertNewInstBefore(NOr, I);
4549     NOr->takeName(Op0);
4550     return BinaryOperator::CreateXor(NOr, C1);
4551   }
4552
4553   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4554   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4555       MaskedValueIsZero(Op0, C1->getValue())) {
4556     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4557     InsertNewInstBefore(NOr, I);
4558     NOr->takeName(Op0);
4559     return BinaryOperator::CreateXor(NOr, C1);
4560   }
4561
4562   // (A & C)|(B & D)
4563   Value *C = 0, *D = 0;
4564   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4565       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4566     Value *V1 = 0, *V2 = 0, *V3 = 0;
4567     C1 = dyn_cast<ConstantInt>(C);
4568     C2 = dyn_cast<ConstantInt>(D);
4569     if (C1 && C2) {  // (A & C1)|(B & C2)
4570       // If we have: ((V + N) & C1) | (V & C2)
4571       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4572       // replace with V+N.
4573       if (C1->getValue() == ~C2->getValue()) {
4574         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4575             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4576           // Add commutes, try both ways.
4577           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4578             return ReplaceInstUsesWith(I, A);
4579           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4580             return ReplaceInstUsesWith(I, A);
4581         }
4582         // Or commutes, try both ways.
4583         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4584             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4585           // Add commutes, try both ways.
4586           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4587             return ReplaceInstUsesWith(I, B);
4588           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4589             return ReplaceInstUsesWith(I, B);
4590         }
4591       }
4592       V1 = 0; V2 = 0; V3 = 0;
4593     }
4594     
4595     // Check to see if we have any common things being and'ed.  If so, find the
4596     // terms for V1 & (V2|V3).
4597     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4598       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4599         V1 = A, V2 = C, V3 = D;
4600       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4601         V1 = A, V2 = B, V3 = C;
4602       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4603         V1 = C, V2 = A, V3 = D;
4604       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4605         V1 = C, V2 = A, V3 = B;
4606       
4607       if (V1) {
4608         Value *Or =
4609           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4610         return BinaryOperator::CreateAnd(V1, Or);
4611       }
4612     }
4613
4614     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4615     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4616       return Match;
4617     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4618       return Match;
4619     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4620       return Match;
4621     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4622       return Match;
4623   }
4624   
4625   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4626   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4627     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4628       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4629           SI0->getOperand(1) == SI1->getOperand(1) &&
4630           (SI0->hasOneUse() || SI1->hasOneUse())) {
4631         Instruction *NewOp =
4632         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4633                                                      SI1->getOperand(0),
4634                                                      SI0->getName()), I);
4635         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4636                                       SI1->getOperand(1));
4637       }
4638   }
4639
4640   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4641     if (A == Op1)   // ~A | A == -1
4642       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4643   } else {
4644     A = 0;
4645   }
4646   // Note, A is still live here!
4647   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4648     if (Op0 == B)
4649       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4650
4651     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4652     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4653       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4654                                               I.getName()+".demorgan"), I);
4655       return BinaryOperator::CreateNot(And);
4656     }
4657   }
4658
4659   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4660   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4661     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4662       return R;
4663
4664     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4665       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4666         return Res;
4667   }
4668     
4669   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4670   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4671     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4672       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4673         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4674             !isa<ICmpInst>(Op1C->getOperand(0))) {
4675           const Type *SrcTy = Op0C->getOperand(0)->getType();
4676           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4677               // Only do this if the casts both really cause code to be
4678               // generated.
4679               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4680                                 I.getType(), TD) &&
4681               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4682                                 I.getType(), TD)) {
4683             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4684                                                           Op1C->getOperand(0),
4685                                                           I.getName());
4686             InsertNewInstBefore(NewOp, I);
4687             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4688           }
4689         }
4690       }
4691   }
4692   
4693     
4694   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4695   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4696     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4697       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4698           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4699           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4700         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4701           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4702             // If either of the constants are nans, then the whole thing returns
4703             // true.
4704             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4705               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4706             
4707             // Otherwise, no need to compare the two constants, compare the
4708             // rest.
4709             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4710                                 RHS->getOperand(0));
4711           }
4712       } else {
4713         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4714         FCmpInst::Predicate Op0CC, Op1CC;
4715         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4716             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4717           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4718             // Swap RHS operands to match LHS.
4719             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4720             std::swap(Op1LHS, Op1RHS);
4721           }
4722           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4723             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4724             if (Op0CC == Op1CC)
4725               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4726             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4727                      Op1CC == FCmpInst::FCMP_TRUE)
4728               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4729             else if (Op0CC == FCmpInst::FCMP_FALSE)
4730               return ReplaceInstUsesWith(I, Op1);
4731             else if (Op1CC == FCmpInst::FCMP_FALSE)
4732               return ReplaceInstUsesWith(I, Op0);
4733             bool Op0Ordered;
4734             bool Op1Ordered;
4735             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4736             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4737             if (Op0Ordered == Op1Ordered) {
4738               // If both are ordered or unordered, return a new fcmp with
4739               // or'ed predicates.
4740               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4741                                        Op0LHS, Op0RHS);
4742               if (Instruction *I = dyn_cast<Instruction>(RV))
4743                 return I;
4744               // Otherwise, it's a constant boolean value...
4745               return ReplaceInstUsesWith(I, RV);
4746             }
4747           }
4748         }
4749       }
4750     }
4751   }
4752
4753   return Changed ? &I : 0;
4754 }
4755
4756 namespace {
4757
4758 // XorSelf - Implements: X ^ X --> 0
4759 struct XorSelf {
4760   Value *RHS;
4761   XorSelf(Value *rhs) : RHS(rhs) {}
4762   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4763   Instruction *apply(BinaryOperator &Xor) const {
4764     return &Xor;
4765   }
4766 };
4767
4768 }
4769
4770 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4771   bool Changed = SimplifyCommutative(I);
4772   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4773
4774   if (isa<UndefValue>(Op1)) {
4775     if (isa<UndefValue>(Op0))
4776       // Handle undef ^ undef -> 0 special case. This is a common
4777       // idiom (misuse).
4778       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4779     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4780   }
4781
4782   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4783   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4784     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4785     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4786   }
4787   
4788   // See if we can simplify any instructions used by the instruction whose sole 
4789   // purpose is to compute bits we don't care about.
4790   if (!isa<VectorType>(I.getType())) {
4791     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4792     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4793     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4794                              KnownZero, KnownOne))
4795       return &I;
4796   } else if (isa<ConstantAggregateZero>(Op1)) {
4797     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4798   }
4799
4800   // Is this a ~ operation?
4801   if (Value *NotOp = dyn_castNotVal(&I)) {
4802     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4803     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4804     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4805       if (Op0I->getOpcode() == Instruction::And || 
4806           Op0I->getOpcode() == Instruction::Or) {
4807         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4808         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4809           Instruction *NotY =
4810             BinaryOperator::CreateNot(Op0I->getOperand(1),
4811                                       Op0I->getOperand(1)->getName()+".not");
4812           InsertNewInstBefore(NotY, I);
4813           if (Op0I->getOpcode() == Instruction::And)
4814             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4815           else
4816             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4817         }
4818       }
4819     }
4820   }
4821   
4822   
4823   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4824     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4825     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4826       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4827         return new ICmpInst(ICI->getInversePredicate(),
4828                             ICI->getOperand(0), ICI->getOperand(1));
4829
4830       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4831         return new FCmpInst(FCI->getInversePredicate(),
4832                             FCI->getOperand(0), FCI->getOperand(1));
4833     }
4834
4835     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4836     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4837       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4838         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4839           Instruction::CastOps Opcode = Op0C->getOpcode();
4840           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4841             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4842                                              Op0C->getDestTy())) {
4843               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4844                                      CI->getOpcode(), CI->getInversePredicate(),
4845                                      CI->getOperand(0), CI->getOperand(1)), I);
4846               NewCI->takeName(CI);
4847               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4848             }
4849           }
4850         }
4851       }
4852     }
4853
4854     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4855       // ~(c-X) == X-c-1 == X+(-c-1)
4856       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4857         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4858           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4859           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4860                                               ConstantInt::get(I.getType(), 1));
4861           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4862         }
4863           
4864       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4865         if (Op0I->getOpcode() == Instruction::Add) {
4866           // ~(X-c) --> (-c-1)-X
4867           if (RHS->isAllOnesValue()) {
4868             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4869             return BinaryOperator::CreateSub(
4870                            ConstantExpr::getSub(NegOp0CI,
4871                                              ConstantInt::get(I.getType(), 1)),
4872                                           Op0I->getOperand(0));
4873           } else if (RHS->getValue().isSignBit()) {
4874             // (X + C) ^ signbit -> (X + C + signbit)
4875             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4876             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4877
4878           }
4879         } else if (Op0I->getOpcode() == Instruction::Or) {
4880           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4881           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4882             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4883             // Anything in both C1 and C2 is known to be zero, remove it from
4884             // NewRHS.
4885             Constant *CommonBits = And(Op0CI, RHS);
4886             NewRHS = ConstantExpr::getAnd(NewRHS, 
4887                                           ConstantExpr::getNot(CommonBits));
4888             AddToWorkList(Op0I);
4889             I.setOperand(0, Op0I->getOperand(0));
4890             I.setOperand(1, NewRHS);
4891             return &I;
4892           }
4893         }
4894       }
4895     }
4896
4897     // Try to fold constant and into select arguments.
4898     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4899       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4900         return R;
4901     if (isa<PHINode>(Op0))
4902       if (Instruction *NV = FoldOpIntoPhi(I))
4903         return NV;
4904   }
4905
4906   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4907     if (X == Op1)
4908       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4909
4910   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4911     if (X == Op0)
4912       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4913
4914   
4915   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4916   if (Op1I) {
4917     Value *A, *B;
4918     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4919       if (A == Op0) {              // B^(B|A) == (A|B)^B
4920         Op1I->swapOperands();
4921         I.swapOperands();
4922         std::swap(Op0, Op1);
4923       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4924         I.swapOperands();     // Simplified below.
4925         std::swap(Op0, Op1);
4926       }
4927     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4928       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
4929     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4930       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
4931     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4932       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4933         Op1I->swapOperands();
4934         std::swap(A, B);
4935       }
4936       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4937         I.swapOperands();     // Simplified below.
4938         std::swap(Op0, Op1);
4939       }
4940     }
4941   }
4942   
4943   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4944   if (Op0I) {
4945     Value *A, *B;
4946     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4947       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4948         std::swap(A, B);
4949       if (B == Op1) {                                // (A|B)^B == A & ~B
4950         Instruction *NotB =
4951           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4952         return BinaryOperator::CreateAnd(A, NotB);
4953       }
4954     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
4955       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
4956     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
4957       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
4958     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4959       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4960         std::swap(A, B);
4961       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4962           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4963         Instruction *N =
4964           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4965         return BinaryOperator::CreateAnd(N, Op1);
4966       }
4967     }
4968   }
4969   
4970   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4971   if (Op0I && Op1I && Op0I->isShift() && 
4972       Op0I->getOpcode() == Op1I->getOpcode() && 
4973       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4974       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4975     Instruction *NewOp =
4976       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4977                                                     Op1I->getOperand(0),
4978                                                     Op0I->getName()), I);
4979     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4980                                   Op1I->getOperand(1));
4981   }
4982     
4983   if (Op0I && Op1I) {
4984     Value *A, *B, *C, *D;
4985     // (A & B)^(A | B) -> A ^ B
4986     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4987         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4988       if ((A == C && B == D) || (A == D && B == C)) 
4989         return BinaryOperator::CreateXor(A, B);
4990     }
4991     // (A | B)^(A & B) -> A ^ B
4992     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4993         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4994       if ((A == C && B == D) || (A == D && B == C)) 
4995         return BinaryOperator::CreateXor(A, B);
4996     }
4997     
4998     // (A & B)^(C & D)
4999     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5000         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5001         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5002       // (X & Y)^(X & Y) -> (Y^Z) & X
5003       Value *X = 0, *Y = 0, *Z = 0;
5004       if (A == C)
5005         X = A, Y = B, Z = D;
5006       else if (A == D)
5007         X = A, Y = B, Z = C;
5008       else if (B == C)
5009         X = B, Y = A, Z = D;
5010       else if (B == D)
5011         X = B, Y = A, Z = C;
5012       
5013       if (X) {
5014         Instruction *NewOp =
5015         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5016         return BinaryOperator::CreateAnd(NewOp, X);
5017       }
5018     }
5019   }
5020     
5021   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5022   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5023     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5024       return R;
5025
5026   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5027   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5028     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5029       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5030         const Type *SrcTy = Op0C->getOperand(0)->getType();
5031         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5032             // Only do this if the casts both really cause code to be generated.
5033             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5034                               I.getType(), TD) &&
5035             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5036                               I.getType(), TD)) {
5037           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5038                                                          Op1C->getOperand(0),
5039                                                          I.getName());
5040           InsertNewInstBefore(NewOp, I);
5041           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5042         }
5043       }
5044   }
5045
5046   return Changed ? &I : 0;
5047 }
5048
5049 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5050 /// overflowed for this type.
5051 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5052                             ConstantInt *In2, bool IsSigned = false) {
5053   Result = cast<ConstantInt>(Add(In1, In2));
5054
5055   if (IsSigned)
5056     if (In2->getValue().isNegative())
5057       return Result->getValue().sgt(In1->getValue());
5058     else
5059       return Result->getValue().slt(In1->getValue());
5060   else
5061     return Result->getValue().ult(In1->getValue());
5062 }
5063
5064 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5065 /// overflowed for this type.
5066 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5067                             ConstantInt *In2, bool IsSigned = false) {
5068   Result = cast<ConstantInt>(Subtract(In1, In2));
5069
5070   if (IsSigned)
5071     if (In2->getValue().isNegative())
5072       return Result->getValue().slt(In1->getValue());
5073     else
5074       return Result->getValue().sgt(In1->getValue());
5075   else
5076     return Result->getValue().ugt(In1->getValue());
5077 }
5078
5079 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5080 /// code necessary to compute the offset from the base pointer (without adding
5081 /// in the base pointer).  Return the result as a signed integer of intptr size.
5082 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5083   TargetData &TD = IC.getTargetData();
5084   gep_type_iterator GTI = gep_type_begin(GEP);
5085   const Type *IntPtrTy = TD.getIntPtrType();
5086   Value *Result = Constant::getNullValue(IntPtrTy);
5087
5088   // Build a mask for high order bits.
5089   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5090   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5091
5092   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5093        ++i, ++GTI) {
5094     Value *Op = *i;
5095     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5096     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5097       if (OpC->isZero()) continue;
5098       
5099       // Handle a struct index, which adds its field offset to the pointer.
5100       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5101         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5102         
5103         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5104           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5105         else
5106           Result = IC.InsertNewInstBefore(
5107                    BinaryOperator::CreateAdd(Result,
5108                                              ConstantInt::get(IntPtrTy, Size),
5109                                              GEP->getName()+".offs"), I);
5110         continue;
5111       }
5112       
5113       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5114       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5115       Scale = ConstantExpr::getMul(OC, Scale);
5116       if (Constant *RC = dyn_cast<Constant>(Result))
5117         Result = ConstantExpr::getAdd(RC, Scale);
5118       else {
5119         // Emit an add instruction.
5120         Result = IC.InsertNewInstBefore(
5121            BinaryOperator::CreateAdd(Result, Scale,
5122                                      GEP->getName()+".offs"), I);
5123       }
5124       continue;
5125     }
5126     // Convert to correct type.
5127     if (Op->getType() != IntPtrTy) {
5128       if (Constant *OpC = dyn_cast<Constant>(Op))
5129         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5130       else
5131         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5132                                                  Op->getName()+".c"), I);
5133     }
5134     if (Size != 1) {
5135       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5136       if (Constant *OpC = dyn_cast<Constant>(Op))
5137         Op = ConstantExpr::getMul(OpC, Scale);
5138       else    // We'll let instcombine(mul) convert this to a shl if possible.
5139         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5140                                                   GEP->getName()+".idx"), I);
5141     }
5142
5143     // Emit an add instruction.
5144     if (isa<Constant>(Op) && isa<Constant>(Result))
5145       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5146                                     cast<Constant>(Result));
5147     else
5148       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5149                                                   GEP->getName()+".offs"), I);
5150   }
5151   return Result;
5152 }
5153
5154
5155 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5156 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5157 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5158 /// complex, and scales are involved.  The above expression would also be legal
5159 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5160 /// later form is less amenable to optimization though, and we are allowed to
5161 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5162 ///
5163 /// If we can't emit an optimized form for this expression, this returns null.
5164 /// 
5165 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5166                                           InstCombiner &IC) {
5167   TargetData &TD = IC.getTargetData();
5168   gep_type_iterator GTI = gep_type_begin(GEP);
5169
5170   // Check to see if this gep only has a single variable index.  If so, and if
5171   // any constant indices are a multiple of its scale, then we can compute this
5172   // in terms of the scale of the variable index.  For example, if the GEP
5173   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5174   // because the expression will cross zero at the same point.
5175   unsigned i, e = GEP->getNumOperands();
5176   int64_t Offset = 0;
5177   for (i = 1; i != e; ++i, ++GTI) {
5178     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5179       // Compute the aggregate offset of constant indices.
5180       if (CI->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         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5185       } else {
5186         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5187         Offset += Size*CI->getSExtValue();
5188       }
5189     } else {
5190       // Found our variable index.
5191       break;
5192     }
5193   }
5194   
5195   // If there are no variable indices, we must have a constant offset, just
5196   // evaluate it the general way.
5197   if (i == e) return 0;
5198   
5199   Value *VariableIdx = GEP->getOperand(i);
5200   // Determine the scale factor of the variable element.  For example, this is
5201   // 4 if the variable index is into an array of i32.
5202   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5203   
5204   // Verify that there are no other variable indices.  If so, emit the hard way.
5205   for (++i, ++GTI; i != e; ++i, ++GTI) {
5206     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5207     if (!CI) return 0;
5208    
5209     // Compute the aggregate offset of constant indices.
5210     if (CI->isZero()) continue;
5211     
5212     // Handle a struct index, which adds its field offset to the pointer.
5213     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5214       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5215     } else {
5216       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5217       Offset += Size*CI->getSExtValue();
5218     }
5219   }
5220   
5221   // Okay, we know we have a single variable index, which must be a
5222   // pointer/array/vector index.  If there is no offset, life is simple, return
5223   // the index.
5224   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5225   if (Offset == 0) {
5226     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5227     // we don't need to bother extending: the extension won't affect where the
5228     // computation crosses zero.
5229     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5230       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5231                                   VariableIdx->getNameStart(), &I);
5232     return VariableIdx;
5233   }
5234   
5235   // Otherwise, there is an index.  The computation we will do will be modulo
5236   // the pointer size, so get it.
5237   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5238   
5239   Offset &= PtrSizeMask;
5240   VariableScale &= PtrSizeMask;
5241
5242   // To do this transformation, any constant index must be a multiple of the
5243   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5244   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5245   // multiple of the variable scale.
5246   int64_t NewOffs = Offset / (int64_t)VariableScale;
5247   if (Offset != NewOffs*(int64_t)VariableScale)
5248     return 0;
5249
5250   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5251   const Type *IntPtrTy = TD.getIntPtrType();
5252   if (VariableIdx->getType() != IntPtrTy)
5253     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5254                                               true /*SExt*/, 
5255                                               VariableIdx->getNameStart(), &I);
5256   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5257   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5258 }
5259
5260
5261 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5262 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5263 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5264                                        ICmpInst::Predicate Cond,
5265                                        Instruction &I) {
5266   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5267
5268   // Look through bitcasts.
5269   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5270     RHS = BCI->getOperand(0);
5271
5272   Value *PtrBase = GEPLHS->getOperand(0);
5273   if (PtrBase == RHS) {
5274     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5275     // This transformation (ignoring the base and scales) is valid because we
5276     // know pointers can't overflow.  See if we can output an optimized form.
5277     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5278     
5279     // If not, synthesize the offset the hard way.
5280     if (Offset == 0)
5281       Offset = EmitGEPOffset(GEPLHS, I, *this);
5282     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5283                         Constant::getNullValue(Offset->getType()));
5284   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5285     // If the base pointers are different, but the indices are the same, just
5286     // compare the base pointer.
5287     if (PtrBase != GEPRHS->getOperand(0)) {
5288       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5289       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5290                         GEPRHS->getOperand(0)->getType();
5291       if (IndicesTheSame)
5292         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5293           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5294             IndicesTheSame = false;
5295             break;
5296           }
5297
5298       // If all indices are the same, just compare the base pointers.
5299       if (IndicesTheSame)
5300         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5301                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5302
5303       // Otherwise, the base pointers are different and the indices are
5304       // different, bail out.
5305       return 0;
5306     }
5307
5308     // If one of the GEPs has all zero indices, recurse.
5309     bool AllZeros = true;
5310     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5311       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5312           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5313         AllZeros = false;
5314         break;
5315       }
5316     if (AllZeros)
5317       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5318                           ICmpInst::getSwappedPredicate(Cond), I);
5319
5320     // If the other GEP has all zero indices, recurse.
5321     AllZeros = true;
5322     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5323       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5324           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5325         AllZeros = false;
5326         break;
5327       }
5328     if (AllZeros)
5329       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5330
5331     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5332       // If the GEPs only differ by one index, compare it.
5333       unsigned NumDifferences = 0;  // Keep track of # differences.
5334       unsigned DiffOperand = 0;     // The operand that differs.
5335       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5336         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5337           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5338                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5339             // Irreconcilable differences.
5340             NumDifferences = 2;
5341             break;
5342           } else {
5343             if (NumDifferences++) break;
5344             DiffOperand = i;
5345           }
5346         }
5347
5348       if (NumDifferences == 0)   // SAME GEP?
5349         return ReplaceInstUsesWith(I, // No comparison is needed here.
5350                                    ConstantInt::get(Type::Int1Ty,
5351                                              ICmpInst::isTrueWhenEqual(Cond)));
5352
5353       else if (NumDifferences == 1) {
5354         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5355         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5356         // Make sure we do a signed comparison here.
5357         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5358       }
5359     }
5360
5361     // Only lower this if the icmp is the only user of the GEP or if we expect
5362     // the result to fold to a constant!
5363     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5364         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5365       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5366       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5367       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5368       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5369     }
5370   }
5371   return 0;
5372 }
5373
5374 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5375 ///
5376 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5377                                                 Instruction *LHSI,
5378                                                 Constant *RHSC) {
5379   if (!isa<ConstantFP>(RHSC)) return 0;
5380   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5381   
5382   // Get the width of the mantissa.  We don't want to hack on conversions that
5383   // might lose information from the integer, e.g. "i64 -> float"
5384   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5385   if (MantissaWidth == -1) return 0;  // Unknown.
5386   
5387   // Check to see that the input is converted from an integer type that is small
5388   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5389   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5390   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5391   
5392   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5393   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5394   if (LHSUnsigned)
5395     ++InputSize;
5396   
5397   // If the conversion would lose info, don't hack on this.
5398   if ((int)InputSize > MantissaWidth)
5399     return 0;
5400   
5401   // Otherwise, we can potentially simplify the comparison.  We know that it
5402   // will always come through as an integer value and we know the constant is
5403   // not a NAN (it would have been previously simplified).
5404   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5405   
5406   ICmpInst::Predicate Pred;
5407   switch (I.getPredicate()) {
5408   default: assert(0 && "Unexpected predicate!");
5409   case FCmpInst::FCMP_UEQ:
5410   case FCmpInst::FCMP_OEQ:
5411     Pred = ICmpInst::ICMP_EQ;
5412     break;
5413   case FCmpInst::FCMP_UGT:
5414   case FCmpInst::FCMP_OGT:
5415     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5416     break;
5417   case FCmpInst::FCMP_UGE:
5418   case FCmpInst::FCMP_OGE:
5419     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5420     break;
5421   case FCmpInst::FCMP_ULT:
5422   case FCmpInst::FCMP_OLT:
5423     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5424     break;
5425   case FCmpInst::FCMP_ULE:
5426   case FCmpInst::FCMP_OLE:
5427     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5428     break;
5429   case FCmpInst::FCMP_UNE:
5430   case FCmpInst::FCMP_ONE:
5431     Pred = ICmpInst::ICMP_NE;
5432     break;
5433   case FCmpInst::FCMP_ORD:
5434     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5435   case FCmpInst::FCMP_UNO:
5436     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5437   }
5438   
5439   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5440   
5441   // Now we know that the APFloat is a normal number, zero or inf.
5442   
5443   // See if the FP constant is too large for the integer.  For example,
5444   // comparing an i8 to 300.0.
5445   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5446   
5447   if (!LHSUnsigned) {
5448     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5449     // and large values.
5450     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5451     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5452                           APFloat::rmNearestTiesToEven);
5453     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5454       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5455           Pred == ICmpInst::ICMP_SLE)
5456         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5457       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5458     }
5459   } else {
5460     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5461     // +INF and large values.
5462     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5463     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5464                           APFloat::rmNearestTiesToEven);
5465     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5466       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5467           Pred == ICmpInst::ICMP_ULE)
5468         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5469       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5470     }
5471   }
5472   
5473   if (!LHSUnsigned) {
5474     // See if the RHS value is < SignedMin.
5475     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5476     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5477                           APFloat::rmNearestTiesToEven);
5478     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5479       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5480           Pred == ICmpInst::ICMP_SGE)
5481         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5482       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5483     }
5484   }
5485
5486   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5487   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5488   // casting the FP value to the integer value and back, checking for equality.
5489   // Don't do this for zero, because -0.0 is not fractional.
5490   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5491   if (!RHS.isZero() &&
5492       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5493     // If we had a comparison against a fractional value, we have to adjust the
5494     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5495     // at this point.
5496     switch (Pred) {
5497     default: assert(0 && "Unexpected integer comparison!");
5498     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5499       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5500     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5501       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5502     case ICmpInst::ICMP_ULE:
5503       // (float)int <= 4.4   --> int <= 4
5504       // (float)int <= -4.4  --> false
5505       if (RHS.isNegative())
5506         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5507       break;
5508     case ICmpInst::ICMP_SLE:
5509       // (float)int <= 4.4   --> int <= 4
5510       // (float)int <= -4.4  --> int < -4
5511       if (RHS.isNegative())
5512         Pred = ICmpInst::ICMP_SLT;
5513       break;
5514     case ICmpInst::ICMP_ULT:
5515       // (float)int < -4.4   --> false
5516       // (float)int < 4.4    --> int <= 4
5517       if (RHS.isNegative())
5518         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5519       Pred = ICmpInst::ICMP_ULE;
5520       break;
5521     case ICmpInst::ICMP_SLT:
5522       // (float)int < -4.4   --> int < -4
5523       // (float)int < 4.4    --> int <= 4
5524       if (!RHS.isNegative())
5525         Pred = ICmpInst::ICMP_SLE;
5526       break;
5527     case ICmpInst::ICMP_UGT:
5528       // (float)int > 4.4    --> int > 4
5529       // (float)int > -4.4   --> true
5530       if (RHS.isNegative())
5531         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5532       break;
5533     case ICmpInst::ICMP_SGT:
5534       // (float)int > 4.4    --> int > 4
5535       // (float)int > -4.4   --> int >= -4
5536       if (RHS.isNegative())
5537         Pred = ICmpInst::ICMP_SGE;
5538       break;
5539     case ICmpInst::ICMP_UGE:
5540       // (float)int >= -4.4   --> true
5541       // (float)int >= 4.4    --> int > 4
5542       if (!RHS.isNegative())
5543         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5544       Pred = ICmpInst::ICMP_UGT;
5545       break;
5546     case ICmpInst::ICMP_SGE:
5547       // (float)int >= -4.4   --> int >= -4
5548       // (float)int >= 4.4    --> int > 4
5549       if (!RHS.isNegative())
5550         Pred = ICmpInst::ICMP_SGT;
5551       break;
5552     }
5553   }
5554
5555   // Lower this FP comparison into an appropriate integer version of the
5556   // comparison.
5557   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5558 }
5559
5560 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5561   bool Changed = SimplifyCompare(I);
5562   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5563
5564   // Fold trivial predicates.
5565   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5566     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5567   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5568     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5569   
5570   // Simplify 'fcmp pred X, X'
5571   if (Op0 == Op1) {
5572     switch (I.getPredicate()) {
5573     default: assert(0 && "Unknown predicate!");
5574     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5575     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5576     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5577       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5578     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5579     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5580     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5581       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5582       
5583     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5584     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5585     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5586     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5587       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5588       I.setPredicate(FCmpInst::FCMP_UNO);
5589       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5590       return &I;
5591       
5592     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5593     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5594     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5595     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5596       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5597       I.setPredicate(FCmpInst::FCMP_ORD);
5598       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5599       return &I;
5600     }
5601   }
5602     
5603   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5604     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5605
5606   // Handle fcmp with constant RHS
5607   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5608     // If the constant is a nan, see if we can fold the comparison based on it.
5609     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5610       if (CFP->getValueAPF().isNaN()) {
5611         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5612           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5613         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5614                "Comparison must be either ordered or unordered!");
5615         // True if unordered.
5616         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5617       }
5618     }
5619     
5620     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5621       switch (LHSI->getOpcode()) {
5622       case Instruction::PHI:
5623         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5624         // block.  If in the same block, we're encouraging jump threading.  If
5625         // not, we are just pessimizing the code by making an i1 phi.
5626         if (LHSI->getParent() == I.getParent())
5627           if (Instruction *NV = FoldOpIntoPhi(I))
5628             return NV;
5629         break;
5630       case Instruction::SIToFP:
5631       case Instruction::UIToFP:
5632         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5633           return NV;
5634         break;
5635       case Instruction::Select:
5636         // If either operand of the select is a constant, we can fold the
5637         // comparison into the select arms, which will cause one to be
5638         // constant folded and the select turned into a bitwise or.
5639         Value *Op1 = 0, *Op2 = 0;
5640         if (LHSI->hasOneUse()) {
5641           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5642             // Fold the known value into the constant operand.
5643             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5644             // Insert a new FCmp of the other select operand.
5645             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5646                                                       LHSI->getOperand(2), RHSC,
5647                                                       I.getName()), I);
5648           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5649             // Fold the known value into the constant operand.
5650             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5651             // Insert a new FCmp of the other select operand.
5652             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5653                                                       LHSI->getOperand(1), RHSC,
5654                                                       I.getName()), I);
5655           }
5656         }
5657
5658         if (Op1)
5659           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5660         break;
5661       }
5662   }
5663
5664   return Changed ? &I : 0;
5665 }
5666
5667 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5668   bool Changed = SimplifyCompare(I);
5669   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5670   const Type *Ty = Op0->getType();
5671
5672   // icmp X, X
5673   if (Op0 == Op1)
5674     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5675                                                    I.isTrueWhenEqual()));
5676
5677   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5678     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5679   
5680   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5681   // addresses never equal each other!  We already know that Op0 != Op1.
5682   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5683        isa<ConstantPointerNull>(Op0)) &&
5684       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5685        isa<ConstantPointerNull>(Op1)))
5686     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5687                                                    !I.isTrueWhenEqual()));
5688
5689   // icmp's with boolean values can always be turned into bitwise operations
5690   if (Ty == Type::Int1Ty) {
5691     switch (I.getPredicate()) {
5692     default: assert(0 && "Invalid icmp instruction!");
5693     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5694       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5695       InsertNewInstBefore(Xor, I);
5696       return BinaryOperator::CreateNot(Xor);
5697     }
5698     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5699       return BinaryOperator::CreateXor(Op0, Op1);
5700
5701     case ICmpInst::ICMP_UGT:
5702       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5703       // FALL THROUGH
5704     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5705       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5706       InsertNewInstBefore(Not, I);
5707       return BinaryOperator::CreateAnd(Not, Op1);
5708     }
5709     case ICmpInst::ICMP_SGT:
5710       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5711       // FALL THROUGH
5712     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5713       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5714       InsertNewInstBefore(Not, I);
5715       return BinaryOperator::CreateAnd(Not, Op0);
5716     }
5717     case ICmpInst::ICMP_UGE:
5718       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5719       // FALL THROUGH
5720     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5721       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5722       InsertNewInstBefore(Not, I);
5723       return BinaryOperator::CreateOr(Not, Op1);
5724     }
5725     case ICmpInst::ICMP_SGE:
5726       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5727       // FALL THROUGH
5728     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5729       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5730       InsertNewInstBefore(Not, I);
5731       return BinaryOperator::CreateOr(Not, Op0);
5732     }
5733     }
5734   }
5735
5736   // See if we are doing a comparison with a constant.
5737   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5738     Value *A, *B;
5739     
5740     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5741     if (I.isEquality() && CI->isNullValue() &&
5742         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5743       // (icmp cond A B) if cond is equality
5744       return new ICmpInst(I.getPredicate(), A, B);
5745     }
5746     
5747     // If we have an icmp le or icmp ge instruction, turn it into the
5748     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5749     // them being folded in the code below.
5750     switch (I.getPredicate()) {
5751     default: break;
5752     case ICmpInst::ICMP_ULE:
5753       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5754         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5755       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5756     case ICmpInst::ICMP_SLE:
5757       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5758         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5759       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5760     case ICmpInst::ICMP_UGE:
5761       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5762         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5763       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5764     case ICmpInst::ICMP_SGE:
5765       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5766         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5767       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5768     }
5769     
5770     // See if we can fold the comparison based on range information we can get
5771     // by checking whether bits are known to be zero or one in the input.
5772     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5773     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5774     
5775     // If this comparison is a normal comparison, it demands all
5776     // bits, if it is a sign bit comparison, it only demands the sign bit.
5777     bool UnusedBit;
5778     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5779     
5780     if (SimplifyDemandedBits(Op0, 
5781                              isSignBit ? APInt::getSignBit(BitWidth)
5782                                        : APInt::getAllOnesValue(BitWidth),
5783                              KnownZero, KnownOne, 0))
5784       return &I;
5785         
5786     // Given the known and unknown bits, compute a range that the LHS could be
5787     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5788     // EQ and NE we use unsigned values.
5789     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5790     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5791       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5792     else
5793       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5794     
5795     // If Min and Max are known to be the same, then SimplifyDemandedBits
5796     // figured out that the LHS is a constant.  Just constant fold this now so
5797     // that code below can assume that Min != Max.
5798     if (Min == Max)
5799       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5800                                                           ConstantInt::get(Min),
5801                                                           CI));
5802     
5803     // Based on the range information we know about the LHS, see if we can
5804     // simplify this comparison.  For example, (x&4) < 8  is always true.
5805     const APInt &RHSVal = CI->getValue();
5806     switch (I.getPredicate()) {  // LE/GE have been folded already.
5807     default: assert(0 && "Unknown icmp opcode!");
5808     case ICmpInst::ICMP_EQ:
5809       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5810         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5811       break;
5812     case ICmpInst::ICMP_NE:
5813       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5814         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5815       break;
5816     case ICmpInst::ICMP_ULT:
5817       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5818         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5819       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5820         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5821       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5822         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5823       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5824         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5825         
5826       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5827       if (CI->isMinValue(true))
5828         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5829                             ConstantInt::getAllOnesValue(Op0->getType()));
5830       break;
5831     case ICmpInst::ICMP_UGT:
5832       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5833         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5834       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5835         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5836         
5837       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5838         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5839       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5840         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5841       
5842       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5843       if (CI->isMaxValue(true))
5844         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5845                             ConstantInt::getNullValue(Op0->getType()));
5846       break;
5847     case ICmpInst::ICMP_SLT:
5848       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5849         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5850       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5851         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5852       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5853         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5854       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5855         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5856       break;
5857     case ICmpInst::ICMP_SGT: 
5858       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5859         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5860       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5861         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5862         
5863       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5864         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5865       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5866         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5867       break;
5868     }
5869   }
5870
5871   // Test if the ICmpInst instruction is used exclusively by a select as
5872   // part of a minimum or maximum operation. If so, refrain from doing
5873   // any other folding. This helps out other analyses which understand
5874   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5875   // and CodeGen. And in this case, at least one of the comparison
5876   // operands has at least one user besides the compare (the select),
5877   // which would often largely negate the benefit of folding anyway.
5878   if (I.hasOneUse())
5879     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5880       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5881           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5882         return 0;
5883
5884   // See if we are doing a comparison between a constant and an instruction that
5885   // can be folded into the comparison.
5886   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5887     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5888     // instruction, see if that instruction also has constants so that the 
5889     // instruction can be folded into the icmp 
5890     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5891       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5892         return Res;
5893   }
5894
5895   // Handle icmp with constant (but not simple integer constant) RHS
5896   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5897     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5898       switch (LHSI->getOpcode()) {
5899       case Instruction::GetElementPtr:
5900         if (RHSC->isNullValue()) {
5901           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5902           bool isAllZeros = true;
5903           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5904             if (!isa<Constant>(LHSI->getOperand(i)) ||
5905                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5906               isAllZeros = false;
5907               break;
5908             }
5909           if (isAllZeros)
5910             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5911                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5912         }
5913         break;
5914
5915       case Instruction::PHI:
5916         // Only fold icmp into the PHI if the phi and fcmp are in the same
5917         // block.  If in the same block, we're encouraging jump threading.  If
5918         // not, we are just pessimizing the code by making an i1 phi.
5919         if (LHSI->getParent() == I.getParent())
5920           if (Instruction *NV = FoldOpIntoPhi(I))
5921             return NV;
5922         break;
5923       case Instruction::Select: {
5924         // If either operand of the select is a constant, we can fold the
5925         // comparison into the select arms, which will cause one to be
5926         // constant folded and the select turned into a bitwise or.
5927         Value *Op1 = 0, *Op2 = 0;
5928         if (LHSI->hasOneUse()) {
5929           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5930             // Fold the known value into the constant operand.
5931             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5932             // Insert a new ICmp of the other select operand.
5933             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5934                                                    LHSI->getOperand(2), RHSC,
5935                                                    I.getName()), I);
5936           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5937             // Fold the known value into the constant operand.
5938             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5939             // Insert a new ICmp of the other select operand.
5940             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5941                                                    LHSI->getOperand(1), RHSC,
5942                                                    I.getName()), I);
5943           }
5944         }
5945
5946         if (Op1)
5947           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5948         break;
5949       }
5950       case Instruction::Malloc:
5951         // If we have (malloc != null), and if the malloc has a single use, we
5952         // can assume it is successful and remove the malloc.
5953         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5954           AddToWorkList(LHSI);
5955           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5956                                                          !I.isTrueWhenEqual()));
5957         }
5958         break;
5959       }
5960   }
5961
5962   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5963   if (User *GEP = dyn_castGetElementPtr(Op0))
5964     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5965       return NI;
5966   if (User *GEP = dyn_castGetElementPtr(Op1))
5967     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5968                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5969       return NI;
5970
5971   // Test to see if the operands of the icmp are casted versions of other
5972   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5973   // now.
5974   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5975     if (isa<PointerType>(Op0->getType()) && 
5976         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5977       // We keep moving the cast from the left operand over to the right
5978       // operand, where it can often be eliminated completely.
5979       Op0 = CI->getOperand(0);
5980
5981       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5982       // so eliminate it as well.
5983       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5984         Op1 = CI2->getOperand(0);
5985
5986       // If Op1 is a constant, we can fold the cast into the constant.
5987       if (Op0->getType() != Op1->getType()) {
5988         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5989           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5990         } else {
5991           // Otherwise, cast the RHS right before the icmp
5992           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5993         }
5994       }
5995       return new ICmpInst(I.getPredicate(), Op0, Op1);
5996     }
5997   }
5998   
5999   if (isa<CastInst>(Op0)) {
6000     // Handle the special case of: icmp (cast bool to X), <cst>
6001     // This comes up when you have code like
6002     //   int X = A < B;
6003     //   if (X) ...
6004     // For generality, we handle any zero-extension of any operand comparison
6005     // with a constant or another cast from the same type.
6006     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6007       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6008         return R;
6009   }
6010   
6011   // See if it's the same type of instruction on the left and right.
6012   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6013     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6014       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6015           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6016           I.isEquality()) {
6017         switch (Op0I->getOpcode()) {
6018         default: break;
6019         case Instruction::Add:
6020         case Instruction::Sub:
6021         case Instruction::Xor:
6022           // a+x icmp eq/ne b+x --> a icmp b
6023           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6024                               Op1I->getOperand(0));
6025           break;
6026         case Instruction::Mul:
6027           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6028             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6029             // Mask = -1 >> count-trailing-zeros(Cst).
6030             if (!CI->isZero() && !CI->isOne()) {
6031               const APInt &AP = CI->getValue();
6032               ConstantInt *Mask = ConstantInt::get(
6033                                       APInt::getLowBitsSet(AP.getBitWidth(),
6034                                                            AP.getBitWidth() -
6035                                                       AP.countTrailingZeros()));
6036               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6037                                                             Mask);
6038               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6039                                                             Mask);
6040               InsertNewInstBefore(And1, I);
6041               InsertNewInstBefore(And2, I);
6042               return new ICmpInst(I.getPredicate(), And1, And2);
6043             }
6044           }
6045           break;
6046         }
6047       }
6048     }
6049   }
6050   
6051   // ~x < ~y --> y < x
6052   { Value *A, *B;
6053     if (match(Op0, m_Not(m_Value(A))) &&
6054         match(Op1, m_Not(m_Value(B))))
6055       return new ICmpInst(I.getPredicate(), B, A);
6056   }
6057   
6058   if (I.isEquality()) {
6059     Value *A, *B, *C, *D;
6060     
6061     // -x == -y --> x == y
6062     if (match(Op0, m_Neg(m_Value(A))) &&
6063         match(Op1, m_Neg(m_Value(B))))
6064       return new ICmpInst(I.getPredicate(), A, B);
6065     
6066     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6067       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6068         Value *OtherVal = A == Op1 ? B : A;
6069         return new ICmpInst(I.getPredicate(), OtherVal,
6070                             Constant::getNullValue(A->getType()));
6071       }
6072
6073       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6074         // A^c1 == C^c2 --> A == C^(c1^c2)
6075         ConstantInt *C1, *C2;
6076         if (match(B, m_ConstantInt(C1)) &&
6077             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6078           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6079           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6080           return new ICmpInst(I.getPredicate(), A,
6081                               InsertNewInstBefore(Xor, I));
6082         }
6083         
6084         // A^B == A^D -> B == D
6085         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6086         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6087         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6088         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6089       }
6090     }
6091     
6092     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6093         (A == Op0 || B == Op0)) {
6094       // A == (A^B)  ->  B == 0
6095       Value *OtherVal = A == Op0 ? B : A;
6096       return new ICmpInst(I.getPredicate(), OtherVal,
6097                           Constant::getNullValue(A->getType()));
6098     }
6099
6100     // (A-B) == A  ->  B == 0
6101     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6102       return new ICmpInst(I.getPredicate(), B, 
6103                           Constant::getNullValue(B->getType()));
6104
6105     // A == (A-B)  ->  B == 0
6106     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6107       return new ICmpInst(I.getPredicate(), B,
6108                           Constant::getNullValue(B->getType()));
6109     
6110     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6111     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6112         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6113         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6114       Value *X = 0, *Y = 0, *Z = 0;
6115       
6116       if (A == C) {
6117         X = B; Y = D; Z = A;
6118       } else if (A == D) {
6119         X = B; Y = C; Z = A;
6120       } else if (B == C) {
6121         X = A; Y = D; Z = B;
6122       } else if (B == D) {
6123         X = A; Y = C; Z = B;
6124       }
6125       
6126       if (X) {   // Build (X^Y) & Z
6127         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6128         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6129         I.setOperand(0, Op1);
6130         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6131         return &I;
6132       }
6133     }
6134   }
6135   return Changed ? &I : 0;
6136 }
6137
6138
6139 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6140 /// and CmpRHS are both known to be integer constants.
6141 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6142                                           ConstantInt *DivRHS) {
6143   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6144   const APInt &CmpRHSV = CmpRHS->getValue();
6145   
6146   // FIXME: If the operand types don't match the type of the divide 
6147   // then don't attempt this transform. The code below doesn't have the
6148   // logic to deal with a signed divide and an unsigned compare (and
6149   // vice versa). This is because (x /s C1) <s C2  produces different 
6150   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6151   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6152   // work. :(  The if statement below tests that condition and bails 
6153   // if it finds it. 
6154   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6155   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6156     return 0;
6157   if (DivRHS->isZero())
6158     return 0; // The ProdOV computation fails on divide by zero.
6159   if (DivIsSigned && DivRHS->isAllOnesValue())
6160     return 0; // The overflow computation also screws up here
6161   if (DivRHS->isOne())
6162     return 0; // Not worth bothering, and eliminates some funny cases
6163               // with INT_MIN.
6164
6165   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6166   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6167   // C2 (CI). By solving for X we can turn this into a range check 
6168   // instead of computing a divide. 
6169   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6170
6171   // Determine if the product overflows by seeing if the product is
6172   // not equal to the divide. Make sure we do the same kind of divide
6173   // as in the LHS instruction that we're folding. 
6174   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6175                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6176
6177   // Get the ICmp opcode
6178   ICmpInst::Predicate Pred = ICI.getPredicate();
6179
6180   // Figure out the interval that is being checked.  For example, a comparison
6181   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6182   // Compute this interval based on the constants involved and the signedness of
6183   // the compare/divide.  This computes a half-open interval, keeping track of
6184   // whether either value in the interval overflows.  After analysis each
6185   // overflow variable is set to 0 if it's corresponding bound variable is valid
6186   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6187   int LoOverflow = 0, HiOverflow = 0;
6188   ConstantInt *LoBound = 0, *HiBound = 0;
6189   
6190   if (!DivIsSigned) {  // udiv
6191     // e.g. X/5 op 3  --> [15, 20)
6192     LoBound = Prod;
6193     HiOverflow = LoOverflow = ProdOV;
6194     if (!HiOverflow)
6195       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6196   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6197     if (CmpRHSV == 0) {       // (X / pos) op 0
6198       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6199       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6200       HiBound = DivRHS;
6201     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6202       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6203       HiOverflow = LoOverflow = ProdOV;
6204       if (!HiOverflow)
6205         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6206     } else {                       // (X / pos) op neg
6207       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6208       HiBound = AddOne(Prod);
6209       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6210       if (!LoOverflow) {
6211         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6212         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6213                                      true) ? -1 : 0;
6214        }
6215     }
6216   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6217     if (CmpRHSV == 0) {       // (X / neg) op 0
6218       // e.g. X/-5 op 0  --> [-4, 5)
6219       LoBound = AddOne(DivRHS);
6220       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6221       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6222         HiOverflow = 1;            // [INTMIN+1, overflow)
6223         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6224       }
6225     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6226       // e.g. X/-5 op 3  --> [-19, -14)
6227       HiBound = AddOne(Prod);
6228       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6229       if (!LoOverflow)
6230         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6231     } else {                       // (X / neg) op neg
6232       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6233       LoOverflow = HiOverflow = ProdOV;
6234       if (!HiOverflow)
6235         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6236     }
6237     
6238     // Dividing by a negative swaps the condition.  LT <-> GT
6239     Pred = ICmpInst::getSwappedPredicate(Pred);
6240   }
6241
6242   Value *X = DivI->getOperand(0);
6243   switch (Pred) {
6244   default: assert(0 && "Unhandled icmp opcode!");
6245   case ICmpInst::ICMP_EQ:
6246     if (LoOverflow && HiOverflow)
6247       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6248     else if (HiOverflow)
6249       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6250                           ICmpInst::ICMP_UGE, X, LoBound);
6251     else if (LoOverflow)
6252       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6253                           ICmpInst::ICMP_ULT, X, HiBound);
6254     else
6255       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6256   case ICmpInst::ICMP_NE:
6257     if (LoOverflow && HiOverflow)
6258       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6259     else if (HiOverflow)
6260       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6261                           ICmpInst::ICMP_ULT, X, LoBound);
6262     else if (LoOverflow)
6263       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6264                           ICmpInst::ICMP_UGE, X, HiBound);
6265     else
6266       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6267   case ICmpInst::ICMP_ULT:
6268   case ICmpInst::ICMP_SLT:
6269     if (LoOverflow == +1)   // Low bound is greater than input range.
6270       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6271     if (LoOverflow == -1)   // Low bound is less than input range.
6272       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6273     return new ICmpInst(Pred, X, LoBound);
6274   case ICmpInst::ICMP_UGT:
6275   case ICmpInst::ICMP_SGT:
6276     if (HiOverflow == +1)       // High bound greater than input range.
6277       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6278     else if (HiOverflow == -1)  // High bound less than input range.
6279       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6280     if (Pred == ICmpInst::ICMP_UGT)
6281       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6282     else
6283       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6284   }
6285 }
6286
6287
6288 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6289 ///
6290 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6291                                                           Instruction *LHSI,
6292                                                           ConstantInt *RHS) {
6293   const APInt &RHSV = RHS->getValue();
6294   
6295   switch (LHSI->getOpcode()) {
6296   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6297     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6298       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6299       // fold the xor.
6300       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6301           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6302         Value *CompareVal = LHSI->getOperand(0);
6303         
6304         // If the sign bit of the XorCST is not set, there is no change to
6305         // the operation, just stop using the Xor.
6306         if (!XorCST->getValue().isNegative()) {
6307           ICI.setOperand(0, CompareVal);
6308           AddToWorkList(LHSI);
6309           return &ICI;
6310         }
6311         
6312         // Was the old condition true if the operand is positive?
6313         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6314         
6315         // If so, the new one isn't.
6316         isTrueIfPositive ^= true;
6317         
6318         if (isTrueIfPositive)
6319           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6320         else
6321           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6322       }
6323     }
6324     break;
6325   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6326     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6327         LHSI->getOperand(0)->hasOneUse()) {
6328       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6329       
6330       // If the LHS is an AND of a truncating cast, we can widen the
6331       // and/compare to be the input width without changing the value
6332       // produced, eliminating a cast.
6333       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6334         // We can do this transformation if either the AND constant does not
6335         // have its sign bit set or if it is an equality comparison. 
6336         // Extending a relational comparison when we're checking the sign
6337         // bit would not work.
6338         if (Cast->hasOneUse() &&
6339             (ICI.isEquality() ||
6340              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6341           uint32_t BitWidth = 
6342             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6343           APInt NewCST = AndCST->getValue();
6344           NewCST.zext(BitWidth);
6345           APInt NewCI = RHSV;
6346           NewCI.zext(BitWidth);
6347           Instruction *NewAnd = 
6348             BinaryOperator::CreateAnd(Cast->getOperand(0),
6349                                       ConstantInt::get(NewCST),LHSI->getName());
6350           InsertNewInstBefore(NewAnd, ICI);
6351           return new ICmpInst(ICI.getPredicate(), NewAnd,
6352                               ConstantInt::get(NewCI));
6353         }
6354       }
6355       
6356       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6357       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6358       // happens a LOT in code produced by the C front-end, for bitfield
6359       // access.
6360       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6361       if (Shift && !Shift->isShift())
6362         Shift = 0;
6363       
6364       ConstantInt *ShAmt;
6365       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6366       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6367       const Type *AndTy = AndCST->getType();          // Type of the and.
6368       
6369       // We can fold this as long as we can't shift unknown bits
6370       // into the mask.  This can only happen with signed shift
6371       // rights, as they sign-extend.
6372       if (ShAmt) {
6373         bool CanFold = Shift->isLogicalShift();
6374         if (!CanFold) {
6375           // To test for the bad case of the signed shr, see if any
6376           // of the bits shifted in could be tested after the mask.
6377           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6378           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6379           
6380           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6381           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6382                AndCST->getValue()) == 0)
6383             CanFold = true;
6384         }
6385         
6386         if (CanFold) {
6387           Constant *NewCst;
6388           if (Shift->getOpcode() == Instruction::Shl)
6389             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6390           else
6391             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6392           
6393           // Check to see if we are shifting out any of the bits being
6394           // compared.
6395           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6396             // If we shifted bits out, the fold is not going to work out.
6397             // As a special case, check to see if this means that the
6398             // result is always true or false now.
6399             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6400               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6401             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6402               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6403           } else {
6404             ICI.setOperand(1, NewCst);
6405             Constant *NewAndCST;
6406             if (Shift->getOpcode() == Instruction::Shl)
6407               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6408             else
6409               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6410             LHSI->setOperand(1, NewAndCST);
6411             LHSI->setOperand(0, Shift->getOperand(0));
6412             AddToWorkList(Shift); // Shift is dead.
6413             AddUsesToWorkList(ICI);
6414             return &ICI;
6415           }
6416         }
6417       }
6418       
6419       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6420       // preferable because it allows the C<<Y expression to be hoisted out
6421       // of a loop if Y is invariant and X is not.
6422       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6423           ICI.isEquality() && !Shift->isArithmeticShift() &&
6424           isa<Instruction>(Shift->getOperand(0))) {
6425         // Compute C << Y.
6426         Value *NS;
6427         if (Shift->getOpcode() == Instruction::LShr) {
6428           NS = BinaryOperator::CreateShl(AndCST, 
6429                                          Shift->getOperand(1), "tmp");
6430         } else {
6431           // Insert a logical shift.
6432           NS = BinaryOperator::CreateLShr(AndCST,
6433                                           Shift->getOperand(1), "tmp");
6434         }
6435         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6436         
6437         // Compute X & (C << Y).
6438         Instruction *NewAnd = 
6439           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6440         InsertNewInstBefore(NewAnd, ICI);
6441         
6442         ICI.setOperand(0, NewAnd);
6443         return &ICI;
6444       }
6445     }
6446     break;
6447     
6448   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6449     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6450     if (!ShAmt) break;
6451     
6452     uint32_t TypeBits = RHSV.getBitWidth();
6453     
6454     // Check that the shift amount is in range.  If not, don't perform
6455     // undefined shifts.  When the shift is visited it will be
6456     // simplified.
6457     if (ShAmt->uge(TypeBits))
6458       break;
6459     
6460     if (ICI.isEquality()) {
6461       // If we are comparing against bits always shifted out, the
6462       // comparison cannot succeed.
6463       Constant *Comp =
6464         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6465       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6466         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6467         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6468         return ReplaceInstUsesWith(ICI, Cst);
6469       }
6470       
6471       if (LHSI->hasOneUse()) {
6472         // Otherwise strength reduce the shift into an and.
6473         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6474         Constant *Mask =
6475           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6476         
6477         Instruction *AndI =
6478           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6479                                     Mask, LHSI->getName()+".mask");
6480         Value *And = InsertNewInstBefore(AndI, ICI);
6481         return new ICmpInst(ICI.getPredicate(), And,
6482                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6483       }
6484     }
6485     
6486     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6487     bool TrueIfSigned = false;
6488     if (LHSI->hasOneUse() &&
6489         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6490       // (X << 31) <s 0  --> (X&1) != 0
6491       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6492                                            (TypeBits-ShAmt->getZExtValue()-1));
6493       Instruction *AndI =
6494         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6495                                   Mask, LHSI->getName()+".mask");
6496       Value *And = InsertNewInstBefore(AndI, ICI);
6497       
6498       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6499                           And, Constant::getNullValue(And->getType()));
6500     }
6501     break;
6502   }
6503     
6504   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6505   case Instruction::AShr: {
6506     // Only handle equality comparisons of shift-by-constant.
6507     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6508     if (!ShAmt || !ICI.isEquality()) break;
6509
6510     // Check that the shift amount is in range.  If not, don't perform
6511     // undefined shifts.  When the shift is visited it will be
6512     // simplified.
6513     uint32_t TypeBits = RHSV.getBitWidth();
6514     if (ShAmt->uge(TypeBits))
6515       break;
6516     
6517     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6518       
6519     // If we are comparing against bits always shifted out, the
6520     // comparison cannot succeed.
6521     APInt Comp = RHSV << ShAmtVal;
6522     if (LHSI->getOpcode() == Instruction::LShr)
6523       Comp = Comp.lshr(ShAmtVal);
6524     else
6525       Comp = Comp.ashr(ShAmtVal);
6526     
6527     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6528       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6529       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6530       return ReplaceInstUsesWith(ICI, Cst);
6531     }
6532     
6533     // Otherwise, check to see if the bits shifted out are known to be zero.
6534     // If so, we can compare against the unshifted value:
6535     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6536     if (LHSI->hasOneUse() &&
6537         MaskedValueIsZero(LHSI->getOperand(0), 
6538                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6539       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6540                           ConstantExpr::getShl(RHS, ShAmt));
6541     }
6542       
6543     if (LHSI->hasOneUse()) {
6544       // Otherwise strength reduce the shift into an and.
6545       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6546       Constant *Mask = ConstantInt::get(Val);
6547       
6548       Instruction *AndI =
6549         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6550                                   Mask, LHSI->getName()+".mask");
6551       Value *And = InsertNewInstBefore(AndI, ICI);
6552       return new ICmpInst(ICI.getPredicate(), And,
6553                           ConstantExpr::getShl(RHS, ShAmt));
6554     }
6555     break;
6556   }
6557     
6558   case Instruction::SDiv:
6559   case Instruction::UDiv:
6560     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6561     // Fold this div into the comparison, producing a range check. 
6562     // Determine, based on the divide type, what the range is being 
6563     // checked.  If there is an overflow on the low or high side, remember 
6564     // it, otherwise compute the range [low, hi) bounding the new value.
6565     // See: InsertRangeTest above for the kinds of replacements possible.
6566     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6567       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6568                                           DivRHS))
6569         return R;
6570     break;
6571
6572   case Instruction::Add:
6573     // Fold: icmp pred (add, X, C1), C2
6574
6575     if (!ICI.isEquality()) {
6576       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6577       if (!LHSC) break;
6578       const APInt &LHSV = LHSC->getValue();
6579
6580       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6581                             .subtract(LHSV);
6582
6583       if (ICI.isSignedPredicate()) {
6584         if (CR.getLower().isSignBit()) {
6585           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6586                               ConstantInt::get(CR.getUpper()));
6587         } else if (CR.getUpper().isSignBit()) {
6588           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6589                               ConstantInt::get(CR.getLower()));
6590         }
6591       } else {
6592         if (CR.getLower().isMinValue()) {
6593           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6594                               ConstantInt::get(CR.getUpper()));
6595         } else if (CR.getUpper().isMinValue()) {
6596           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6597                               ConstantInt::get(CR.getLower()));
6598         }
6599       }
6600     }
6601     break;
6602   }
6603   
6604   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6605   if (ICI.isEquality()) {
6606     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6607     
6608     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6609     // the second operand is a constant, simplify a bit.
6610     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6611       switch (BO->getOpcode()) {
6612       case Instruction::SRem:
6613         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6614         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6615           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6616           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6617             Instruction *NewRem =
6618               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6619                                          BO->getName());
6620             InsertNewInstBefore(NewRem, ICI);
6621             return new ICmpInst(ICI.getPredicate(), NewRem, 
6622                                 Constant::getNullValue(BO->getType()));
6623           }
6624         }
6625         break;
6626       case Instruction::Add:
6627         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6628         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6629           if (BO->hasOneUse())
6630             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6631                                 Subtract(RHS, BOp1C));
6632         } else if (RHSV == 0) {
6633           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6634           // efficiently invertible, or if the add has just this one use.
6635           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6636           
6637           if (Value *NegVal = dyn_castNegVal(BOp1))
6638             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6639           else if (Value *NegVal = dyn_castNegVal(BOp0))
6640             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6641           else if (BO->hasOneUse()) {
6642             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6643             InsertNewInstBefore(Neg, ICI);
6644             Neg->takeName(BO);
6645             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6646           }
6647         }
6648         break;
6649       case Instruction::Xor:
6650         // For the xor case, we can xor two constants together, eliminating
6651         // the explicit xor.
6652         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6653           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6654                               ConstantExpr::getXor(RHS, BOC));
6655         
6656         // FALLTHROUGH
6657       case Instruction::Sub:
6658         // Replace (([sub|xor] A, B) != 0) with (A != B)
6659         if (RHSV == 0)
6660           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6661                               BO->getOperand(1));
6662         break;
6663         
6664       case Instruction::Or:
6665         // If bits are being or'd in that are not present in the constant we
6666         // are comparing against, then the comparison could never succeed!
6667         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6668           Constant *NotCI = ConstantExpr::getNot(RHS);
6669           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6670             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6671                                                              isICMP_NE));
6672         }
6673         break;
6674         
6675       case Instruction::And:
6676         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6677           // If bits are being compared against that are and'd out, then the
6678           // comparison can never succeed!
6679           if ((RHSV & ~BOC->getValue()) != 0)
6680             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6681                                                              isICMP_NE));
6682           
6683           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6684           if (RHS == BOC && RHSV.isPowerOf2())
6685             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6686                                 ICmpInst::ICMP_NE, LHSI,
6687                                 Constant::getNullValue(RHS->getType()));
6688           
6689           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6690           if (BOC->getValue().isSignBit()) {
6691             Value *X = BO->getOperand(0);
6692             Constant *Zero = Constant::getNullValue(X->getType());
6693             ICmpInst::Predicate pred = isICMP_NE ? 
6694               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6695             return new ICmpInst(pred, X, Zero);
6696           }
6697           
6698           // ((X & ~7) == 0) --> X < 8
6699           if (RHSV == 0 && isHighOnes(BOC)) {
6700             Value *X = BO->getOperand(0);
6701             Constant *NegX = ConstantExpr::getNeg(BOC);
6702             ICmpInst::Predicate pred = isICMP_NE ? 
6703               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6704             return new ICmpInst(pred, X, NegX);
6705           }
6706         }
6707       default: break;
6708       }
6709     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6710       // Handle icmp {eq|ne} <intrinsic>, intcst.
6711       if (II->getIntrinsicID() == Intrinsic::bswap) {
6712         AddToWorkList(II);
6713         ICI.setOperand(0, II->getOperand(1));
6714         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6715         return &ICI;
6716       }
6717     }
6718   } else {  // Not a ICMP_EQ/ICMP_NE
6719             // If the LHS is a cast from an integral value of the same size, 
6720             // then since we know the RHS is a constant, try to simlify.
6721     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6722       Value *CastOp = Cast->getOperand(0);
6723       const Type *SrcTy = CastOp->getType();
6724       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6725       if (SrcTy->isInteger() && 
6726           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6727         // If this is an unsigned comparison, try to make the comparison use
6728         // smaller constant values.
6729         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6730           // X u< 128 => X s> -1
6731           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6732                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6733         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6734                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6735           // X u> 127 => X s< 0
6736           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6737                               Constant::getNullValue(SrcTy));
6738         }
6739       }
6740     }
6741   }
6742   return 0;
6743 }
6744
6745 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6746 /// We only handle extending casts so far.
6747 ///
6748 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6749   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6750   Value *LHSCIOp        = LHSCI->getOperand(0);
6751   const Type *SrcTy     = LHSCIOp->getType();
6752   const Type *DestTy    = LHSCI->getType();
6753   Value *RHSCIOp;
6754
6755   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6756   // integer type is the same size as the pointer type.
6757   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6758       getTargetData().getPointerSizeInBits() == 
6759          cast<IntegerType>(DestTy)->getBitWidth()) {
6760     Value *RHSOp = 0;
6761     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6762       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6763     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6764       RHSOp = RHSC->getOperand(0);
6765       // If the pointer types don't match, insert a bitcast.
6766       if (LHSCIOp->getType() != RHSOp->getType())
6767         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6768     }
6769
6770     if (RHSOp)
6771       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6772   }
6773   
6774   // The code below only handles extension cast instructions, so far.
6775   // Enforce this.
6776   if (LHSCI->getOpcode() != Instruction::ZExt &&
6777       LHSCI->getOpcode() != Instruction::SExt)
6778     return 0;
6779
6780   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6781   bool isSignedCmp = ICI.isSignedPredicate();
6782
6783   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6784     // Not an extension from the same type?
6785     RHSCIOp = CI->getOperand(0);
6786     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6787       return 0;
6788     
6789     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6790     // and the other is a zext), then we can't handle this.
6791     if (CI->getOpcode() != LHSCI->getOpcode())
6792       return 0;
6793
6794     // Deal with equality cases early.
6795     if (ICI.isEquality())
6796       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6797
6798     // A signed comparison of sign extended values simplifies into a
6799     // signed comparison.
6800     if (isSignedCmp && isSignedExt)
6801       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6802
6803     // The other three cases all fold into an unsigned comparison.
6804     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6805   }
6806
6807   // If we aren't dealing with a constant on the RHS, exit early
6808   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6809   if (!CI)
6810     return 0;
6811
6812   // Compute the constant that would happen if we truncated to SrcTy then
6813   // reextended to DestTy.
6814   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6815   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6816
6817   // If the re-extended constant didn't change...
6818   if (Res2 == CI) {
6819     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6820     // For example, we might have:
6821     //    %A = sext short %X to uint
6822     //    %B = icmp ugt uint %A, 1330
6823     // It is incorrect to transform this into 
6824     //    %B = icmp ugt short %X, 1330 
6825     // because %A may have negative value. 
6826     //
6827     // However, we allow this when the compare is EQ/NE, because they are
6828     // signless.
6829     if (isSignedExt == isSignedCmp || ICI.isEquality())
6830       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6831     return 0;
6832   }
6833
6834   // The re-extended constant changed so the constant cannot be represented 
6835   // in the shorter type. Consequently, we cannot emit a simple comparison.
6836
6837   // First, handle some easy cases. We know the result cannot be equal at this
6838   // point so handle the ICI.isEquality() cases
6839   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6840     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6841   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6842     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6843
6844   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6845   // should have been folded away previously and not enter in here.
6846   Value *Result;
6847   if (isSignedCmp) {
6848     // We're performing a signed comparison.
6849     if (cast<ConstantInt>(CI)->getValue().isNegative())
6850       Result = ConstantInt::getFalse();          // X < (small) --> false
6851     else
6852       Result = ConstantInt::getTrue();           // X < (large) --> true
6853   } else {
6854     // We're performing an unsigned comparison.
6855     if (isSignedExt) {
6856       // We're performing an unsigned comp with a sign extended value.
6857       // This is true if the input is >= 0. [aka >s -1]
6858       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6859       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6860                                    NegOne, ICI.getName()), ICI);
6861     } else {
6862       // Unsigned extend & unsigned compare -> always true.
6863       Result = ConstantInt::getTrue();
6864     }
6865   }
6866
6867   // Finally, return the value computed.
6868   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6869       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6870     return ReplaceInstUsesWith(ICI, Result);
6871
6872   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6873           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6874          "ICmp should be folded!");
6875   if (Constant *CI = dyn_cast<Constant>(Result))
6876     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6877   return BinaryOperator::CreateNot(Result);
6878 }
6879
6880 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6881   return commonShiftTransforms(I);
6882 }
6883
6884 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6885   return commonShiftTransforms(I);
6886 }
6887
6888 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6889   if (Instruction *R = commonShiftTransforms(I))
6890     return R;
6891   
6892   Value *Op0 = I.getOperand(0);
6893   
6894   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6895   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6896     if (CSI->isAllOnesValue())
6897       return ReplaceInstUsesWith(I, CSI);
6898   
6899   // See if we can turn a signed shr into an unsigned shr.
6900   if (!isa<VectorType>(I.getType()) &&
6901       MaskedValueIsZero(Op0,
6902                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6903     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6904   
6905   return 0;
6906 }
6907
6908 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6909   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6910   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6911
6912   // shl X, 0 == X and shr X, 0 == X
6913   // shl 0, X == 0 and shr 0, X == 0
6914   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6915       Op0 == Constant::getNullValue(Op0->getType()))
6916     return ReplaceInstUsesWith(I, Op0);
6917   
6918   if (isa<UndefValue>(Op0)) {            
6919     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6920       return ReplaceInstUsesWith(I, Op0);
6921     else                                    // undef << X -> 0, undef >>u X -> 0
6922       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6923   }
6924   if (isa<UndefValue>(Op1)) {
6925     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6926       return ReplaceInstUsesWith(I, Op0);          
6927     else                                     // X << undef, X >>u undef -> 0
6928       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6929   }
6930
6931   // Try to fold constant and into select arguments.
6932   if (isa<Constant>(Op0))
6933     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6934       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6935         return R;
6936
6937   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6938     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6939       return Res;
6940   return 0;
6941 }
6942
6943 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6944                                                BinaryOperator &I) {
6945   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6946
6947   // See if we can simplify any instructions used by the instruction whose sole 
6948   // purpose is to compute bits we don't care about.
6949   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6950   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6951   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6952                            KnownZero, KnownOne))
6953     return &I;
6954   
6955   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6956   // of a signed value.
6957   //
6958   if (Op1->uge(TypeBits)) {
6959     if (I.getOpcode() != Instruction::AShr)
6960       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6961     else {
6962       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6963       return &I;
6964     }
6965   }
6966   
6967   // ((X*C1) << C2) == (X * (C1 << C2))
6968   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6969     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6970       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6971         return BinaryOperator::CreateMul(BO->getOperand(0),
6972                                          ConstantExpr::getShl(BOOp, Op1));
6973   
6974   // Try to fold constant and into select arguments.
6975   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6976     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6977       return R;
6978   if (isa<PHINode>(Op0))
6979     if (Instruction *NV = FoldOpIntoPhi(I))
6980       return NV;
6981   
6982   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6983   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6984     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6985     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6986     // place.  Don't try to do this transformation in this case.  Also, we
6987     // require that the input operand is a shift-by-constant so that we have
6988     // confidence that the shifts will get folded together.  We could do this
6989     // xform in more cases, but it is unlikely to be profitable.
6990     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6991         isa<ConstantInt>(TrOp->getOperand(1))) {
6992       // Okay, we'll do this xform.  Make the shift of shift.
6993       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6994       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6995                                                 I.getName());
6996       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6997
6998       // For logical shifts, the truncation has the effect of making the high
6999       // part of the register be zeros.  Emulate this by inserting an AND to
7000       // clear the top bits as needed.  This 'and' will usually be zapped by
7001       // other xforms later if dead.
7002       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7003       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7004       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7005       
7006       // The mask we constructed says what the trunc would do if occurring
7007       // between the shifts.  We want to know the effect *after* the second
7008       // shift.  We know that it is a logical shift by a constant, so adjust the
7009       // mask as appropriate.
7010       if (I.getOpcode() == Instruction::Shl)
7011         MaskV <<= Op1->getZExtValue();
7012       else {
7013         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7014         MaskV = MaskV.lshr(Op1->getZExtValue());
7015       }
7016
7017       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7018                                                    TI->getName());
7019       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7020
7021       // Return the value truncated to the interesting size.
7022       return new TruncInst(And, I.getType());
7023     }
7024   }
7025   
7026   if (Op0->hasOneUse()) {
7027     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7028       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7029       Value *V1, *V2;
7030       ConstantInt *CC;
7031       switch (Op0BO->getOpcode()) {
7032         default: break;
7033         case Instruction::Add:
7034         case Instruction::And:
7035         case Instruction::Or:
7036         case Instruction::Xor: {
7037           // These operators commute.
7038           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7039           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7040               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7041             Instruction *YS = BinaryOperator::CreateShl(
7042                                             Op0BO->getOperand(0), Op1,
7043                                             Op0BO->getName());
7044             InsertNewInstBefore(YS, I); // (Y << C)
7045             Instruction *X = 
7046               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7047                                      Op0BO->getOperand(1)->getName());
7048             InsertNewInstBefore(X, I);  // (X + (Y << C))
7049             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7050             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7051                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7052           }
7053           
7054           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7055           Value *Op0BOOp1 = Op0BO->getOperand(1);
7056           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7057               match(Op0BOOp1, 
7058                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7059                           m_ConstantInt(CC))) &&
7060               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7061             Instruction *YS = BinaryOperator::CreateShl(
7062                                                      Op0BO->getOperand(0), Op1,
7063                                                      Op0BO->getName());
7064             InsertNewInstBefore(YS, I); // (Y << C)
7065             Instruction *XM =
7066               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7067                                         V1->getName()+".mask");
7068             InsertNewInstBefore(XM, I); // X & (CC << C)
7069             
7070             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7071           }
7072         }
7073           
7074         // FALL THROUGH.
7075         case Instruction::Sub: {
7076           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7077           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7078               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7079             Instruction *YS = BinaryOperator::CreateShl(
7080                                                      Op0BO->getOperand(1), Op1,
7081                                                      Op0BO->getName());
7082             InsertNewInstBefore(YS, I); // (Y << C)
7083             Instruction *X =
7084               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7085                                      Op0BO->getOperand(0)->getName());
7086             InsertNewInstBefore(X, I);  // (X + (Y << C))
7087             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7088             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7089                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7090           }
7091           
7092           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7093           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7094               match(Op0BO->getOperand(0),
7095                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7096                           m_ConstantInt(CC))) && V2 == Op1 &&
7097               cast<BinaryOperator>(Op0BO->getOperand(0))
7098                   ->getOperand(0)->hasOneUse()) {
7099             Instruction *YS = BinaryOperator::CreateShl(
7100                                                      Op0BO->getOperand(1), Op1,
7101                                                      Op0BO->getName());
7102             InsertNewInstBefore(YS, I); // (Y << C)
7103             Instruction *XM =
7104               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7105                                         V1->getName()+".mask");
7106             InsertNewInstBefore(XM, I); // X & (CC << C)
7107             
7108             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7109           }
7110           
7111           break;
7112         }
7113       }
7114       
7115       
7116       // If the operand is an bitwise operator with a constant RHS, and the
7117       // shift is the only use, we can pull it out of the shift.
7118       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7119         bool isValid = true;     // Valid only for And, Or, Xor
7120         bool highBitSet = false; // Transform if high bit of constant set?
7121         
7122         switch (Op0BO->getOpcode()) {
7123           default: isValid = false; break;   // Do not perform transform!
7124           case Instruction::Add:
7125             isValid = isLeftShift;
7126             break;
7127           case Instruction::Or:
7128           case Instruction::Xor:
7129             highBitSet = false;
7130             break;
7131           case Instruction::And:
7132             highBitSet = true;
7133             break;
7134         }
7135         
7136         // If this is a signed shift right, and the high bit is modified
7137         // by the logical operation, do not perform the transformation.
7138         // The highBitSet boolean indicates the value of the high bit of
7139         // the constant which would cause it to be modified for this
7140         // operation.
7141         //
7142         if (isValid && I.getOpcode() == Instruction::AShr)
7143           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7144         
7145         if (isValid) {
7146           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7147           
7148           Instruction *NewShift =
7149             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7150           InsertNewInstBefore(NewShift, I);
7151           NewShift->takeName(Op0BO);
7152           
7153           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7154                                         NewRHS);
7155         }
7156       }
7157     }
7158   }
7159   
7160   // Find out if this is a shift of a shift by a constant.
7161   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7162   if (ShiftOp && !ShiftOp->isShift())
7163     ShiftOp = 0;
7164   
7165   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7166     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7167     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7168     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7169     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7170     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7171     Value *X = ShiftOp->getOperand(0);
7172     
7173     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7174     if (AmtSum > TypeBits)
7175       AmtSum = TypeBits;
7176     
7177     const IntegerType *Ty = cast<IntegerType>(I.getType());
7178     
7179     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7180     if (I.getOpcode() == ShiftOp->getOpcode()) {
7181       return BinaryOperator::Create(I.getOpcode(), X,
7182                                     ConstantInt::get(Ty, AmtSum));
7183     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7184                I.getOpcode() == Instruction::AShr) {
7185       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7186       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7187     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7188                I.getOpcode() == Instruction::LShr) {
7189       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7190       Instruction *Shift =
7191         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7192       InsertNewInstBefore(Shift, I);
7193
7194       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7195       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7196     }
7197     
7198     // Okay, if we get here, one shift must be left, and the other shift must be
7199     // right.  See if the amounts are equal.
7200     if (ShiftAmt1 == ShiftAmt2) {
7201       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7202       if (I.getOpcode() == Instruction::Shl) {
7203         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7204         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7205       }
7206       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7207       if (I.getOpcode() == Instruction::LShr) {
7208         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7209         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7210       }
7211       // We can simplify ((X << C) >>s C) into a trunc + sext.
7212       // NOTE: we could do this for any C, but that would make 'unusual' integer
7213       // types.  For now, just stick to ones well-supported by the code
7214       // generators.
7215       const Type *SExtType = 0;
7216       switch (Ty->getBitWidth() - ShiftAmt1) {
7217       case 1  :
7218       case 8  :
7219       case 16 :
7220       case 32 :
7221       case 64 :
7222       case 128:
7223         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7224         break;
7225       default: break;
7226       }
7227       if (SExtType) {
7228         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7229         InsertNewInstBefore(NewTrunc, I);
7230         return new SExtInst(NewTrunc, Ty);
7231       }
7232       // Otherwise, we can't handle it yet.
7233     } else if (ShiftAmt1 < ShiftAmt2) {
7234       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7235       
7236       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7237       if (I.getOpcode() == Instruction::Shl) {
7238         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7239                ShiftOp->getOpcode() == Instruction::AShr);
7240         Instruction *Shift =
7241           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7242         InsertNewInstBefore(Shift, I);
7243         
7244         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7245         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7246       }
7247       
7248       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7249       if (I.getOpcode() == Instruction::LShr) {
7250         assert(ShiftOp->getOpcode() == Instruction::Shl);
7251         Instruction *Shift =
7252           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7253         InsertNewInstBefore(Shift, I);
7254         
7255         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7256         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7257       }
7258       
7259       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7260     } else {
7261       assert(ShiftAmt2 < ShiftAmt1);
7262       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7263
7264       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7265       if (I.getOpcode() == Instruction::Shl) {
7266         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7267                ShiftOp->getOpcode() == Instruction::AShr);
7268         Instruction *Shift =
7269           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7270                                  ConstantInt::get(Ty, ShiftDiff));
7271         InsertNewInstBefore(Shift, I);
7272         
7273         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7274         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7275       }
7276       
7277       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7278       if (I.getOpcode() == Instruction::LShr) {
7279         assert(ShiftOp->getOpcode() == Instruction::Shl);
7280         Instruction *Shift =
7281           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7282         InsertNewInstBefore(Shift, I);
7283         
7284         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7285         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7286       }
7287       
7288       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7289     }
7290   }
7291   return 0;
7292 }
7293
7294
7295 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7296 /// expression.  If so, decompose it, returning some value X, such that Val is
7297 /// X*Scale+Offset.
7298 ///
7299 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7300                                         int &Offset) {
7301   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7302   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7303     Offset = CI->getZExtValue();
7304     Scale  = 0;
7305     return ConstantInt::get(Type::Int32Ty, 0);
7306   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7307     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7308       if (I->getOpcode() == Instruction::Shl) {
7309         // This is a value scaled by '1 << the shift amt'.
7310         Scale = 1U << RHS->getZExtValue();
7311         Offset = 0;
7312         return I->getOperand(0);
7313       } else if (I->getOpcode() == Instruction::Mul) {
7314         // This value is scaled by 'RHS'.
7315         Scale = RHS->getZExtValue();
7316         Offset = 0;
7317         return I->getOperand(0);
7318       } else if (I->getOpcode() == Instruction::Add) {
7319         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7320         // where C1 is divisible by C2.
7321         unsigned SubScale;
7322         Value *SubVal = 
7323           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7324         Offset += RHS->getZExtValue();
7325         Scale = SubScale;
7326         return SubVal;
7327       }
7328     }
7329   }
7330
7331   // Otherwise, we can't look past this.
7332   Scale = 1;
7333   Offset = 0;
7334   return Val;
7335 }
7336
7337
7338 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7339 /// try to eliminate the cast by moving the type information into the alloc.
7340 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7341                                                    AllocationInst &AI) {
7342   const PointerType *PTy = cast<PointerType>(CI.getType());
7343   
7344   // Remove any uses of AI that are dead.
7345   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7346   
7347   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7348     Instruction *User = cast<Instruction>(*UI++);
7349     if (isInstructionTriviallyDead(User)) {
7350       while (UI != E && *UI == User)
7351         ++UI; // If this instruction uses AI more than once, don't break UI.
7352       
7353       ++NumDeadInst;
7354       DOUT << "IC: DCE: " << *User;
7355       EraseInstFromFunction(*User);
7356     }
7357   }
7358   
7359   // Get the type really allocated and the type casted to.
7360   const Type *AllocElTy = AI.getAllocatedType();
7361   const Type *CastElTy = PTy->getElementType();
7362   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7363
7364   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7365   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7366   if (CastElTyAlign < AllocElTyAlign) return 0;
7367
7368   // If the allocation has multiple uses, only promote it if we are strictly
7369   // increasing the alignment of the resultant allocation.  If we keep it the
7370   // same, we open the door to infinite loops of various kinds.
7371   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7372
7373   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7374   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7375   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7376
7377   // See if we can satisfy the modulus by pulling a scale out of the array
7378   // size argument.
7379   unsigned ArraySizeScale;
7380   int ArrayOffset;
7381   Value *NumElements = // See if the array size is a decomposable linear expr.
7382     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7383  
7384   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7385   // do the xform.
7386   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7387       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7388
7389   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7390   Value *Amt = 0;
7391   if (Scale == 1) {
7392     Amt = NumElements;
7393   } else {
7394     // If the allocation size is constant, form a constant mul expression
7395     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7396     if (isa<ConstantInt>(NumElements))
7397       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7398     // otherwise multiply the amount and the number of elements
7399     else if (Scale != 1) {
7400       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7401       Amt = InsertNewInstBefore(Tmp, AI);
7402     }
7403   }
7404   
7405   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7406     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7407     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7408     Amt = InsertNewInstBefore(Tmp, AI);
7409   }
7410   
7411   AllocationInst *New;
7412   if (isa<MallocInst>(AI))
7413     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7414   else
7415     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7416   InsertNewInstBefore(New, AI);
7417   New->takeName(&AI);
7418   
7419   // If the allocation has multiple uses, insert a cast and change all things
7420   // that used it to use the new cast.  This will also hack on CI, but it will
7421   // die soon.
7422   if (!AI.hasOneUse()) {
7423     AddUsesToWorkList(AI);
7424     // New is the allocation instruction, pointer typed. AI is the original
7425     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7426     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7427     InsertNewInstBefore(NewCast, AI);
7428     AI.replaceAllUsesWith(NewCast);
7429   }
7430   return ReplaceInstUsesWith(CI, New);
7431 }
7432
7433 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7434 /// and return it as type Ty without inserting any new casts and without
7435 /// changing the computed value.  This is used by code that tries to decide
7436 /// whether promoting or shrinking integer operations to wider or smaller types
7437 /// will allow us to eliminate a truncate or extend.
7438 ///
7439 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7440 /// extension operation if Ty is larger.
7441 ///
7442 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7443 /// should return true if trunc(V) can be computed by computing V in the smaller
7444 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7445 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7446 /// efficiently truncated.
7447 ///
7448 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7449 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7450 /// the final result.
7451 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7452                                               unsigned CastOpc,
7453                                               int &NumCastsRemoved) {
7454   // We can always evaluate constants in another type.
7455   if (isa<ConstantInt>(V))
7456     return true;
7457   
7458   Instruction *I = dyn_cast<Instruction>(V);
7459   if (!I) return false;
7460   
7461   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7462   
7463   // If this is an extension or truncate, we can often eliminate it.
7464   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7465     // If this is a cast from the destination type, we can trivially eliminate
7466     // it, and this will remove a cast overall.
7467     if (I->getOperand(0)->getType() == Ty) {
7468       // If the first operand is itself a cast, and is eliminable, do not count
7469       // this as an eliminable cast.  We would prefer to eliminate those two
7470       // casts first.
7471       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7472         ++NumCastsRemoved;
7473       return true;
7474     }
7475   }
7476
7477   // We can't extend or shrink something that has multiple uses: doing so would
7478   // require duplicating the instruction in general, which isn't profitable.
7479   if (!I->hasOneUse()) return false;
7480
7481   switch (I->getOpcode()) {
7482   case Instruction::Add:
7483   case Instruction::Sub:
7484   case Instruction::Mul:
7485   case Instruction::And:
7486   case Instruction::Or:
7487   case Instruction::Xor:
7488     // These operators can all arbitrarily be extended or truncated.
7489     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7490                                       NumCastsRemoved) &&
7491            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7492                                       NumCastsRemoved);
7493
7494   case Instruction::Shl:
7495     // If we are truncating the result of this SHL, and if it's a shift of a
7496     // constant amount, we can always perform a SHL in a smaller type.
7497     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7498       uint32_t BitWidth = Ty->getBitWidth();
7499       if (BitWidth < OrigTy->getBitWidth() && 
7500           CI->getLimitedValue(BitWidth) < BitWidth)
7501         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7502                                           NumCastsRemoved);
7503     }
7504     break;
7505   case Instruction::LShr:
7506     // If this is a truncate of a logical shr, we can truncate it to a smaller
7507     // lshr iff we know that the bits we would otherwise be shifting in are
7508     // already zeros.
7509     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7510       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7511       uint32_t BitWidth = Ty->getBitWidth();
7512       if (BitWidth < OrigBitWidth &&
7513           MaskedValueIsZero(I->getOperand(0),
7514             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7515           CI->getLimitedValue(BitWidth) < BitWidth) {
7516         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7517                                           NumCastsRemoved);
7518       }
7519     }
7520     break;
7521   case Instruction::ZExt:
7522   case Instruction::SExt:
7523   case Instruction::Trunc:
7524     // If this is the same kind of case as our original (e.g. zext+zext), we
7525     // can safely replace it.  Note that replacing it does not reduce the number
7526     // of casts in the input.
7527     if (I->getOpcode() == CastOpc)
7528       return true;
7529     break;
7530   case Instruction::Select: {
7531     SelectInst *SI = cast<SelectInst>(I);
7532     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7533                                       NumCastsRemoved) &&
7534            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7535                                       NumCastsRemoved);
7536   }
7537   case Instruction::PHI: {
7538     // We can change a phi if we can change all operands.
7539     PHINode *PN = cast<PHINode>(I);
7540     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7541       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7542                                       NumCastsRemoved))
7543         return false;
7544     return true;
7545   }
7546   default:
7547     // TODO: Can handle more cases here.
7548     break;
7549   }
7550   
7551   return false;
7552 }
7553
7554 /// EvaluateInDifferentType - Given an expression that 
7555 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7556 /// evaluate the expression.
7557 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7558                                              bool isSigned) {
7559   if (Constant *C = dyn_cast<Constant>(V))
7560     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7561
7562   // Otherwise, it must be an instruction.
7563   Instruction *I = cast<Instruction>(V);
7564   Instruction *Res = 0;
7565   switch (I->getOpcode()) {
7566   case Instruction::Add:
7567   case Instruction::Sub:
7568   case Instruction::Mul:
7569   case Instruction::And:
7570   case Instruction::Or:
7571   case Instruction::Xor:
7572   case Instruction::AShr:
7573   case Instruction::LShr:
7574   case Instruction::Shl: {
7575     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7576     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7577     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7578                                  LHS, RHS);
7579     break;
7580   }    
7581   case Instruction::Trunc:
7582   case Instruction::ZExt:
7583   case Instruction::SExt:
7584     // If the source type of the cast is the type we're trying for then we can
7585     // just return the source.  There's no need to insert it because it is not
7586     // new.
7587     if (I->getOperand(0)->getType() == Ty)
7588       return I->getOperand(0);
7589     
7590     // Otherwise, must be the same type of cast, so just reinsert a new one.
7591     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7592                            Ty);
7593     break;
7594   case Instruction::Select: {
7595     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7596     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7597     Res = SelectInst::Create(I->getOperand(0), True, False);
7598     break;
7599   }
7600   case Instruction::PHI: {
7601     PHINode *OPN = cast<PHINode>(I);
7602     PHINode *NPN = PHINode::Create(Ty);
7603     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7604       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7605       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7606     }
7607     Res = NPN;
7608     break;
7609   }
7610   default: 
7611     // TODO: Can handle more cases here.
7612     assert(0 && "Unreachable!");
7613     break;
7614   }
7615   
7616   Res->takeName(I);
7617   return InsertNewInstBefore(Res, *I);
7618 }
7619
7620 /// @brief Implement the transforms common to all CastInst visitors.
7621 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7622   Value *Src = CI.getOperand(0);
7623
7624   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7625   // eliminate it now.
7626   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7627     if (Instruction::CastOps opc = 
7628         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7629       // The first cast (CSrc) is eliminable so we need to fix up or replace
7630       // the second cast (CI). CSrc will then have a good chance of being dead.
7631       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7632     }
7633   }
7634
7635   // If we are casting a select then fold the cast into the select
7636   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7637     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7638       return NV;
7639
7640   // If we are casting a PHI then fold the cast into the PHI
7641   if (isa<PHINode>(Src))
7642     if (Instruction *NV = FoldOpIntoPhi(CI))
7643       return NV;
7644   
7645   return 0;
7646 }
7647
7648 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7649 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7650   Value *Src = CI.getOperand(0);
7651   
7652   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7653     // If casting the result of a getelementptr instruction with no offset, turn
7654     // this into a cast of the original pointer!
7655     if (GEP->hasAllZeroIndices()) {
7656       // Changing the cast operand is usually not a good idea but it is safe
7657       // here because the pointer operand is being replaced with another 
7658       // pointer operand so the opcode doesn't need to change.
7659       AddToWorkList(GEP);
7660       CI.setOperand(0, GEP->getOperand(0));
7661       return &CI;
7662     }
7663     
7664     // If the GEP has a single use, and the base pointer is a bitcast, and the
7665     // GEP computes a constant offset, see if we can convert these three
7666     // instructions into fewer.  This typically happens with unions and other
7667     // non-type-safe code.
7668     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7669       if (GEP->hasAllConstantIndices()) {
7670         // We are guaranteed to get a constant from EmitGEPOffset.
7671         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7672         int64_t Offset = OffsetV->getSExtValue();
7673         
7674         // Get the base pointer input of the bitcast, and the type it points to.
7675         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7676         const Type *GEPIdxTy =
7677           cast<PointerType>(OrigBase->getType())->getElementType();
7678         if (GEPIdxTy->isSized()) {
7679           SmallVector<Value*, 8> NewIndices;
7680           
7681           // Start with the index over the outer type.  Note that the type size
7682           // might be zero (even if the offset isn't zero) if the indexed type
7683           // is something like [0 x {int, int}]
7684           const Type *IntPtrTy = TD->getIntPtrType();
7685           int64_t FirstIdx = 0;
7686           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7687             FirstIdx = Offset/TySize;
7688             Offset %= TySize;
7689           
7690             // Handle silly modulus not returning values values [0..TySize).
7691             if (Offset < 0) {
7692               --FirstIdx;
7693               Offset += TySize;
7694               assert(Offset >= 0);
7695             }
7696             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7697           }
7698           
7699           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7700
7701           // Index into the types.  If we fail, set OrigBase to null.
7702           while (Offset) {
7703             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7704               const StructLayout *SL = TD->getStructLayout(STy);
7705               if (Offset < (int64_t)SL->getSizeInBytes()) {
7706                 unsigned Elt = SL->getElementContainingOffset(Offset);
7707                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7708               
7709                 Offset -= SL->getElementOffset(Elt);
7710                 GEPIdxTy = STy->getElementType(Elt);
7711               } else {
7712                 // Otherwise, we can't index into this, bail out.
7713                 Offset = 0;
7714                 OrigBase = 0;
7715               }
7716             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7717               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7718               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7719                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7720                 Offset %= EltSize;
7721               } else {
7722                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7723               }
7724               GEPIdxTy = STy->getElementType();
7725             } else {
7726               // Otherwise, we can't index into this, bail out.
7727               Offset = 0;
7728               OrigBase = 0;
7729             }
7730           }
7731           if (OrigBase) {
7732             // If we were able to index down into an element, create the GEP
7733             // and bitcast the result.  This eliminates one bitcast, potentially
7734             // two.
7735             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7736                                                           NewIndices.begin(),
7737                                                           NewIndices.end(), "");
7738             InsertNewInstBefore(NGEP, CI);
7739             NGEP->takeName(GEP);
7740             
7741             if (isa<BitCastInst>(CI))
7742               return new BitCastInst(NGEP, CI.getType());
7743             assert(isa<PtrToIntInst>(CI));
7744             return new PtrToIntInst(NGEP, CI.getType());
7745           }
7746         }
7747       }      
7748     }
7749   }
7750     
7751   return commonCastTransforms(CI);
7752 }
7753
7754
7755
7756 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7757 /// integer types. This function implements the common transforms for all those
7758 /// cases.
7759 /// @brief Implement the transforms common to CastInst with integer operands
7760 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7761   if (Instruction *Result = commonCastTransforms(CI))
7762     return Result;
7763
7764   Value *Src = CI.getOperand(0);
7765   const Type *SrcTy = Src->getType();
7766   const Type *DestTy = CI.getType();
7767   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7768   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7769
7770   // See if we can simplify any instructions used by the LHS whose sole 
7771   // purpose is to compute bits we don't care about.
7772   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7773   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7774                            KnownZero, KnownOne))
7775     return &CI;
7776
7777   // If the source isn't an instruction or has more than one use then we
7778   // can't do anything more. 
7779   Instruction *SrcI = dyn_cast<Instruction>(Src);
7780   if (!SrcI || !Src->hasOneUse())
7781     return 0;
7782
7783   // Attempt to propagate the cast into the instruction for int->int casts.
7784   int NumCastsRemoved = 0;
7785   if (!isa<BitCastInst>(CI) &&
7786       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7787                                  CI.getOpcode(), NumCastsRemoved)) {
7788     // If this cast is a truncate, evaluting in a different type always
7789     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7790     // we need to do an AND to maintain the clear top-part of the computation,
7791     // so we require that the input have eliminated at least one cast.  If this
7792     // is a sign extension, we insert two new casts (to do the extension) so we
7793     // require that two casts have been eliminated.
7794     bool DoXForm;
7795     switch (CI.getOpcode()) {
7796     default:
7797       // All the others use floating point so we shouldn't actually 
7798       // get here because of the check above.
7799       assert(0 && "Unknown cast type");
7800     case Instruction::Trunc:
7801       DoXForm = true;
7802       break;
7803     case Instruction::ZExt:
7804       DoXForm = NumCastsRemoved >= 1;
7805       break;
7806     case Instruction::SExt:
7807       DoXForm = NumCastsRemoved >= 2;
7808       break;
7809     }
7810     
7811     if (DoXForm) {
7812       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7813                                            CI.getOpcode() == Instruction::SExt);
7814       assert(Res->getType() == DestTy);
7815       switch (CI.getOpcode()) {
7816       default: assert(0 && "Unknown cast type!");
7817       case Instruction::Trunc:
7818       case Instruction::BitCast:
7819         // Just replace this cast with the result.
7820         return ReplaceInstUsesWith(CI, Res);
7821       case Instruction::ZExt: {
7822         // We need to emit an AND to clear the high bits.
7823         assert(SrcBitSize < DestBitSize && "Not a zext?");
7824         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7825                                                             SrcBitSize));
7826         return BinaryOperator::CreateAnd(Res, C);
7827       }
7828       case Instruction::SExt:
7829         // We need to emit a cast to truncate, then a cast to sext.
7830         return CastInst::Create(Instruction::SExt,
7831             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7832                              CI), DestTy);
7833       }
7834     }
7835   }
7836   
7837   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7838   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7839
7840   switch (SrcI->getOpcode()) {
7841   case Instruction::Add:
7842   case Instruction::Mul:
7843   case Instruction::And:
7844   case Instruction::Or:
7845   case Instruction::Xor:
7846     // If we are discarding information, rewrite.
7847     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7848       // Don't insert two casts if they cannot be eliminated.  We allow 
7849       // two casts to be inserted if the sizes are the same.  This could 
7850       // only be converting signedness, which is a noop.
7851       if (DestBitSize == SrcBitSize || 
7852           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7853           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7854         Instruction::CastOps opcode = CI.getOpcode();
7855         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7856         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7857         return BinaryOperator::Create(
7858             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7859       }
7860     }
7861
7862     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7863     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7864         SrcI->getOpcode() == Instruction::Xor &&
7865         Op1 == ConstantInt::getTrue() &&
7866         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7867       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7868       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7869     }
7870     break;
7871   case Instruction::SDiv:
7872   case Instruction::UDiv:
7873   case Instruction::SRem:
7874   case Instruction::URem:
7875     // If we are just changing the sign, rewrite.
7876     if (DestBitSize == SrcBitSize) {
7877       // Don't insert two casts if they cannot be eliminated.  We allow 
7878       // two casts to be inserted if the sizes are the same.  This could 
7879       // only be converting signedness, which is a noop.
7880       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7881           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7882         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7883                                               Op0, DestTy, SrcI);
7884         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7885                                               Op1, DestTy, SrcI);
7886         return BinaryOperator::Create(
7887           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7888       }
7889     }
7890     break;
7891
7892   case Instruction::Shl:
7893     // Allow changing the sign of the source operand.  Do not allow 
7894     // changing the size of the shift, UNLESS the shift amount is a 
7895     // constant.  We must not change variable sized shifts to a smaller 
7896     // size, because it is undefined to shift more bits out than exist 
7897     // in the value.
7898     if (DestBitSize == SrcBitSize ||
7899         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7900       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7901           Instruction::BitCast : Instruction::Trunc);
7902       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7903       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7904       return BinaryOperator::CreateShl(Op0c, Op1c);
7905     }
7906     break;
7907   case Instruction::AShr:
7908     // If this is a signed shr, and if all bits shifted in are about to be
7909     // truncated off, turn it into an unsigned shr to allow greater
7910     // simplifications.
7911     if (DestBitSize < SrcBitSize &&
7912         isa<ConstantInt>(Op1)) {
7913       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7914       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7915         // Insert the new logical shift right.
7916         return BinaryOperator::CreateLShr(Op0, Op1);
7917       }
7918     }
7919     break;
7920   }
7921   return 0;
7922 }
7923
7924 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7925   if (Instruction *Result = commonIntCastTransforms(CI))
7926     return Result;
7927   
7928   Value *Src = CI.getOperand(0);
7929   const Type *Ty = CI.getType();
7930   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7931   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7932   
7933   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7934     switch (SrcI->getOpcode()) {
7935     default: break;
7936     case Instruction::LShr:
7937       // We can shrink lshr to something smaller if we know the bits shifted in
7938       // are already zeros.
7939       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7940         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7941         
7942         // Get a mask for the bits shifting in.
7943         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7944         Value* SrcIOp0 = SrcI->getOperand(0);
7945         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7946           if (ShAmt >= DestBitWidth)        // All zeros.
7947             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7948
7949           // Okay, we can shrink this.  Truncate the input, then return a new
7950           // shift.
7951           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7952           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7953                                        Ty, CI);
7954           return BinaryOperator::CreateLShr(V1, V2);
7955         }
7956       } else {     // This is a variable shr.
7957         
7958         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7959         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7960         // loop-invariant and CSE'd.
7961         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7962           Value *One = ConstantInt::get(SrcI->getType(), 1);
7963
7964           Value *V = InsertNewInstBefore(
7965               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7966                                      "tmp"), CI);
7967           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7968                                                             SrcI->getOperand(0),
7969                                                             "tmp"), CI);
7970           Value *Zero = Constant::getNullValue(V->getType());
7971           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7972         }
7973       }
7974       break;
7975     }
7976   }
7977   
7978   return 0;
7979 }
7980
7981 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7982 /// in order to eliminate the icmp.
7983 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7984                                              bool DoXform) {
7985   // If we are just checking for a icmp eq of a single bit and zext'ing it
7986   // to an integer, then shift the bit to the appropriate place and then
7987   // cast to integer to avoid the comparison.
7988   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7989     const APInt &Op1CV = Op1C->getValue();
7990       
7991     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7992     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7993     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7994         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7995       if (!DoXform) return ICI;
7996
7997       Value *In = ICI->getOperand(0);
7998       Value *Sh = ConstantInt::get(In->getType(),
7999                                    In->getType()->getPrimitiveSizeInBits()-1);
8000       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8001                                                         In->getName()+".lobit"),
8002                                CI);
8003       if (In->getType() != CI.getType())
8004         In = CastInst::CreateIntegerCast(In, CI.getType(),
8005                                          false/*ZExt*/, "tmp", &CI);
8006
8007       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8008         Constant *One = ConstantInt::get(In->getType(), 1);
8009         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8010                                                          In->getName()+".not"),
8011                                  CI);
8012       }
8013
8014       return ReplaceInstUsesWith(CI, In);
8015     }
8016       
8017       
8018       
8019     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8020     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8021     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8022     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8023     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8024     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8025     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8026     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8027     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8028         // This only works for EQ and NE
8029         ICI->isEquality()) {
8030       // If Op1C some other power of two, convert:
8031       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8032       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8033       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8034       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8035         
8036       APInt KnownZeroMask(~KnownZero);
8037       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8038         if (!DoXform) return ICI;
8039
8040         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8041         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8042           // (X&4) == 2 --> false
8043           // (X&4) != 2 --> true
8044           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8045           Res = ConstantExpr::getZExt(Res, CI.getType());
8046           return ReplaceInstUsesWith(CI, Res);
8047         }
8048           
8049         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8050         Value *In = ICI->getOperand(0);
8051         if (ShiftAmt) {
8052           // Perform a logical shr by shiftamt.
8053           // Insert the shift to put the result in the low bit.
8054           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8055                                   ConstantInt::get(In->getType(), ShiftAmt),
8056                                                    In->getName()+".lobit"), CI);
8057         }
8058           
8059         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8060           Constant *One = ConstantInt::get(In->getType(), 1);
8061           In = BinaryOperator::CreateXor(In, One, "tmp");
8062           InsertNewInstBefore(cast<Instruction>(In), CI);
8063         }
8064           
8065         if (CI.getType() == In->getType())
8066           return ReplaceInstUsesWith(CI, In);
8067         else
8068           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8069       }
8070     }
8071   }
8072
8073   return 0;
8074 }
8075
8076 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8077   // If one of the common conversion will work ..
8078   if (Instruction *Result = commonIntCastTransforms(CI))
8079     return Result;
8080
8081   Value *Src = CI.getOperand(0);
8082
8083   // If this is a cast of a cast
8084   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8085     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8086     // types and if the sizes are just right we can convert this into a logical
8087     // 'and' which will be much cheaper than the pair of casts.
8088     if (isa<TruncInst>(CSrc)) {
8089       // Get the sizes of the types involved
8090       Value *A = CSrc->getOperand(0);
8091       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8092       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8093       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8094       // If we're actually extending zero bits and the trunc is a no-op
8095       if (MidSize < DstSize && SrcSize == DstSize) {
8096         // Replace both of the casts with an And of the type mask.
8097         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8098         Constant *AndConst = ConstantInt::get(AndValue);
8099         Instruction *And = 
8100           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8101         // Unfortunately, if the type changed, we need to cast it back.
8102         if (And->getType() != CI.getType()) {
8103           And->setName(CSrc->getName()+".mask");
8104           InsertNewInstBefore(And, CI);
8105           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8106         }
8107         return And;
8108       }
8109     }
8110   }
8111
8112   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8113     return transformZExtICmp(ICI, CI);
8114
8115   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8116   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8117     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8118     // of the (zext icmp) will be transformed.
8119     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8120     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8121     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8122         (transformZExtICmp(LHS, CI, false) ||
8123          transformZExtICmp(RHS, CI, false))) {
8124       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8125       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8126       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8127     }
8128   }
8129
8130   return 0;
8131 }
8132
8133 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8134   if (Instruction *I = commonIntCastTransforms(CI))
8135     return I;
8136   
8137   Value *Src = CI.getOperand(0);
8138   
8139   // Canonicalize sign-extend from i1 to a select.
8140   if (Src->getType() == Type::Int1Ty)
8141     return SelectInst::Create(Src,
8142                               ConstantInt::getAllOnesValue(CI.getType()),
8143                               Constant::getNullValue(CI.getType()));
8144
8145   // See if the value being truncated is already sign extended.  If so, just
8146   // eliminate the trunc/sext pair.
8147   if (getOpcode(Src) == Instruction::Trunc) {
8148     Value *Op = cast<User>(Src)->getOperand(0);
8149     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8150     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8151     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8152     unsigned NumSignBits = ComputeNumSignBits(Op);
8153
8154     if (OpBits == DestBits) {
8155       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8156       // bits, it is already ready.
8157       if (NumSignBits > DestBits-MidBits)
8158         return ReplaceInstUsesWith(CI, Op);
8159     } else if (OpBits < DestBits) {
8160       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8161       // bits, just sext from i32.
8162       if (NumSignBits > OpBits-MidBits)
8163         return new SExtInst(Op, CI.getType(), "tmp");
8164     } else {
8165       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8166       // bits, just truncate to i32.
8167       if (NumSignBits > OpBits-MidBits)
8168         return new TruncInst(Op, CI.getType(), "tmp");
8169     }
8170   }
8171
8172   // If the input is a shl/ashr pair of a same constant, then this is a sign
8173   // extension from a smaller value.  If we could trust arbitrary bitwidth
8174   // integers, we could turn this into a truncate to the smaller bit and then
8175   // use a sext for the whole extension.  Since we don't, look deeper and check
8176   // for a truncate.  If the source and dest are the same type, eliminate the
8177   // trunc and extend and just do shifts.  For example, turn:
8178   //   %a = trunc i32 %i to i8
8179   //   %b = shl i8 %a, 6
8180   //   %c = ashr i8 %b, 6
8181   //   %d = sext i8 %c to i32
8182   // into:
8183   //   %a = shl i32 %i, 30
8184   //   %d = ashr i32 %a, 30
8185   Value *A = 0;
8186   ConstantInt *BA = 0, *CA = 0;
8187   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8188                         m_ConstantInt(CA))) &&
8189       BA == CA && isa<TruncInst>(A)) {
8190     Value *I = cast<TruncInst>(A)->getOperand(0);
8191     if (I->getType() == CI.getType()) {
8192       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8193       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8194       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8195       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8196       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8197                                                         CI.getName()), CI);
8198       return BinaryOperator::CreateAShr(I, ShAmtV);
8199     }
8200   }
8201   
8202   return 0;
8203 }
8204
8205 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8206 /// in the specified FP type without changing its value.
8207 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8208   bool losesInfo;
8209   APFloat F = CFP->getValueAPF();
8210   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8211   if (!losesInfo)
8212     return ConstantFP::get(F);
8213   return 0;
8214 }
8215
8216 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8217 /// through it until we get the source value.
8218 static Value *LookThroughFPExtensions(Value *V) {
8219   if (Instruction *I = dyn_cast<Instruction>(V))
8220     if (I->getOpcode() == Instruction::FPExt)
8221       return LookThroughFPExtensions(I->getOperand(0));
8222   
8223   // If this value is a constant, return the constant in the smallest FP type
8224   // that can accurately represent it.  This allows us to turn
8225   // (float)((double)X+2.0) into x+2.0f.
8226   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8227     if (CFP->getType() == Type::PPC_FP128Ty)
8228       return V;  // No constant folding of this.
8229     // See if the value can be truncated to float and then reextended.
8230     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8231       return V;
8232     if (CFP->getType() == Type::DoubleTy)
8233       return V;  // Won't shrink.
8234     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8235       return V;
8236     // Don't try to shrink to various long double types.
8237   }
8238   
8239   return V;
8240 }
8241
8242 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8243   if (Instruction *I = commonCastTransforms(CI))
8244     return I;
8245   
8246   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8247   // smaller than the destination type, we can eliminate the truncate by doing
8248   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8249   // many builtins (sqrt, etc).
8250   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8251   if (OpI && OpI->hasOneUse()) {
8252     switch (OpI->getOpcode()) {
8253     default: break;
8254     case Instruction::Add:
8255     case Instruction::Sub:
8256     case Instruction::Mul:
8257     case Instruction::FDiv:
8258     case Instruction::FRem:
8259       const Type *SrcTy = OpI->getType();
8260       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8261       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8262       if (LHSTrunc->getType() != SrcTy && 
8263           RHSTrunc->getType() != SrcTy) {
8264         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8265         // If the source types were both smaller than the destination type of
8266         // the cast, do this xform.
8267         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8268             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8269           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8270                                       CI.getType(), CI);
8271           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8272                                       CI.getType(), CI);
8273           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8274         }
8275       }
8276       break;  
8277     }
8278   }
8279   return 0;
8280 }
8281
8282 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8283   return commonCastTransforms(CI);
8284 }
8285
8286 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8287   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8288   if (OpI == 0)
8289     return commonCastTransforms(FI);
8290
8291   // fptoui(uitofp(X)) --> X
8292   // fptoui(sitofp(X)) --> X
8293   // This is safe if the intermediate type has enough bits in its mantissa to
8294   // accurately represent all values of X.  For example, do not do this with
8295   // i64->float->i64.  This is also safe for sitofp case, because any negative
8296   // 'X' value would cause an undefined result for the fptoui. 
8297   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8298       OpI->getOperand(0)->getType() == FI.getType() &&
8299       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8300                     OpI->getType()->getFPMantissaWidth())
8301     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8302
8303   return commonCastTransforms(FI);
8304 }
8305
8306 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8307   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8308   if (OpI == 0)
8309     return commonCastTransforms(FI);
8310   
8311   // fptosi(sitofp(X)) --> X
8312   // fptosi(uitofp(X)) --> X
8313   // This is safe if the intermediate type has enough bits in its mantissa to
8314   // accurately represent all values of X.  For example, do not do this with
8315   // i64->float->i64.  This is also safe for sitofp case, because any negative
8316   // 'X' value would cause an undefined result for the fptoui. 
8317   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8318       OpI->getOperand(0)->getType() == FI.getType() &&
8319       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8320                     OpI->getType()->getFPMantissaWidth())
8321     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8322   
8323   return commonCastTransforms(FI);
8324 }
8325
8326 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8327   return commonCastTransforms(CI);
8328 }
8329
8330 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8331   return commonCastTransforms(CI);
8332 }
8333
8334 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8335   return commonPointerCastTransforms(CI);
8336 }
8337
8338 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8339   if (Instruction *I = commonCastTransforms(CI))
8340     return I;
8341   
8342   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8343   if (!DestPointee->isSized()) return 0;
8344
8345   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8346   ConstantInt *Cst;
8347   Value *X;
8348   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8349                                     m_ConstantInt(Cst)))) {
8350     // If the source and destination operands have the same type, see if this
8351     // is a single-index GEP.
8352     if (X->getType() == CI.getType()) {
8353       // Get the size of the pointee type.
8354       uint64_t Size = TD->getABITypeSize(DestPointee);
8355
8356       // Convert the constant to intptr type.
8357       APInt Offset = Cst->getValue();
8358       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8359
8360       // If Offset is evenly divisible by Size, we can do this xform.
8361       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8362         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8363         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8364       }
8365     }
8366     // TODO: Could handle other cases, e.g. where add is indexing into field of
8367     // struct etc.
8368   } else if (CI.getOperand(0)->hasOneUse() &&
8369              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8370     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8371     // "inttoptr+GEP" instead of "add+intptr".
8372     
8373     // Get the size of the pointee type.
8374     uint64_t Size = TD->getABITypeSize(DestPointee);
8375     
8376     // Convert the constant to intptr type.
8377     APInt Offset = Cst->getValue();
8378     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8379     
8380     // If Offset is evenly divisible by Size, we can do this xform.
8381     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8382       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8383       
8384       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8385                                                             "tmp"), CI);
8386       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8387     }
8388   }
8389   return 0;
8390 }
8391
8392 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8393   // If the operands are integer typed then apply the integer transforms,
8394   // otherwise just apply the common ones.
8395   Value *Src = CI.getOperand(0);
8396   const Type *SrcTy = Src->getType();
8397   const Type *DestTy = CI.getType();
8398
8399   if (SrcTy->isInteger() && DestTy->isInteger()) {
8400     if (Instruction *Result = commonIntCastTransforms(CI))
8401       return Result;
8402   } else if (isa<PointerType>(SrcTy)) {
8403     if (Instruction *I = commonPointerCastTransforms(CI))
8404       return I;
8405   } else {
8406     if (Instruction *Result = commonCastTransforms(CI))
8407       return Result;
8408   }
8409
8410
8411   // Get rid of casts from one type to the same type. These are useless and can
8412   // be replaced by the operand.
8413   if (DestTy == Src->getType())
8414     return ReplaceInstUsesWith(CI, Src);
8415
8416   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8417     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8418     const Type *DstElTy = DstPTy->getElementType();
8419     const Type *SrcElTy = SrcPTy->getElementType();
8420     
8421     // If the address spaces don't match, don't eliminate the bitcast, which is
8422     // required for changing types.
8423     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8424       return 0;
8425     
8426     // If we are casting a malloc or alloca to a pointer to a type of the same
8427     // size, rewrite the allocation instruction to allocate the "right" type.
8428     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8429       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8430         return V;
8431     
8432     // If the source and destination are pointers, and this cast is equivalent
8433     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8434     // This can enhance SROA and other transforms that want type-safe pointers.
8435     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8436     unsigned NumZeros = 0;
8437     while (SrcElTy != DstElTy && 
8438            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8439            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8440       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8441       ++NumZeros;
8442     }
8443
8444     // If we found a path from the src to dest, create the getelementptr now.
8445     if (SrcElTy == DstElTy) {
8446       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8447       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8448                                        ((Instruction*) NULL));
8449     }
8450   }
8451
8452   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8453     if (SVI->hasOneUse()) {
8454       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8455       // a bitconvert to a vector with the same # elts.
8456       if (isa<VectorType>(DestTy) && 
8457           cast<VectorType>(DestTy)->getNumElements() ==
8458                 SVI->getType()->getNumElements() &&
8459           SVI->getType()->getNumElements() ==
8460             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8461         CastInst *Tmp;
8462         // If either of the operands is a cast from CI.getType(), then
8463         // evaluating the shuffle in the casted destination's type will allow
8464         // us to eliminate at least one cast.
8465         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8466              Tmp->getOperand(0)->getType() == DestTy) ||
8467             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8468              Tmp->getOperand(0)->getType() == DestTy)) {
8469           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8470                                                SVI->getOperand(0), DestTy, &CI);
8471           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8472                                                SVI->getOperand(1), DestTy, &CI);
8473           // Return a new shuffle vector.  Use the same element ID's, as we
8474           // know the vector types match #elts.
8475           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8476         }
8477       }
8478     }
8479   }
8480   return 0;
8481 }
8482
8483 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8484 ///   %C = or %A, %B
8485 ///   %D = select %cond, %C, %A
8486 /// into:
8487 ///   %C = select %cond, %B, 0
8488 ///   %D = or %A, %C
8489 ///
8490 /// Assuming that the specified instruction is an operand to the select, return
8491 /// a bitmask indicating which operands of this instruction are foldable if they
8492 /// equal the other incoming value of the select.
8493 ///
8494 static unsigned GetSelectFoldableOperands(Instruction *I) {
8495   switch (I->getOpcode()) {
8496   case Instruction::Add:
8497   case Instruction::Mul:
8498   case Instruction::And:
8499   case Instruction::Or:
8500   case Instruction::Xor:
8501     return 3;              // Can fold through either operand.
8502   case Instruction::Sub:   // Can only fold on the amount subtracted.
8503   case Instruction::Shl:   // Can only fold on the shift amount.
8504   case Instruction::LShr:
8505   case Instruction::AShr:
8506     return 1;
8507   default:
8508     return 0;              // Cannot fold
8509   }
8510 }
8511
8512 /// GetSelectFoldableConstant - For the same transformation as the previous
8513 /// function, return the identity constant that goes into the select.
8514 static Constant *GetSelectFoldableConstant(Instruction *I) {
8515   switch (I->getOpcode()) {
8516   default: assert(0 && "This cannot happen!"); abort();
8517   case Instruction::Add:
8518   case Instruction::Sub:
8519   case Instruction::Or:
8520   case Instruction::Xor:
8521   case Instruction::Shl:
8522   case Instruction::LShr:
8523   case Instruction::AShr:
8524     return Constant::getNullValue(I->getType());
8525   case Instruction::And:
8526     return Constant::getAllOnesValue(I->getType());
8527   case Instruction::Mul:
8528     return ConstantInt::get(I->getType(), 1);
8529   }
8530 }
8531
8532 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8533 /// have the same opcode and only one use each.  Try to simplify this.
8534 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8535                                           Instruction *FI) {
8536   if (TI->getNumOperands() == 1) {
8537     // If this is a non-volatile load or a cast from the same type,
8538     // merge.
8539     if (TI->isCast()) {
8540       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8541         return 0;
8542     } else {
8543       return 0;  // unknown unary op.
8544     }
8545
8546     // Fold this by inserting a select from the input values.
8547     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8548                                            FI->getOperand(0), SI.getName()+".v");
8549     InsertNewInstBefore(NewSI, SI);
8550     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8551                             TI->getType());
8552   }
8553
8554   // Only handle binary operators here.
8555   if (!isa<BinaryOperator>(TI))
8556     return 0;
8557
8558   // Figure out if the operations have any operands in common.
8559   Value *MatchOp, *OtherOpT, *OtherOpF;
8560   bool MatchIsOpZero;
8561   if (TI->getOperand(0) == FI->getOperand(0)) {
8562     MatchOp  = TI->getOperand(0);
8563     OtherOpT = TI->getOperand(1);
8564     OtherOpF = FI->getOperand(1);
8565     MatchIsOpZero = true;
8566   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8567     MatchOp  = TI->getOperand(1);
8568     OtherOpT = TI->getOperand(0);
8569     OtherOpF = FI->getOperand(0);
8570     MatchIsOpZero = false;
8571   } else if (!TI->isCommutative()) {
8572     return 0;
8573   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8574     MatchOp  = TI->getOperand(0);
8575     OtherOpT = TI->getOperand(1);
8576     OtherOpF = FI->getOperand(0);
8577     MatchIsOpZero = true;
8578   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8579     MatchOp  = TI->getOperand(1);
8580     OtherOpT = TI->getOperand(0);
8581     OtherOpF = FI->getOperand(1);
8582     MatchIsOpZero = true;
8583   } else {
8584     return 0;
8585   }
8586
8587   // If we reach here, they do have operations in common.
8588   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8589                                          OtherOpF, SI.getName()+".v");
8590   InsertNewInstBefore(NewSI, SI);
8591
8592   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8593     if (MatchIsOpZero)
8594       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8595     else
8596       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8597   }
8598   assert(0 && "Shouldn't get here");
8599   return 0;
8600 }
8601
8602 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8603 /// ICmpInst as its first operand.
8604 ///
8605 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8606                                                    ICmpInst *ICI) {
8607   bool Changed = false;
8608   ICmpInst::Predicate Pred = ICI->getPredicate();
8609   Value *CmpLHS = ICI->getOperand(0);
8610   Value *CmpRHS = ICI->getOperand(1);
8611   Value *TrueVal = SI.getTrueValue();
8612   Value *FalseVal = SI.getFalseValue();
8613
8614   // Check cases where the comparison is with a constant that
8615   // can be adjusted to fit the min/max idiom. We may edit ICI in
8616   // place here, so make sure the select is the only user.
8617   if (ICI->hasOneUse())
8618     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8619       switch (Pred) {
8620       default: break;
8621       case ICmpInst::ICMP_ULT:
8622       case ICmpInst::ICMP_SLT: {
8623         // X < MIN ? T : F  -->  F
8624         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8625           return ReplaceInstUsesWith(SI, FalseVal);
8626         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8627         Constant *AdjustedRHS = SubOne(CI);
8628         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8629             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8630           Pred = ICmpInst::getSwappedPredicate(Pred);
8631           CmpRHS = AdjustedRHS;
8632           std::swap(FalseVal, TrueVal);
8633           ICI->setPredicate(Pred);
8634           ICI->setOperand(1, CmpRHS);
8635           SI.setOperand(1, TrueVal);
8636           SI.setOperand(2, FalseVal);
8637           Changed = true;
8638         }
8639         break;
8640       }
8641       case ICmpInst::ICMP_UGT:
8642       case ICmpInst::ICMP_SGT: {
8643         // X > MAX ? T : F  -->  F
8644         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8645           return ReplaceInstUsesWith(SI, FalseVal);
8646         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8647         Constant *AdjustedRHS = AddOne(CI);
8648         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8649             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8650           Pred = ICmpInst::getSwappedPredicate(Pred);
8651           CmpRHS = AdjustedRHS;
8652           std::swap(FalseVal, TrueVal);
8653           ICI->setPredicate(Pred);
8654           ICI->setOperand(1, CmpRHS);
8655           SI.setOperand(1, TrueVal);
8656           SI.setOperand(2, FalseVal);
8657           Changed = true;
8658         }
8659         break;
8660       }
8661       }
8662
8663       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8664       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8665       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8666       if (match(TrueVal, m_ConstantInt(-1)) &&
8667           match(FalseVal, m_ConstantInt(0)))
8668         Pred = ICI->getPredicate();
8669       else if (match(TrueVal, m_ConstantInt(0)) &&
8670                match(FalseVal, m_ConstantInt(-1)))
8671         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8672       
8673       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8674         // If we are just checking for a icmp eq of a single bit and zext'ing it
8675         // to an integer, then shift the bit to the appropriate place and then
8676         // cast to integer to avoid the comparison.
8677         const APInt &Op1CV = CI->getValue();
8678     
8679         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8680         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8681         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8682             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8683           Value *In = ICI->getOperand(0);
8684           Value *Sh = ConstantInt::get(In->getType(),
8685                                        In->getType()->getPrimitiveSizeInBits()-1);
8686           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8687                                                           In->getName()+".lobit"),
8688                                    *ICI);
8689           if (In->getType() != SI.getType())
8690             In = CastInst::CreateIntegerCast(In, SI.getType(),
8691                                              true/*SExt*/, "tmp", ICI);
8692     
8693           if (Pred == ICmpInst::ICMP_SGT)
8694             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8695                                        In->getName()+".not"), *ICI);
8696     
8697           return ReplaceInstUsesWith(SI, In);
8698         }
8699       }
8700     }
8701
8702   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8703     // Transform (X == Y) ? X : Y  -> Y
8704     if (Pred == ICmpInst::ICMP_EQ)
8705       return ReplaceInstUsesWith(SI, FalseVal);
8706     // Transform (X != Y) ? X : Y  -> X
8707     if (Pred == ICmpInst::ICMP_NE)
8708       return ReplaceInstUsesWith(SI, TrueVal);
8709     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8710
8711   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8712     // Transform (X == Y) ? Y : X  -> X
8713     if (Pred == ICmpInst::ICMP_EQ)
8714       return ReplaceInstUsesWith(SI, FalseVal);
8715     // Transform (X != Y) ? Y : X  -> Y
8716     if (Pred == ICmpInst::ICMP_NE)
8717       return ReplaceInstUsesWith(SI, TrueVal);
8718     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8719   }
8720
8721   /// NOTE: if we wanted to, this is where to detect integer ABS
8722
8723   return Changed ? &SI : 0;
8724 }
8725
8726 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8727   Value *CondVal = SI.getCondition();
8728   Value *TrueVal = SI.getTrueValue();
8729   Value *FalseVal = SI.getFalseValue();
8730
8731   // select true, X, Y  -> X
8732   // select false, X, Y -> Y
8733   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8734     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8735
8736   // select C, X, X -> X
8737   if (TrueVal == FalseVal)
8738     return ReplaceInstUsesWith(SI, TrueVal);
8739
8740   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8741     return ReplaceInstUsesWith(SI, FalseVal);
8742   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8743     return ReplaceInstUsesWith(SI, TrueVal);
8744   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8745     if (isa<Constant>(TrueVal))
8746       return ReplaceInstUsesWith(SI, TrueVal);
8747     else
8748       return ReplaceInstUsesWith(SI, FalseVal);
8749   }
8750
8751   if (SI.getType() == Type::Int1Ty) {
8752     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8753       if (C->getZExtValue()) {
8754         // Change: A = select B, true, C --> A = or B, C
8755         return BinaryOperator::CreateOr(CondVal, FalseVal);
8756       } else {
8757         // Change: A = select B, false, C --> A = and !B, C
8758         Value *NotCond =
8759           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8760                                              "not."+CondVal->getName()), SI);
8761         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8762       }
8763     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8764       if (C->getZExtValue() == false) {
8765         // Change: A = select B, C, false --> A = and B, C
8766         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8767       } else {
8768         // Change: A = select B, C, true --> A = or !B, C
8769         Value *NotCond =
8770           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8771                                              "not."+CondVal->getName()), SI);
8772         return BinaryOperator::CreateOr(NotCond, TrueVal);
8773       }
8774     }
8775     
8776     // select a, b, a  -> a&b
8777     // select a, a, b  -> a|b
8778     if (CondVal == TrueVal)
8779       return BinaryOperator::CreateOr(CondVal, FalseVal);
8780     else if (CondVal == FalseVal)
8781       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8782   }
8783
8784   // Selecting between two integer constants?
8785   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8786     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8787       // select C, 1, 0 -> zext C to int
8788       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8789         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8790       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8791         // select C, 0, 1 -> zext !C to int
8792         Value *NotCond =
8793           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8794                                                "not."+CondVal->getName()), SI);
8795         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8796       }
8797       
8798       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8799
8800       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8801
8802         // (x <s 0) ? -1 : 0 -> ashr x, 31
8803         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8804           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8805             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8806               // The comparison constant and the result are not neccessarily the
8807               // same width. Make an all-ones value by inserting a AShr.
8808               Value *X = IC->getOperand(0);
8809               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8810               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8811               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8812                                                         ShAmt, "ones");
8813               InsertNewInstBefore(SRA, SI);
8814               
8815               // Finally, convert to the type of the select RHS.  We figure out
8816               // if this requires a SExt, Trunc or BitCast based on the sizes.
8817               Instruction::CastOps opc = Instruction::BitCast;
8818               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8819               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8820               if (SRASize < SISize)
8821                 opc = Instruction::SExt;
8822               else if (SRASize > SISize)
8823                 opc = Instruction::Trunc;
8824               return CastInst::Create(opc, SRA, SI.getType());
8825             }
8826           }
8827
8828
8829         // If one of the constants is zero (we know they can't both be) and we
8830         // have an icmp instruction with zero, and we have an 'and' with the
8831         // non-constant value, eliminate this whole mess.  This corresponds to
8832         // cases like this: ((X & 27) ? 27 : 0)
8833         if (TrueValC->isZero() || FalseValC->isZero())
8834           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8835               cast<Constant>(IC->getOperand(1))->isNullValue())
8836             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8837               if (ICA->getOpcode() == Instruction::And &&
8838                   isa<ConstantInt>(ICA->getOperand(1)) &&
8839                   (ICA->getOperand(1) == TrueValC ||
8840                    ICA->getOperand(1) == FalseValC) &&
8841                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8842                 // Okay, now we know that everything is set up, we just don't
8843                 // know whether we have a icmp_ne or icmp_eq and whether the 
8844                 // true or false val is the zero.
8845                 bool ShouldNotVal = !TrueValC->isZero();
8846                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8847                 Value *V = ICA;
8848                 if (ShouldNotVal)
8849                   V = InsertNewInstBefore(BinaryOperator::Create(
8850                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8851                 return ReplaceInstUsesWith(SI, V);
8852               }
8853       }
8854     }
8855
8856   // See if we are selecting two values based on a comparison of the two values.
8857   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8858     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8859       // Transform (X == Y) ? X : Y  -> Y
8860       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8861         // This is not safe in general for floating point:  
8862         // consider X== -0, Y== +0.
8863         // It becomes safe if either operand is a nonzero constant.
8864         ConstantFP *CFPt, *CFPf;
8865         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8866               !CFPt->getValueAPF().isZero()) ||
8867             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8868              !CFPf->getValueAPF().isZero()))
8869         return ReplaceInstUsesWith(SI, FalseVal);
8870       }
8871       // Transform (X != Y) ? X : Y  -> X
8872       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8873         return ReplaceInstUsesWith(SI, TrueVal);
8874       // NOTE: if we wanted to, this is where to detect MIN/MAX
8875
8876     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8877       // Transform (X == Y) ? Y : X  -> X
8878       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8879         // This is not safe in general for floating point:  
8880         // consider X== -0, Y== +0.
8881         // It becomes safe if either operand is a nonzero constant.
8882         ConstantFP *CFPt, *CFPf;
8883         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8884               !CFPt->getValueAPF().isZero()) ||
8885             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8886              !CFPf->getValueAPF().isZero()))
8887           return ReplaceInstUsesWith(SI, FalseVal);
8888       }
8889       // Transform (X != Y) ? Y : X  -> Y
8890       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8891         return ReplaceInstUsesWith(SI, TrueVal);
8892       // NOTE: if we wanted to, this is where to detect MIN/MAX
8893     }
8894     // NOTE: if we wanted to, this is where to detect ABS
8895   }
8896
8897   // See if we are selecting two values based on a comparison of the two values.
8898   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8899     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8900       return Result;
8901
8902   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8903     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8904       if (TI->hasOneUse() && FI->hasOneUse()) {
8905         Instruction *AddOp = 0, *SubOp = 0;
8906
8907         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8908         if (TI->getOpcode() == FI->getOpcode())
8909           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8910             return IV;
8911
8912         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8913         // even legal for FP.
8914         if (TI->getOpcode() == Instruction::Sub &&
8915             FI->getOpcode() == Instruction::Add) {
8916           AddOp = FI; SubOp = TI;
8917         } else if (FI->getOpcode() == Instruction::Sub &&
8918                    TI->getOpcode() == Instruction::Add) {
8919           AddOp = TI; SubOp = FI;
8920         }
8921
8922         if (AddOp) {
8923           Value *OtherAddOp = 0;
8924           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8925             OtherAddOp = AddOp->getOperand(1);
8926           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8927             OtherAddOp = AddOp->getOperand(0);
8928           }
8929
8930           if (OtherAddOp) {
8931             // So at this point we know we have (Y -> OtherAddOp):
8932             //        select C, (add X, Y), (sub X, Z)
8933             Value *NegVal;  // Compute -Z
8934             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8935               NegVal = ConstantExpr::getNeg(C);
8936             } else {
8937               NegVal = InsertNewInstBefore(
8938                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8939             }
8940
8941             Value *NewTrueOp = OtherAddOp;
8942             Value *NewFalseOp = NegVal;
8943             if (AddOp != TI)
8944               std::swap(NewTrueOp, NewFalseOp);
8945             Instruction *NewSel =
8946               SelectInst::Create(CondVal, NewTrueOp,
8947                                  NewFalseOp, SI.getName() + ".p");
8948
8949             NewSel = InsertNewInstBefore(NewSel, SI);
8950             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8951           }
8952         }
8953       }
8954
8955   // See if we can fold the select into one of our operands.
8956   if (SI.getType()->isInteger()) {
8957     // See the comment above GetSelectFoldableOperands for a description of the
8958     // transformation we are doing here.
8959     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8960       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8961           !isa<Constant>(FalseVal))
8962         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8963           unsigned OpToFold = 0;
8964           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8965             OpToFold = 1;
8966           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8967             OpToFold = 2;
8968           }
8969
8970           if (OpToFold) {
8971             Constant *C = GetSelectFoldableConstant(TVI);
8972             Instruction *NewSel =
8973               SelectInst::Create(SI.getCondition(),
8974                                  TVI->getOperand(2-OpToFold), C);
8975             InsertNewInstBefore(NewSel, SI);
8976             NewSel->takeName(TVI);
8977             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8978               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8979             else {
8980               assert(0 && "Unknown instruction!!");
8981             }
8982           }
8983         }
8984
8985     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8986       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8987           !isa<Constant>(TrueVal))
8988         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8989           unsigned OpToFold = 0;
8990           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8991             OpToFold = 1;
8992           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8993             OpToFold = 2;
8994           }
8995
8996           if (OpToFold) {
8997             Constant *C = GetSelectFoldableConstant(FVI);
8998             Instruction *NewSel =
8999               SelectInst::Create(SI.getCondition(), C,
9000                                  FVI->getOperand(2-OpToFold));
9001             InsertNewInstBefore(NewSel, SI);
9002             NewSel->takeName(FVI);
9003             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9004               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9005             else
9006               assert(0 && "Unknown instruction!!");
9007           }
9008         }
9009   }
9010
9011   if (BinaryOperator::isNot(CondVal)) {
9012     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9013     SI.setOperand(1, FalseVal);
9014     SI.setOperand(2, TrueVal);
9015     return &SI;
9016   }
9017
9018   return 0;
9019 }
9020
9021 /// EnforceKnownAlignment - If the specified pointer points to an object that
9022 /// we control, modify the object's alignment to PrefAlign. This isn't
9023 /// often possible though. If alignment is important, a more reliable approach
9024 /// is to simply align all global variables and allocation instructions to
9025 /// their preferred alignment from the beginning.
9026 ///
9027 static unsigned EnforceKnownAlignment(Value *V,
9028                                       unsigned Align, unsigned PrefAlign) {
9029
9030   User *U = dyn_cast<User>(V);
9031   if (!U) return Align;
9032
9033   switch (getOpcode(U)) {
9034   default: break;
9035   case Instruction::BitCast:
9036     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9037   case Instruction::GetElementPtr: {
9038     // If all indexes are zero, it is just the alignment of the base pointer.
9039     bool AllZeroOperands = true;
9040     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9041       if (!isa<Constant>(*i) ||
9042           !cast<Constant>(*i)->isNullValue()) {
9043         AllZeroOperands = false;
9044         break;
9045       }
9046
9047     if (AllZeroOperands) {
9048       // Treat this like a bitcast.
9049       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9050     }
9051     break;
9052   }
9053   }
9054
9055   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9056     // If there is a large requested alignment and we can, bump up the alignment
9057     // of the global.
9058     if (!GV->isDeclaration()) {
9059       GV->setAlignment(PrefAlign);
9060       Align = PrefAlign;
9061     }
9062   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9063     // If there is a requested alignment and if this is an alloca, round up.  We
9064     // don't do this for malloc, because some systems can't respect the request.
9065     if (isa<AllocaInst>(AI)) {
9066       AI->setAlignment(PrefAlign);
9067       Align = PrefAlign;
9068     }
9069   }
9070
9071   return Align;
9072 }
9073
9074 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9075 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9076 /// and it is more than the alignment of the ultimate object, see if we can
9077 /// increase the alignment of the ultimate object, making this check succeed.
9078 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9079                                                   unsigned PrefAlign) {
9080   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9081                       sizeof(PrefAlign) * CHAR_BIT;
9082   APInt Mask = APInt::getAllOnesValue(BitWidth);
9083   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9084   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9085   unsigned TrailZ = KnownZero.countTrailingOnes();
9086   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9087
9088   if (PrefAlign > Align)
9089     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9090   
9091     // We don't need to make any adjustment.
9092   return Align;
9093 }
9094
9095 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9096   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9097   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9098   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9099   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9100
9101   if (CopyAlign < MinAlign) {
9102     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9103     return MI;
9104   }
9105   
9106   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9107   // load/store.
9108   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9109   if (MemOpLength == 0) return 0;
9110   
9111   // Source and destination pointer types are always "i8*" for intrinsic.  See
9112   // if the size is something we can handle with a single primitive load/store.
9113   // A single load+store correctly handles overlapping memory in the memmove
9114   // case.
9115   unsigned Size = MemOpLength->getZExtValue();
9116   if (Size == 0) return MI;  // Delete this mem transfer.
9117   
9118   if (Size > 8 || (Size&(Size-1)))
9119     return 0;  // If not 1/2/4/8 bytes, exit.
9120   
9121   // Use an integer load+store unless we can find something better.
9122   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9123   
9124   // Memcpy forces the use of i8* for the source and destination.  That means
9125   // that if you're using memcpy to move one double around, you'll get a cast
9126   // from double* to i8*.  We'd much rather use a double load+store rather than
9127   // an i64 load+store, here because this improves the odds that the source or
9128   // dest address will be promotable.  See if we can find a better type than the
9129   // integer datatype.
9130   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9131     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9132     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9133       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9134       // down through these levels if so.
9135       while (!SrcETy->isSingleValueType()) {
9136         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9137           if (STy->getNumElements() == 1)
9138             SrcETy = STy->getElementType(0);
9139           else
9140             break;
9141         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9142           if (ATy->getNumElements() == 1)
9143             SrcETy = ATy->getElementType();
9144           else
9145             break;
9146         } else
9147           break;
9148       }
9149       
9150       if (SrcETy->isSingleValueType())
9151         NewPtrTy = PointerType::getUnqual(SrcETy);
9152     }
9153   }
9154   
9155   
9156   // If the memcpy/memmove provides better alignment info than we can
9157   // infer, use it.
9158   SrcAlign = std::max(SrcAlign, CopyAlign);
9159   DstAlign = std::max(DstAlign, CopyAlign);
9160   
9161   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9162   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9163   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9164   InsertNewInstBefore(L, *MI);
9165   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9166
9167   // Set the size of the copy to 0, it will be deleted on the next iteration.
9168   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9169   return MI;
9170 }
9171
9172 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9173   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9174   if (MI->getAlignment()->getZExtValue() < Alignment) {
9175     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9176     return MI;
9177   }
9178   
9179   // Extract the length and alignment and fill if they are constant.
9180   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9181   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9182   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9183     return 0;
9184   uint64_t Len = LenC->getZExtValue();
9185   Alignment = MI->getAlignment()->getZExtValue();
9186   
9187   // If the length is zero, this is a no-op
9188   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9189   
9190   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9191   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9192     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9193     
9194     Value *Dest = MI->getDest();
9195     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9196
9197     // Alignment 0 is identity for alignment 1 for memset, but not store.
9198     if (Alignment == 0) Alignment = 1;
9199     
9200     // Extract the fill value and store.
9201     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9202     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9203                                       Alignment), *MI);
9204     
9205     // Set the size of the copy to 0, it will be deleted on the next iteration.
9206     MI->setLength(Constant::getNullValue(LenC->getType()));
9207     return MI;
9208   }
9209
9210   return 0;
9211 }
9212
9213
9214 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9215 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9216 /// the heavy lifting.
9217 ///
9218 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9219   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9220   if (!II) return visitCallSite(&CI);
9221   
9222   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9223   // visitCallSite.
9224   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9225     bool Changed = false;
9226
9227     // memmove/cpy/set of zero bytes is a noop.
9228     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9229       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9230
9231       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9232         if (CI->getZExtValue() == 1) {
9233           // Replace the instruction with just byte operations.  We would
9234           // transform other cases to loads/stores, but we don't know if
9235           // alignment is sufficient.
9236         }
9237     }
9238
9239     // If we have a memmove and the source operation is a constant global,
9240     // then the source and dest pointers can't alias, so we can change this
9241     // into a call to memcpy.
9242     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9243       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9244         if (GVSrc->isConstant()) {
9245           Module *M = CI.getParent()->getParent()->getParent();
9246           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9247           const Type *Tys[1];
9248           Tys[0] = CI.getOperand(3)->getType();
9249           CI.setOperand(0, 
9250                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9251           Changed = true;
9252         }
9253
9254       // memmove(x,x,size) -> noop.
9255       if (MMI->getSource() == MMI->getDest())
9256         return EraseInstFromFunction(CI);
9257     }
9258
9259     // If we can determine a pointer alignment that is bigger than currently
9260     // set, update the alignment.
9261     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9262       if (Instruction *I = SimplifyMemTransfer(MI))
9263         return I;
9264     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9265       if (Instruction *I = SimplifyMemSet(MSI))
9266         return I;
9267     }
9268           
9269     if (Changed) return II;
9270   }
9271   
9272   switch (II->getIntrinsicID()) {
9273   default: break;
9274   case Intrinsic::bswap:
9275     // bswap(bswap(x)) -> x
9276     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9277       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9278         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9279     break;
9280   case Intrinsic::ppc_altivec_lvx:
9281   case Intrinsic::ppc_altivec_lvxl:
9282   case Intrinsic::x86_sse_loadu_ps:
9283   case Intrinsic::x86_sse2_loadu_pd:
9284   case Intrinsic::x86_sse2_loadu_dq:
9285     // Turn PPC lvx     -> load if the pointer is known aligned.
9286     // Turn X86 loadups -> load if the pointer is known aligned.
9287     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9288       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9289                                        PointerType::getUnqual(II->getType()),
9290                                        CI);
9291       return new LoadInst(Ptr);
9292     }
9293     break;
9294   case Intrinsic::ppc_altivec_stvx:
9295   case Intrinsic::ppc_altivec_stvxl:
9296     // Turn stvx -> store if the pointer is known aligned.
9297     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9298       const Type *OpPtrTy = 
9299         PointerType::getUnqual(II->getOperand(1)->getType());
9300       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9301       return new StoreInst(II->getOperand(1), Ptr);
9302     }
9303     break;
9304   case Intrinsic::x86_sse_storeu_ps:
9305   case Intrinsic::x86_sse2_storeu_pd:
9306   case Intrinsic::x86_sse2_storeu_dq:
9307     // Turn X86 storeu -> store if the pointer is known aligned.
9308     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9309       const Type *OpPtrTy = 
9310         PointerType::getUnqual(II->getOperand(2)->getType());
9311       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9312       return new StoreInst(II->getOperand(2), Ptr);
9313     }
9314     break;
9315     
9316   case Intrinsic::x86_sse_cvttss2si: {
9317     // These intrinsics only demands the 0th element of its input vector.  If
9318     // we can simplify the input based on that, do so now.
9319     uint64_t UndefElts;
9320     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9321                                               UndefElts)) {
9322       II->setOperand(1, V);
9323       return II;
9324     }
9325     break;
9326   }
9327     
9328   case Intrinsic::ppc_altivec_vperm:
9329     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9330     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9331       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9332       
9333       // Check that all of the elements are integer constants or undefs.
9334       bool AllEltsOk = true;
9335       for (unsigned i = 0; i != 16; ++i) {
9336         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9337             !isa<UndefValue>(Mask->getOperand(i))) {
9338           AllEltsOk = false;
9339           break;
9340         }
9341       }
9342       
9343       if (AllEltsOk) {
9344         // Cast the input vectors to byte vectors.
9345         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9346         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9347         Value *Result = UndefValue::get(Op0->getType());
9348         
9349         // Only extract each element once.
9350         Value *ExtractedElts[32];
9351         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9352         
9353         for (unsigned i = 0; i != 16; ++i) {
9354           if (isa<UndefValue>(Mask->getOperand(i)))
9355             continue;
9356           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9357           Idx &= 31;  // Match the hardware behavior.
9358           
9359           if (ExtractedElts[Idx] == 0) {
9360             Instruction *Elt = 
9361               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9362             InsertNewInstBefore(Elt, CI);
9363             ExtractedElts[Idx] = Elt;
9364           }
9365         
9366           // Insert this value into the result vector.
9367           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9368                                              i, "tmp");
9369           InsertNewInstBefore(cast<Instruction>(Result), CI);
9370         }
9371         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9372       }
9373     }
9374     break;
9375
9376   case Intrinsic::stackrestore: {
9377     // If the save is right next to the restore, remove the restore.  This can
9378     // happen when variable allocas are DCE'd.
9379     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9380       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9381         BasicBlock::iterator BI = SS;
9382         if (&*++BI == II)
9383           return EraseInstFromFunction(CI);
9384       }
9385     }
9386     
9387     // Scan down this block to see if there is another stack restore in the
9388     // same block without an intervening call/alloca.
9389     BasicBlock::iterator BI = II;
9390     TerminatorInst *TI = II->getParent()->getTerminator();
9391     bool CannotRemove = false;
9392     for (++BI; &*BI != TI; ++BI) {
9393       if (isa<AllocaInst>(BI)) {
9394         CannotRemove = true;
9395         break;
9396       }
9397       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9398         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9399           // If there is a stackrestore below this one, remove this one.
9400           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9401             return EraseInstFromFunction(CI);
9402           // Otherwise, ignore the intrinsic.
9403         } else {
9404           // If we found a non-intrinsic call, we can't remove the stack
9405           // restore.
9406           CannotRemove = true;
9407           break;
9408         }
9409       }
9410     }
9411     
9412     // If the stack restore is in a return/unwind block and if there are no
9413     // allocas or calls between the restore and the return, nuke the restore.
9414     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9415       return EraseInstFromFunction(CI);
9416     break;
9417   }
9418   }
9419
9420   return visitCallSite(II);
9421 }
9422
9423 // InvokeInst simplification
9424 //
9425 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9426   return visitCallSite(&II);
9427 }
9428
9429 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9430 /// passed through the varargs area, we can eliminate the use of the cast.
9431 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9432                                          const CastInst * const CI,
9433                                          const TargetData * const TD,
9434                                          const int ix) {
9435   if (!CI->isLosslessCast())
9436     return false;
9437
9438   // The size of ByVal arguments is derived from the type, so we
9439   // can't change to a type with a different size.  If the size were
9440   // passed explicitly we could avoid this check.
9441   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9442     return true;
9443
9444   const Type* SrcTy = 
9445             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9446   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9447   if (!SrcTy->isSized() || !DstTy->isSized())
9448     return false;
9449   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9450     return false;
9451   return true;
9452 }
9453
9454 // visitCallSite - Improvements for call and invoke instructions.
9455 //
9456 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9457   bool Changed = false;
9458
9459   // If the callee is a constexpr cast of a function, attempt to move the cast
9460   // to the arguments of the call/invoke.
9461   if (transformConstExprCastCall(CS)) return 0;
9462
9463   Value *Callee = CS.getCalledValue();
9464
9465   if (Function *CalleeF = dyn_cast<Function>(Callee))
9466     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9467       Instruction *OldCall = CS.getInstruction();
9468       // If the call and callee calling conventions don't match, this call must
9469       // be unreachable, as the call is undefined.
9470       new StoreInst(ConstantInt::getTrue(),
9471                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9472                                     OldCall);
9473       if (!OldCall->use_empty())
9474         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9475       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9476         return EraseInstFromFunction(*OldCall);
9477       return 0;
9478     }
9479
9480   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9481     // This instruction is not reachable, just remove it.  We insert a store to
9482     // undef so that we know that this code is not reachable, despite the fact
9483     // that we can't modify the CFG here.
9484     new StoreInst(ConstantInt::getTrue(),
9485                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9486                   CS.getInstruction());
9487
9488     if (!CS.getInstruction()->use_empty())
9489       CS.getInstruction()->
9490         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9491
9492     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9493       // Don't break the CFG, insert a dummy cond branch.
9494       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9495                          ConstantInt::getTrue(), II);
9496     }
9497     return EraseInstFromFunction(*CS.getInstruction());
9498   }
9499
9500   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9501     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9502       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9503         return transformCallThroughTrampoline(CS);
9504
9505   const PointerType *PTy = cast<PointerType>(Callee->getType());
9506   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9507   if (FTy->isVarArg()) {
9508     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9509     // See if we can optimize any arguments passed through the varargs area of
9510     // the call.
9511     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9512            E = CS.arg_end(); I != E; ++I, ++ix) {
9513       CastInst *CI = dyn_cast<CastInst>(*I);
9514       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9515         *I = CI->getOperand(0);
9516         Changed = true;
9517       }
9518     }
9519   }
9520
9521   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9522     // Inline asm calls cannot throw - mark them 'nounwind'.
9523     CS.setDoesNotThrow();
9524     Changed = true;
9525   }
9526
9527   return Changed ? CS.getInstruction() : 0;
9528 }
9529
9530 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9531 // attempt to move the cast to the arguments of the call/invoke.
9532 //
9533 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9534   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9535   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9536   if (CE->getOpcode() != Instruction::BitCast || 
9537       !isa<Function>(CE->getOperand(0)))
9538     return false;
9539   Function *Callee = cast<Function>(CE->getOperand(0));
9540   Instruction *Caller = CS.getInstruction();
9541   const AttrListPtr &CallerPAL = CS.getAttributes();
9542
9543   // Okay, this is a cast from a function to a different type.  Unless doing so
9544   // would cause a type conversion of one of our arguments, change this call to
9545   // be a direct call with arguments casted to the appropriate types.
9546   //
9547   const FunctionType *FT = Callee->getFunctionType();
9548   const Type *OldRetTy = Caller->getType();
9549   const Type *NewRetTy = FT->getReturnType();
9550
9551   if (isa<StructType>(NewRetTy))
9552     return false; // TODO: Handle multiple return values.
9553
9554   // Check to see if we are changing the return type...
9555   if (OldRetTy != NewRetTy) {
9556     if (Callee->isDeclaration() &&
9557         // Conversion is ok if changing from one pointer type to another or from
9558         // a pointer to an integer of the same size.
9559         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9560           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9561       return false;   // Cannot transform this return value.
9562
9563     if (!Caller->use_empty() &&
9564         // void -> non-void is handled specially
9565         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9566       return false;   // Cannot transform this return value.
9567
9568     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9569       Attributes RAttrs = CallerPAL.getRetAttributes();
9570       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9571         return false;   // Attribute not compatible with transformed value.
9572     }
9573
9574     // If the callsite is an invoke instruction, and the return value is used by
9575     // a PHI node in a successor, we cannot change the return type of the call
9576     // because there is no place to put the cast instruction (without breaking
9577     // the critical edge).  Bail out in this case.
9578     if (!Caller->use_empty())
9579       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9580         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9581              UI != E; ++UI)
9582           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9583             if (PN->getParent() == II->getNormalDest() ||
9584                 PN->getParent() == II->getUnwindDest())
9585               return false;
9586   }
9587
9588   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9589   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9590
9591   CallSite::arg_iterator AI = CS.arg_begin();
9592   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9593     const Type *ParamTy = FT->getParamType(i);
9594     const Type *ActTy = (*AI)->getType();
9595
9596     if (!CastInst::isCastable(ActTy, ParamTy))
9597       return false;   // Cannot transform this parameter value.
9598
9599     if (CallerPAL.getParamAttributes(i + 1) 
9600         & Attribute::typeIncompatible(ParamTy))
9601       return false;   // Attribute not compatible with transformed value.
9602
9603     // Converting from one pointer type to another or between a pointer and an
9604     // integer of the same size is safe even if we do not have a body.
9605     bool isConvertible = ActTy == ParamTy ||
9606       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9607        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9608     if (Callee->isDeclaration() && !isConvertible) return false;
9609   }
9610
9611   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9612       Callee->isDeclaration())
9613     return false;   // Do not delete arguments unless we have a function body.
9614
9615   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9616       !CallerPAL.isEmpty())
9617     // In this case we have more arguments than the new function type, but we
9618     // won't be dropping them.  Check that these extra arguments have attributes
9619     // that are compatible with being a vararg call argument.
9620     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9621       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9622         break;
9623       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9624       if (PAttrs & Attribute::VarArgsIncompatible)
9625         return false;
9626     }
9627
9628   // Okay, we decided that this is a safe thing to do: go ahead and start
9629   // inserting cast instructions as necessary...
9630   std::vector<Value*> Args;
9631   Args.reserve(NumActualArgs);
9632   SmallVector<AttributeWithIndex, 8> attrVec;
9633   attrVec.reserve(NumCommonArgs);
9634
9635   // Get any return attributes.
9636   Attributes RAttrs = CallerPAL.getRetAttributes();
9637
9638   // If the return value is not being used, the type may not be compatible
9639   // with the existing attributes.  Wipe out any problematic attributes.
9640   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9641
9642   // Add the new return attributes.
9643   if (RAttrs)
9644     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9645
9646   AI = CS.arg_begin();
9647   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9648     const Type *ParamTy = FT->getParamType(i);
9649     if ((*AI)->getType() == ParamTy) {
9650       Args.push_back(*AI);
9651     } else {
9652       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9653           false, ParamTy, false);
9654       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9655       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9656     }
9657
9658     // Add any parameter attributes.
9659     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9660       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9661   }
9662
9663   // If the function takes more arguments than the call was taking, add them
9664   // now...
9665   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9666     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9667
9668   // If we are removing arguments to the function, emit an obnoxious warning...
9669   if (FT->getNumParams() < NumActualArgs) {
9670     if (!FT->isVarArg()) {
9671       cerr << "WARNING: While resolving call to function '"
9672            << Callee->getName() << "' arguments were dropped!\n";
9673     } else {
9674       // Add all of the arguments in their promoted form to the arg list...
9675       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9676         const Type *PTy = getPromotedType((*AI)->getType());
9677         if (PTy != (*AI)->getType()) {
9678           // Must promote to pass through va_arg area!
9679           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9680                                                                 PTy, false);
9681           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9682           InsertNewInstBefore(Cast, *Caller);
9683           Args.push_back(Cast);
9684         } else {
9685           Args.push_back(*AI);
9686         }
9687
9688         // Add any parameter attributes.
9689         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9690           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9691       }
9692     }
9693   }
9694
9695   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9696     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9697
9698   if (NewRetTy == Type::VoidTy)
9699     Caller->setName("");   // Void type should not have a name.
9700
9701   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9702
9703   Instruction *NC;
9704   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9705     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9706                             Args.begin(), Args.end(),
9707                             Caller->getName(), Caller);
9708     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9709     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9710   } else {
9711     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9712                           Caller->getName(), Caller);
9713     CallInst *CI = cast<CallInst>(Caller);
9714     if (CI->isTailCall())
9715       cast<CallInst>(NC)->setTailCall();
9716     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9717     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9718   }
9719
9720   // Insert a cast of the return type as necessary.
9721   Value *NV = NC;
9722   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9723     if (NV->getType() != Type::VoidTy) {
9724       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9725                                                             OldRetTy, false);
9726       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9727
9728       // If this is an invoke instruction, we should insert it after the first
9729       // non-phi, instruction in the normal successor block.
9730       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9731         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9732         InsertNewInstBefore(NC, *I);
9733       } else {
9734         // Otherwise, it's a call, just insert cast right after the call instr
9735         InsertNewInstBefore(NC, *Caller);
9736       }
9737       AddUsersToWorkList(*Caller);
9738     } else {
9739       NV = UndefValue::get(Caller->getType());
9740     }
9741   }
9742
9743   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9744     Caller->replaceAllUsesWith(NV);
9745   Caller->eraseFromParent();
9746   RemoveFromWorkList(Caller);
9747   return true;
9748 }
9749
9750 // transformCallThroughTrampoline - Turn a call to a function created by the
9751 // init_trampoline intrinsic into a direct call to the underlying function.
9752 //
9753 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9754   Value *Callee = CS.getCalledValue();
9755   const PointerType *PTy = cast<PointerType>(Callee->getType());
9756   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9757   const AttrListPtr &Attrs = CS.getAttributes();
9758
9759   // If the call already has the 'nest' attribute somewhere then give up -
9760   // otherwise 'nest' would occur twice after splicing in the chain.
9761   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9762     return 0;
9763
9764   IntrinsicInst *Tramp =
9765     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9766
9767   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9768   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9769   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9770
9771   const AttrListPtr &NestAttrs = NestF->getAttributes();
9772   if (!NestAttrs.isEmpty()) {
9773     unsigned NestIdx = 1;
9774     const Type *NestTy = 0;
9775     Attributes NestAttr = Attribute::None;
9776
9777     // Look for a parameter marked with the 'nest' attribute.
9778     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9779          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9780       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9781         // Record the parameter type and any other attributes.
9782         NestTy = *I;
9783         NestAttr = NestAttrs.getParamAttributes(NestIdx);
9784         break;
9785       }
9786
9787     if (NestTy) {
9788       Instruction *Caller = CS.getInstruction();
9789       std::vector<Value*> NewArgs;
9790       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9791
9792       SmallVector<AttributeWithIndex, 8> NewAttrs;
9793       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9794
9795       // Insert the nest argument into the call argument list, which may
9796       // mean appending it.  Likewise for attributes.
9797
9798       // Add any result attributes.
9799       if (Attributes Attr = Attrs.getRetAttributes())
9800         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9801
9802       {
9803         unsigned Idx = 1;
9804         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9805         do {
9806           if (Idx == NestIdx) {
9807             // Add the chain argument and attributes.
9808             Value *NestVal = Tramp->getOperand(3);
9809             if (NestVal->getType() != NestTy)
9810               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9811             NewArgs.push_back(NestVal);
9812             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9813           }
9814
9815           if (I == E)
9816             break;
9817
9818           // Add the original argument and attributes.
9819           NewArgs.push_back(*I);
9820           if (Attributes Attr = Attrs.getParamAttributes(Idx))
9821             NewAttrs.push_back
9822               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9823
9824           ++Idx, ++I;
9825         } while (1);
9826       }
9827
9828       // Add any function attributes.
9829       if (Attributes Attr = Attrs.getFnAttributes())
9830         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9831
9832       // The trampoline may have been bitcast to a bogus type (FTy).
9833       // Handle this by synthesizing a new function type, equal to FTy
9834       // with the chain parameter inserted.
9835
9836       std::vector<const Type*> NewTypes;
9837       NewTypes.reserve(FTy->getNumParams()+1);
9838
9839       // Insert the chain's type into the list of parameter types, which may
9840       // mean appending it.
9841       {
9842         unsigned Idx = 1;
9843         FunctionType::param_iterator I = FTy->param_begin(),
9844           E = FTy->param_end();
9845
9846         do {
9847           if (Idx == NestIdx)
9848             // Add the chain's type.
9849             NewTypes.push_back(NestTy);
9850
9851           if (I == E)
9852             break;
9853
9854           // Add the original type.
9855           NewTypes.push_back(*I);
9856
9857           ++Idx, ++I;
9858         } while (1);
9859       }
9860
9861       // Replace the trampoline call with a direct call.  Let the generic
9862       // code sort out any function type mismatches.
9863       FunctionType *NewFTy =
9864         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9865       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9866         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9867       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
9868
9869       Instruction *NewCaller;
9870       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9871         NewCaller = InvokeInst::Create(NewCallee,
9872                                        II->getNormalDest(), II->getUnwindDest(),
9873                                        NewArgs.begin(), NewArgs.end(),
9874                                        Caller->getName(), Caller);
9875         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9876         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
9877       } else {
9878         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9879                                      Caller->getName(), Caller);
9880         if (cast<CallInst>(Caller)->isTailCall())
9881           cast<CallInst>(NewCaller)->setTailCall();
9882         cast<CallInst>(NewCaller)->
9883           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9884         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
9885       }
9886       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9887         Caller->replaceAllUsesWith(NewCaller);
9888       Caller->eraseFromParent();
9889       RemoveFromWorkList(Caller);
9890       return 0;
9891     }
9892   }
9893
9894   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9895   // parameter, there is no need to adjust the argument list.  Let the generic
9896   // code sort out any function type mismatches.
9897   Constant *NewCallee =
9898     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9899   CS.setCalledFunction(NewCallee);
9900   return CS.getInstruction();
9901 }
9902
9903 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9904 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9905 /// and a single binop.
9906 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9907   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9908   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9909          isa<CmpInst>(FirstInst));
9910   unsigned Opc = FirstInst->getOpcode();
9911   Value *LHSVal = FirstInst->getOperand(0);
9912   Value *RHSVal = FirstInst->getOperand(1);
9913     
9914   const Type *LHSType = LHSVal->getType();
9915   const Type *RHSType = RHSVal->getType();
9916   
9917   // Scan to see if all operands are the same opcode, all have one use, and all
9918   // kill their operands (i.e. the operands have one use).
9919   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9920     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9921     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9922         // Verify type of the LHS matches so we don't fold cmp's of different
9923         // types or GEP's with different index types.
9924         I->getOperand(0)->getType() != LHSType ||
9925         I->getOperand(1)->getType() != RHSType)
9926       return 0;
9927
9928     // If they are CmpInst instructions, check their predicates
9929     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9930       if (cast<CmpInst>(I)->getPredicate() !=
9931           cast<CmpInst>(FirstInst)->getPredicate())
9932         return 0;
9933     
9934     // Keep track of which operand needs a phi node.
9935     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9936     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9937   }
9938   
9939   // Otherwise, this is safe to transform, determine if it is profitable.
9940
9941   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9942   // Indexes are often folded into load/store instructions, so we don't want to
9943   // hide them behind a phi.
9944   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9945     return 0;
9946   
9947   Value *InLHS = FirstInst->getOperand(0);
9948   Value *InRHS = FirstInst->getOperand(1);
9949   PHINode *NewLHS = 0, *NewRHS = 0;
9950   if (LHSVal == 0) {
9951     NewLHS = PHINode::Create(LHSType,
9952                              FirstInst->getOperand(0)->getName() + ".pn");
9953     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9954     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9955     InsertNewInstBefore(NewLHS, PN);
9956     LHSVal = NewLHS;
9957   }
9958   
9959   if (RHSVal == 0) {
9960     NewRHS = PHINode::Create(RHSType,
9961                              FirstInst->getOperand(1)->getName() + ".pn");
9962     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9963     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9964     InsertNewInstBefore(NewRHS, PN);
9965     RHSVal = NewRHS;
9966   }
9967   
9968   // Add all operands to the new PHIs.
9969   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9970     if (NewLHS) {
9971       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9972       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9973     }
9974     if (NewRHS) {
9975       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9976       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9977     }
9978   }
9979     
9980   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9981     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9982   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9983     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9984                            RHSVal);
9985   else {
9986     assert(isa<GetElementPtrInst>(FirstInst));
9987     return GetElementPtrInst::Create(LHSVal, RHSVal);
9988   }
9989 }
9990
9991 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9992 /// of the block that defines it.  This means that it must be obvious the value
9993 /// of the load is not changed from the point of the load to the end of the
9994 /// block it is in.
9995 ///
9996 /// Finally, it is safe, but not profitable, to sink a load targetting a
9997 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9998 /// to a register.
9999 static bool isSafeToSinkLoad(LoadInst *L) {
10000   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10001   
10002   for (++BBI; BBI != E; ++BBI)
10003     if (BBI->mayWriteToMemory())
10004       return false;
10005   
10006   // Check for non-address taken alloca.  If not address-taken already, it isn't
10007   // profitable to do this xform.
10008   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10009     bool isAddressTaken = false;
10010     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10011          UI != E; ++UI) {
10012       if (isa<LoadInst>(UI)) continue;
10013       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10014         // If storing TO the alloca, then the address isn't taken.
10015         if (SI->getOperand(1) == AI) continue;
10016       }
10017       isAddressTaken = true;
10018       break;
10019     }
10020     
10021     if (!isAddressTaken)
10022       return false;
10023   }
10024   
10025   return true;
10026 }
10027
10028
10029 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10030 // operator and they all are only used by the PHI, PHI together their
10031 // inputs, and do the operation once, to the result of the PHI.
10032 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10033   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10034
10035   // Scan the instruction, looking for input operations that can be folded away.
10036   // If all input operands to the phi are the same instruction (e.g. a cast from
10037   // the same type or "+42") we can pull the operation through the PHI, reducing
10038   // code size and simplifying code.
10039   Constant *ConstantOp = 0;
10040   const Type *CastSrcTy = 0;
10041   bool isVolatile = false;
10042   if (isa<CastInst>(FirstInst)) {
10043     CastSrcTy = FirstInst->getOperand(0)->getType();
10044   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10045     // Can fold binop, compare or shift here if the RHS is a constant, 
10046     // otherwise call FoldPHIArgBinOpIntoPHI.
10047     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10048     if (ConstantOp == 0)
10049       return FoldPHIArgBinOpIntoPHI(PN);
10050   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10051     isVolatile = LI->isVolatile();
10052     // We can't sink the load if the loaded value could be modified between the
10053     // load and the PHI.
10054     if (LI->getParent() != PN.getIncomingBlock(0) ||
10055         !isSafeToSinkLoad(LI))
10056       return 0;
10057     
10058     // If the PHI is of volatile loads and the load block has multiple
10059     // successors, sinking it would remove a load of the volatile value from
10060     // the path through the other successor.
10061     if (isVolatile &&
10062         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10063       return 0;
10064     
10065   } else if (isa<GetElementPtrInst>(FirstInst)) {
10066     if (FirstInst->getNumOperands() == 2)
10067       return FoldPHIArgBinOpIntoPHI(PN);
10068     // Can't handle general GEPs yet.
10069     return 0;
10070   } else {
10071     return 0;  // Cannot fold this operation.
10072   }
10073
10074   // Check to see if all arguments are the same operation.
10075   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10076     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10077     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10078     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10079       return 0;
10080     if (CastSrcTy) {
10081       if (I->getOperand(0)->getType() != CastSrcTy)
10082         return 0;  // Cast operation must match.
10083     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10084       // We can't sink the load if the loaded value could be modified between 
10085       // the load and the PHI.
10086       if (LI->isVolatile() != isVolatile ||
10087           LI->getParent() != PN.getIncomingBlock(i) ||
10088           !isSafeToSinkLoad(LI))
10089         return 0;
10090       
10091       // If the PHI is of volatile loads and the load block has multiple
10092       // successors, sinking it would remove a load of the volatile value from
10093       // the path through the other successor.
10094       if (isVolatile &&
10095           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10096         return 0;
10097
10098       
10099     } else if (I->getOperand(1) != ConstantOp) {
10100       return 0;
10101     }
10102   }
10103
10104   // Okay, they are all the same operation.  Create a new PHI node of the
10105   // correct type, and PHI together all of the LHS's of the instructions.
10106   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10107                                    PN.getName()+".in");
10108   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10109
10110   Value *InVal = FirstInst->getOperand(0);
10111   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10112
10113   // Add all operands to the new PHI.
10114   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10115     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10116     if (NewInVal != InVal)
10117       InVal = 0;
10118     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10119   }
10120
10121   Value *PhiVal;
10122   if (InVal) {
10123     // The new PHI unions all of the same values together.  This is really
10124     // common, so we handle it intelligently here for compile-time speed.
10125     PhiVal = InVal;
10126     delete NewPN;
10127   } else {
10128     InsertNewInstBefore(NewPN, PN);
10129     PhiVal = NewPN;
10130   }
10131
10132   // Insert and return the new operation.
10133   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10134     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10135   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10136     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10137   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10138     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10139                            PhiVal, ConstantOp);
10140   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10141   
10142   // If this was a volatile load that we are merging, make sure to loop through
10143   // and mark all the input loads as non-volatile.  If we don't do this, we will
10144   // insert a new volatile load and the old ones will not be deletable.
10145   if (isVolatile)
10146     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10147       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10148   
10149   return new LoadInst(PhiVal, "", isVolatile);
10150 }
10151
10152 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10153 /// that is dead.
10154 static bool DeadPHICycle(PHINode *PN,
10155                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10156   if (PN->use_empty()) return true;
10157   if (!PN->hasOneUse()) return false;
10158
10159   // Remember this node, and if we find the cycle, return.
10160   if (!PotentiallyDeadPHIs.insert(PN))
10161     return true;
10162   
10163   // Don't scan crazily complex things.
10164   if (PotentiallyDeadPHIs.size() == 16)
10165     return false;
10166
10167   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10168     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10169
10170   return false;
10171 }
10172
10173 /// PHIsEqualValue - Return true if this phi node is always equal to
10174 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10175 ///   z = some value; x = phi (y, z); y = phi (x, z)
10176 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10177                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10178   // See if we already saw this PHI node.
10179   if (!ValueEqualPHIs.insert(PN))
10180     return true;
10181   
10182   // Don't scan crazily complex things.
10183   if (ValueEqualPHIs.size() == 16)
10184     return false;
10185  
10186   // Scan the operands to see if they are either phi nodes or are equal to
10187   // the value.
10188   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10189     Value *Op = PN->getIncomingValue(i);
10190     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10191       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10192         return false;
10193     } else if (Op != NonPhiInVal)
10194       return false;
10195   }
10196   
10197   return true;
10198 }
10199
10200
10201 // PHINode simplification
10202 //
10203 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10204   // If LCSSA is around, don't mess with Phi nodes
10205   if (MustPreserveLCSSA) return 0;
10206   
10207   if (Value *V = PN.hasConstantValue())
10208     return ReplaceInstUsesWith(PN, V);
10209
10210   // If all PHI operands are the same operation, pull them through the PHI,
10211   // reducing code size.
10212   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10213       PN.getIncomingValue(0)->hasOneUse())
10214     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10215       return Result;
10216
10217   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10218   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10219   // PHI)... break the cycle.
10220   if (PN.hasOneUse()) {
10221     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10222     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10223       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10224       PotentiallyDeadPHIs.insert(&PN);
10225       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10226         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10227     }
10228    
10229     // If this phi has a single use, and if that use just computes a value for
10230     // the next iteration of a loop, delete the phi.  This occurs with unused
10231     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10232     // common case here is good because the only other things that catch this
10233     // are induction variable analysis (sometimes) and ADCE, which is only run
10234     // late.
10235     if (PHIUser->hasOneUse() &&
10236         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10237         PHIUser->use_back() == &PN) {
10238       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10239     }
10240   }
10241
10242   // We sometimes end up with phi cycles that non-obviously end up being the
10243   // same value, for example:
10244   //   z = some value; x = phi (y, z); y = phi (x, z)
10245   // where the phi nodes don't necessarily need to be in the same block.  Do a
10246   // quick check to see if the PHI node only contains a single non-phi value, if
10247   // so, scan to see if the phi cycle is actually equal to that value.
10248   {
10249     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10250     // Scan for the first non-phi operand.
10251     while (InValNo != NumOperandVals && 
10252            isa<PHINode>(PN.getIncomingValue(InValNo)))
10253       ++InValNo;
10254
10255     if (InValNo != NumOperandVals) {
10256       Value *NonPhiInVal = PN.getOperand(InValNo);
10257       
10258       // Scan the rest of the operands to see if there are any conflicts, if so
10259       // there is no need to recursively scan other phis.
10260       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10261         Value *OpVal = PN.getIncomingValue(InValNo);
10262         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10263           break;
10264       }
10265       
10266       // If we scanned over all operands, then we have one unique value plus
10267       // phi values.  Scan PHI nodes to see if they all merge in each other or
10268       // the value.
10269       if (InValNo == NumOperandVals) {
10270         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10271         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10272           return ReplaceInstUsesWith(PN, NonPhiInVal);
10273       }
10274     }
10275   }
10276   return 0;
10277 }
10278
10279 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10280                                    Instruction *InsertPoint,
10281                                    InstCombiner *IC) {
10282   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10283   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10284   // We must cast correctly to the pointer type. Ensure that we
10285   // sign extend the integer value if it is smaller as this is
10286   // used for address computation.
10287   Instruction::CastOps opcode = 
10288      (VTySize < PtrSize ? Instruction::SExt :
10289       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10290   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10291 }
10292
10293
10294 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10295   Value *PtrOp = GEP.getOperand(0);
10296   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10297   // If so, eliminate the noop.
10298   if (GEP.getNumOperands() == 1)
10299     return ReplaceInstUsesWith(GEP, PtrOp);
10300
10301   if (isa<UndefValue>(GEP.getOperand(0)))
10302     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10303
10304   bool HasZeroPointerIndex = false;
10305   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10306     HasZeroPointerIndex = C->isNullValue();
10307
10308   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10309     return ReplaceInstUsesWith(GEP, PtrOp);
10310
10311   // Eliminate unneeded casts for indices.
10312   bool MadeChange = false;
10313   
10314   gep_type_iterator GTI = gep_type_begin(GEP);
10315   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10316        i != e; ++i, ++GTI) {
10317     if (isa<SequentialType>(*GTI)) {
10318       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10319         if (CI->getOpcode() == Instruction::ZExt ||
10320             CI->getOpcode() == Instruction::SExt) {
10321           const Type *SrcTy = CI->getOperand(0)->getType();
10322           // We can eliminate a cast from i32 to i64 iff the target 
10323           // is a 32-bit pointer target.
10324           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10325             MadeChange = true;
10326             *i = CI->getOperand(0);
10327           }
10328         }
10329       }
10330       // If we are using a wider index than needed for this platform, shrink it
10331       // to what we need.  If narrower, sign-extend it to what we need.
10332       // If the incoming value needs a cast instruction,
10333       // insert it.  This explicit cast can make subsequent optimizations more
10334       // obvious.
10335       Value *Op = *i;
10336       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10337         if (Constant *C = dyn_cast<Constant>(Op)) {
10338           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10339           MadeChange = true;
10340         } else {
10341           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10342                                 GEP);
10343           *i = Op;
10344           MadeChange = true;
10345         }
10346       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10347         if (Constant *C = dyn_cast<Constant>(Op)) {
10348           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10349           MadeChange = true;
10350         } else {
10351           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10352                                 GEP);
10353           *i = Op;
10354           MadeChange = true;
10355         }
10356       }
10357     }
10358   }
10359   if (MadeChange) return &GEP;
10360
10361   // If this GEP instruction doesn't move the pointer, and if the input operand
10362   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10363   // real input to the dest type.
10364   if (GEP.hasAllZeroIndices()) {
10365     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10366       // If the bitcast is of an allocation, and the allocation will be
10367       // converted to match the type of the cast, don't touch this.
10368       if (isa<AllocationInst>(BCI->getOperand(0))) {
10369         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10370         if (Instruction *I = visitBitCast(*BCI)) {
10371           if (I != BCI) {
10372             I->takeName(BCI);
10373             BCI->getParent()->getInstList().insert(BCI, I);
10374             ReplaceInstUsesWith(*BCI, I);
10375           }
10376           return &GEP;
10377         }
10378       }
10379       return new BitCastInst(BCI->getOperand(0), GEP.getType());
10380     }
10381   }
10382   
10383   // Combine Indices - If the source pointer to this getelementptr instruction
10384   // is a getelementptr instruction, combine the indices of the two
10385   // getelementptr instructions into a single instruction.
10386   //
10387   SmallVector<Value*, 8> SrcGEPOperands;
10388   if (User *Src = dyn_castGetElementPtr(PtrOp))
10389     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10390
10391   if (!SrcGEPOperands.empty()) {
10392     // Note that if our source is a gep chain itself that we wait for that
10393     // chain to be resolved before we perform this transformation.  This
10394     // avoids us creating a TON of code in some cases.
10395     //
10396     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10397         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10398       return 0;   // Wait until our source is folded to completion.
10399
10400     SmallVector<Value*, 8> Indices;
10401
10402     // Find out whether the last index in the source GEP is a sequential idx.
10403     bool EndsWithSequential = false;
10404     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10405            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10406       EndsWithSequential = !isa<StructType>(*I);
10407
10408     // Can we combine the two pointer arithmetics offsets?
10409     if (EndsWithSequential) {
10410       // Replace: gep (gep %P, long B), long A, ...
10411       // With:    T = long A+B; gep %P, T, ...
10412       //
10413       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10414       if (SO1 == Constant::getNullValue(SO1->getType())) {
10415         Sum = GO1;
10416       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10417         Sum = SO1;
10418       } else {
10419         // If they aren't the same type, convert both to an integer of the
10420         // target's pointer size.
10421         if (SO1->getType() != GO1->getType()) {
10422           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10423             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10424           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10425             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10426           } else {
10427             unsigned PS = TD->getPointerSizeInBits();
10428             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10429               // Convert GO1 to SO1's type.
10430               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10431
10432             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10433               // Convert SO1 to GO1's type.
10434               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10435             } else {
10436               const Type *PT = TD->getIntPtrType();
10437               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10438               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10439             }
10440           }
10441         }
10442         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10443           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10444         else {
10445           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10446           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10447         }
10448       }
10449
10450       // Recycle the GEP we already have if possible.
10451       if (SrcGEPOperands.size() == 2) {
10452         GEP.setOperand(0, SrcGEPOperands[0]);
10453         GEP.setOperand(1, Sum);
10454         return &GEP;
10455       } else {
10456         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10457                        SrcGEPOperands.end()-1);
10458         Indices.push_back(Sum);
10459         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10460       }
10461     } else if (isa<Constant>(*GEP.idx_begin()) &&
10462                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10463                SrcGEPOperands.size() != 1) {
10464       // Otherwise we can do the fold if the first index of the GEP is a zero
10465       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10466                      SrcGEPOperands.end());
10467       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10468     }
10469
10470     if (!Indices.empty())
10471       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10472                                        Indices.end(), GEP.getName());
10473
10474   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10475     // GEP of global variable.  If all of the indices for this GEP are
10476     // constants, we can promote this to a constexpr instead of an instruction.
10477
10478     // Scan for nonconstants...
10479     SmallVector<Constant*, 8> Indices;
10480     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10481     for (; I != E && isa<Constant>(*I); ++I)
10482       Indices.push_back(cast<Constant>(*I));
10483
10484     if (I == E) {  // If they are all constants...
10485       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10486                                                     &Indices[0],Indices.size());
10487
10488       // Replace all uses of the GEP with the new constexpr...
10489       return ReplaceInstUsesWith(GEP, CE);
10490     }
10491   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10492     if (!isa<PointerType>(X->getType())) {
10493       // Not interesting.  Source pointer must be a cast from pointer.
10494     } else if (HasZeroPointerIndex) {
10495       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10496       // into     : GEP [10 x i8]* X, i32 0, ...
10497       //
10498       // This occurs when the program declares an array extern like "int X[];"
10499       //
10500       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10501       const PointerType *XTy = cast<PointerType>(X->getType());
10502       if (const ArrayType *XATy =
10503           dyn_cast<ArrayType>(XTy->getElementType()))
10504         if (const ArrayType *CATy =
10505             dyn_cast<ArrayType>(CPTy->getElementType()))
10506           if (CATy->getElementType() == XATy->getElementType()) {
10507             // At this point, we know that the cast source type is a pointer
10508             // to an array of the same type as the destination pointer
10509             // array.  Because the array type is never stepped over (there
10510             // is a leading zero) we can fold the cast into this GEP.
10511             GEP.setOperand(0, X);
10512             return &GEP;
10513           }
10514     } else if (GEP.getNumOperands() == 2) {
10515       // Transform things like:
10516       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10517       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10518       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10519       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10520       if (isa<ArrayType>(SrcElTy) &&
10521           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10522           TD->getABITypeSize(ResElTy)) {
10523         Value *Idx[2];
10524         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10525         Idx[1] = GEP.getOperand(1);
10526         Value *V = InsertNewInstBefore(
10527                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10528         // V and GEP are both pointer types --> BitCast
10529         return new BitCastInst(V, GEP.getType());
10530       }
10531       
10532       // Transform things like:
10533       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10534       //   (where tmp = 8*tmp2) into:
10535       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10536       
10537       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10538         uint64_t ArrayEltSize =
10539             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10540         
10541         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10542         // allow either a mul, shift, or constant here.
10543         Value *NewIdx = 0;
10544         ConstantInt *Scale = 0;
10545         if (ArrayEltSize == 1) {
10546           NewIdx = GEP.getOperand(1);
10547           Scale = ConstantInt::get(NewIdx->getType(), 1);
10548         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10549           NewIdx = ConstantInt::get(CI->getType(), 1);
10550           Scale = CI;
10551         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10552           if (Inst->getOpcode() == Instruction::Shl &&
10553               isa<ConstantInt>(Inst->getOperand(1))) {
10554             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10555             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10556             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10557             NewIdx = Inst->getOperand(0);
10558           } else if (Inst->getOpcode() == Instruction::Mul &&
10559                      isa<ConstantInt>(Inst->getOperand(1))) {
10560             Scale = cast<ConstantInt>(Inst->getOperand(1));
10561             NewIdx = Inst->getOperand(0);
10562           }
10563         }
10564         
10565         // If the index will be to exactly the right offset with the scale taken
10566         // out, perform the transformation. Note, we don't know whether Scale is
10567         // signed or not. We'll use unsigned version of division/modulo
10568         // operation after making sure Scale doesn't have the sign bit set.
10569         if (Scale && Scale->getSExtValue() >= 0LL &&
10570             Scale->getZExtValue() % ArrayEltSize == 0) {
10571           Scale = ConstantInt::get(Scale->getType(),
10572                                    Scale->getZExtValue() / ArrayEltSize);
10573           if (Scale->getZExtValue() != 1) {
10574             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10575                                                        false /*ZExt*/);
10576             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10577             NewIdx = InsertNewInstBefore(Sc, GEP);
10578           }
10579
10580           // Insert the new GEP instruction.
10581           Value *Idx[2];
10582           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10583           Idx[1] = NewIdx;
10584           Instruction *NewGEP =
10585             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10586           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10587           // The NewGEP must be pointer typed, so must the old one -> BitCast
10588           return new BitCastInst(NewGEP, GEP.getType());
10589         }
10590       }
10591     }
10592   }
10593
10594   return 0;
10595 }
10596
10597 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10598   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10599   if (AI.isArrayAllocation()) {  // Check C != 1
10600     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10601       const Type *NewTy = 
10602         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10603       AllocationInst *New = 0;
10604
10605       // Create and insert the replacement instruction...
10606       if (isa<MallocInst>(AI))
10607         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10608       else {
10609         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10610         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10611       }
10612
10613       InsertNewInstBefore(New, AI);
10614
10615       // Scan to the end of the allocation instructions, to skip over a block of
10616       // allocas if possible...
10617       //
10618       BasicBlock::iterator It = New;
10619       while (isa<AllocationInst>(*It)) ++It;
10620
10621       // Now that I is pointing to the first non-allocation-inst in the block,
10622       // insert our getelementptr instruction...
10623       //
10624       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10625       Value *Idx[2];
10626       Idx[0] = NullIdx;
10627       Idx[1] = NullIdx;
10628       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10629                                            New->getName()+".sub", It);
10630
10631       // Now make everything use the getelementptr instead of the original
10632       // allocation.
10633       return ReplaceInstUsesWith(AI, V);
10634     } else if (isa<UndefValue>(AI.getArraySize())) {
10635       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10636     }
10637   }
10638
10639   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10640   // Note that we only do this for alloca's, because malloc should allocate and
10641   // return a unique pointer, even for a zero byte allocation.
10642   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10643       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10644     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10645
10646   return 0;
10647 }
10648
10649 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10650   Value *Op = FI.getOperand(0);
10651
10652   // free undef -> unreachable.
10653   if (isa<UndefValue>(Op)) {
10654     // Insert a new store to null because we cannot modify the CFG here.
10655     new StoreInst(ConstantInt::getTrue(),
10656                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10657     return EraseInstFromFunction(FI);
10658   }
10659   
10660   // If we have 'free null' delete the instruction.  This can happen in stl code
10661   // when lots of inlining happens.
10662   if (isa<ConstantPointerNull>(Op))
10663     return EraseInstFromFunction(FI);
10664   
10665   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10666   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10667     FI.setOperand(0, CI->getOperand(0));
10668     return &FI;
10669   }
10670   
10671   // Change free (gep X, 0,0,0,0) into free(X)
10672   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10673     if (GEPI->hasAllZeroIndices()) {
10674       AddToWorkList(GEPI);
10675       FI.setOperand(0, GEPI->getOperand(0));
10676       return &FI;
10677     }
10678   }
10679   
10680   // Change free(malloc) into nothing, if the malloc has a single use.
10681   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10682     if (MI->hasOneUse()) {
10683       EraseInstFromFunction(FI);
10684       return EraseInstFromFunction(*MI);
10685     }
10686
10687   return 0;
10688 }
10689
10690
10691 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10692 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10693                                         const TargetData *TD) {
10694   User *CI = cast<User>(LI.getOperand(0));
10695   Value *CastOp = CI->getOperand(0);
10696
10697   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10698     // Instead of loading constant c string, use corresponding integer value
10699     // directly if string length is small enough.
10700     std::string Str;
10701     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10702       unsigned len = Str.length();
10703       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10704       unsigned numBits = Ty->getPrimitiveSizeInBits();
10705       // Replace LI with immediate integer store.
10706       if ((numBits >> 3) == len + 1) {
10707         APInt StrVal(numBits, 0);
10708         APInt SingleChar(numBits, 0);
10709         if (TD->isLittleEndian()) {
10710           for (signed i = len-1; i >= 0; i--) {
10711             SingleChar = (uint64_t) Str[i];
10712             StrVal = (StrVal << 8) | SingleChar;
10713           }
10714         } else {
10715           for (unsigned i = 0; i < len; i++) {
10716             SingleChar = (uint64_t) Str[i];
10717             StrVal = (StrVal << 8) | SingleChar;
10718           }
10719           // Append NULL at the end.
10720           SingleChar = 0;
10721           StrVal = (StrVal << 8) | SingleChar;
10722         }
10723         Value *NL = ConstantInt::get(StrVal);
10724         return IC.ReplaceInstUsesWith(LI, NL);
10725       }
10726     }
10727   }
10728
10729   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10730   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10731     const Type *SrcPTy = SrcTy->getElementType();
10732
10733     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10734          isa<VectorType>(DestPTy)) {
10735       // If the source is an array, the code below will not succeed.  Check to
10736       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10737       // constants.
10738       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10739         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10740           if (ASrcTy->getNumElements() != 0) {
10741             Value *Idxs[2];
10742             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10743             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10744             SrcTy = cast<PointerType>(CastOp->getType());
10745             SrcPTy = SrcTy->getElementType();
10746           }
10747
10748       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10749             isa<VectorType>(SrcPTy)) &&
10750           // Do not allow turning this into a load of an integer, which is then
10751           // casted to a pointer, this pessimizes pointer analysis a lot.
10752           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10753           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10754                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10755
10756         // Okay, we are casting from one integer or pointer type to another of
10757         // the same size.  Instead of casting the pointer before the load, cast
10758         // the result of the loaded value.
10759         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10760                                                              CI->getName(),
10761                                                          LI.isVolatile()),LI);
10762         // Now cast the result of the load.
10763         return new BitCastInst(NewLoad, LI.getType());
10764       }
10765     }
10766   }
10767   return 0;
10768 }
10769
10770 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10771 /// from this value cannot trap.  If it is not obviously safe to load from the
10772 /// specified pointer, we do a quick local scan of the basic block containing
10773 /// ScanFrom, to determine if the address is already accessed.
10774 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10775   // If it is an alloca it is always safe to load from.
10776   if (isa<AllocaInst>(V)) return true;
10777
10778   // If it is a global variable it is mostly safe to load from.
10779   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10780     // Don't try to evaluate aliases.  External weak GV can be null.
10781     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10782
10783   // Otherwise, be a little bit agressive by scanning the local block where we
10784   // want to check to see if the pointer is already being loaded or stored
10785   // from/to.  If so, the previous load or store would have already trapped,
10786   // so there is no harm doing an extra load (also, CSE will later eliminate
10787   // the load entirely).
10788   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10789
10790   while (BBI != E) {
10791     --BBI;
10792
10793     // If we see a free or a call (which might do a free) the pointer could be
10794     // marked invalid.
10795     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10796       return false;
10797     
10798     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10799       if (LI->getOperand(0) == V) return true;
10800     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10801       if (SI->getOperand(1) == V) return true;
10802     }
10803
10804   }
10805   return false;
10806 }
10807
10808 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10809   Value *Op = LI.getOperand(0);
10810
10811   // Attempt to improve the alignment.
10812   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10813   if (KnownAlign >
10814       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10815                                 LI.getAlignment()))
10816     LI.setAlignment(KnownAlign);
10817
10818   // load (cast X) --> cast (load X) iff safe
10819   if (isa<CastInst>(Op))
10820     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10821       return Res;
10822
10823   // None of the following transforms are legal for volatile loads.
10824   if (LI.isVolatile()) return 0;
10825   
10826   // Do really simple store-to-load forwarding and load CSE, to catch cases
10827   // where there are several consequtive memory accesses to the same location,
10828   // separated by a few arithmetic operations.
10829   BasicBlock::iterator BBI = &LI;
10830   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
10831     return ReplaceInstUsesWith(LI, AvailableVal);
10832
10833   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10834     const Value *GEPI0 = GEPI->getOperand(0);
10835     // TODO: Consider a target hook for valid address spaces for this xform.
10836     if (isa<ConstantPointerNull>(GEPI0) &&
10837         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10838       // Insert a new store to null instruction before the load to indicate
10839       // that this code is not reachable.  We do this instead of inserting
10840       // an unreachable instruction directly because we cannot modify the
10841       // CFG.
10842       new StoreInst(UndefValue::get(LI.getType()),
10843                     Constant::getNullValue(Op->getType()), &LI);
10844       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10845     }
10846   } 
10847
10848   if (Constant *C = dyn_cast<Constant>(Op)) {
10849     // load null/undef -> undef
10850     // TODO: Consider a target hook for valid address spaces for this xform.
10851     if (isa<UndefValue>(C) || (C->isNullValue() && 
10852         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10853       // Insert a new store to null instruction before the load to indicate that
10854       // this code is not reachable.  We do this instead of inserting an
10855       // unreachable instruction directly because we cannot modify the CFG.
10856       new StoreInst(UndefValue::get(LI.getType()),
10857                     Constant::getNullValue(Op->getType()), &LI);
10858       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10859     }
10860
10861     // Instcombine load (constant global) into the value loaded.
10862     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10863       if (GV->isConstant() && !GV->isDeclaration())
10864         return ReplaceInstUsesWith(LI, GV->getInitializer());
10865
10866     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10867     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10868       if (CE->getOpcode() == Instruction::GetElementPtr) {
10869         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10870           if (GV->isConstant() && !GV->isDeclaration())
10871             if (Constant *V = 
10872                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10873               return ReplaceInstUsesWith(LI, V);
10874         if (CE->getOperand(0)->isNullValue()) {
10875           // Insert a new store to null instruction before the load to indicate
10876           // that this code is not reachable.  We do this instead of inserting
10877           // an unreachable instruction directly because we cannot modify the
10878           // CFG.
10879           new StoreInst(UndefValue::get(LI.getType()),
10880                         Constant::getNullValue(Op->getType()), &LI);
10881           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10882         }
10883
10884       } else if (CE->isCast()) {
10885         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10886           return Res;
10887       }
10888     }
10889   }
10890     
10891   // If this load comes from anywhere in a constant global, and if the global
10892   // is all undef or zero, we know what it loads.
10893   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
10894     if (GV->isConstant() && GV->hasInitializer()) {
10895       if (GV->getInitializer()->isNullValue())
10896         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10897       else if (isa<UndefValue>(GV->getInitializer()))
10898         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10899     }
10900   }
10901
10902   if (Op->hasOneUse()) {
10903     // Change select and PHI nodes to select values instead of addresses: this
10904     // helps alias analysis out a lot, allows many others simplifications, and
10905     // exposes redundancy in the code.
10906     //
10907     // Note that we cannot do the transformation unless we know that the
10908     // introduced loads cannot trap!  Something like this is valid as long as
10909     // the condition is always false: load (select bool %C, int* null, int* %G),
10910     // but it would not be valid if we transformed it to load from null
10911     // unconditionally.
10912     //
10913     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10914       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10915       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10916           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10917         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10918                                      SI->getOperand(1)->getName()+".val"), LI);
10919         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10920                                      SI->getOperand(2)->getName()+".val"), LI);
10921         return SelectInst::Create(SI->getCondition(), V1, V2);
10922       }
10923
10924       // load (select (cond, null, P)) -> load P
10925       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10926         if (C->isNullValue()) {
10927           LI.setOperand(0, SI->getOperand(2));
10928           return &LI;
10929         }
10930
10931       // load (select (cond, P, null)) -> load P
10932       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10933         if (C->isNullValue()) {
10934           LI.setOperand(0, SI->getOperand(1));
10935           return &LI;
10936         }
10937     }
10938   }
10939   return 0;
10940 }
10941
10942 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10943 /// when possible.
10944 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10945   User *CI = cast<User>(SI.getOperand(1));
10946   Value *CastOp = CI->getOperand(0);
10947
10948   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10949   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10950     const Type *SrcPTy = SrcTy->getElementType();
10951
10952     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10953       // If the source is an array, the code below will not succeed.  Check to
10954       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10955       // constants.
10956       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10957         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10958           if (ASrcTy->getNumElements() != 0) {
10959             Value* Idxs[2];
10960             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10961             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10962             SrcTy = cast<PointerType>(CastOp->getType());
10963             SrcPTy = SrcTy->getElementType();
10964           }
10965
10966       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10967           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10968                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10969
10970         // Okay, we are casting from one integer or pointer type to another of
10971         // the same size.  Instead of casting the pointer before 
10972         // the store, cast the value to be stored.
10973         Value *NewCast;
10974         Value *SIOp0 = SI.getOperand(0);
10975         Instruction::CastOps opcode = Instruction::BitCast;
10976         const Type* CastSrcTy = SIOp0->getType();
10977         const Type* CastDstTy = SrcPTy;
10978         if (isa<PointerType>(CastDstTy)) {
10979           if (CastSrcTy->isInteger())
10980             opcode = Instruction::IntToPtr;
10981         } else if (isa<IntegerType>(CastDstTy)) {
10982           if (isa<PointerType>(SIOp0->getType()))
10983             opcode = Instruction::PtrToInt;
10984         }
10985         if (Constant *C = dyn_cast<Constant>(SIOp0))
10986           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10987         else
10988           NewCast = IC.InsertNewInstBefore(
10989             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10990             SI);
10991         return new StoreInst(NewCast, CastOp);
10992       }
10993     }
10994   }
10995   return 0;
10996 }
10997
10998 /// equivalentAddressValues - Test if A and B will obviously have the same
10999 /// value. This includes recognizing that %t0 and %t1 will have the same
11000 /// value in code like this:
11001 ///   %t0 = getelementptr @a, 0, 3
11002 ///   store i32 0, i32* %t0
11003 ///   %t1 = getelementptr @a, 0, 3
11004 ///   %t2 = load i32* %t1
11005 ///
11006 static bool equivalentAddressValues(Value *A, Value *B) {
11007   // Test if the values are trivially equivalent.
11008   if (A == B) return true;
11009   
11010   // Test if the values come form identical arithmetic instructions.
11011   if (isa<BinaryOperator>(A) ||
11012       isa<CastInst>(A) ||
11013       isa<PHINode>(A) ||
11014       isa<GetElementPtrInst>(A))
11015     if (Instruction *BI = dyn_cast<Instruction>(B))
11016       if (cast<Instruction>(A)->isIdenticalTo(BI))
11017         return true;
11018   
11019   // Otherwise they may not be equivalent.
11020   return false;
11021 }
11022
11023 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11024   Value *Val = SI.getOperand(0);
11025   Value *Ptr = SI.getOperand(1);
11026
11027   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11028     EraseInstFromFunction(SI);
11029     ++NumCombined;
11030     return 0;
11031   }
11032   
11033   // If the RHS is an alloca with a single use, zapify the store, making the
11034   // alloca dead.
11035   if (Ptr->hasOneUse() && !SI.isVolatile()) {
11036     if (isa<AllocaInst>(Ptr)) {
11037       EraseInstFromFunction(SI);
11038       ++NumCombined;
11039       return 0;
11040     }
11041     
11042     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11043       if (isa<AllocaInst>(GEP->getOperand(0)) &&
11044           GEP->getOperand(0)->hasOneUse()) {
11045         EraseInstFromFunction(SI);
11046         ++NumCombined;
11047         return 0;
11048       }
11049   }
11050
11051   // Attempt to improve the alignment.
11052   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11053   if (KnownAlign >
11054       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11055                                 SI.getAlignment()))
11056     SI.setAlignment(KnownAlign);
11057
11058   // Do really simple DSE, to catch cases where there are several consequtive
11059   // stores to the same location, separated by a few arithmetic operations. This
11060   // situation often occurs with bitfield accesses.
11061   BasicBlock::iterator BBI = &SI;
11062   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11063        --ScanInsts) {
11064     --BBI;
11065     
11066     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11067       // Prev store isn't volatile, and stores to the same location?
11068       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11069                                                           SI.getOperand(1))) {
11070         ++NumDeadStore;
11071         ++BBI;
11072         EraseInstFromFunction(*PrevSI);
11073         continue;
11074       }
11075       break;
11076     }
11077     
11078     // If this is a load, we have to stop.  However, if the loaded value is from
11079     // the pointer we're loading and is producing the pointer we're storing,
11080     // then *this* store is dead (X = load P; store X -> P).
11081     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11082       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11083           !SI.isVolatile()) {
11084         EraseInstFromFunction(SI);
11085         ++NumCombined;
11086         return 0;
11087       }
11088       // Otherwise, this is a load from some other location.  Stores before it
11089       // may not be dead.
11090       break;
11091     }
11092     
11093     // Don't skip over loads or things that can modify memory.
11094     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11095       break;
11096   }
11097   
11098   
11099   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11100
11101   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11102   if (isa<ConstantPointerNull>(Ptr)) {
11103     if (!isa<UndefValue>(Val)) {
11104       SI.setOperand(0, UndefValue::get(Val->getType()));
11105       if (Instruction *U = dyn_cast<Instruction>(Val))
11106         AddToWorkList(U);  // Dropped a use.
11107       ++NumCombined;
11108     }
11109     return 0;  // Do not modify these!
11110   }
11111
11112   // store undef, Ptr -> noop
11113   if (isa<UndefValue>(Val)) {
11114     EraseInstFromFunction(SI);
11115     ++NumCombined;
11116     return 0;
11117   }
11118
11119   // If the pointer destination is a cast, see if we can fold the cast into the
11120   // source instead.
11121   if (isa<CastInst>(Ptr))
11122     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11123       return Res;
11124   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11125     if (CE->isCast())
11126       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11127         return Res;
11128
11129   
11130   // If this store is the last instruction in the basic block, and if the block
11131   // ends with an unconditional branch, try to move it to the successor block.
11132   BBI = &SI; ++BBI;
11133   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11134     if (BI->isUnconditional())
11135       if (SimplifyStoreAtEndOfBlock(SI))
11136         return 0;  // xform done!
11137   
11138   return 0;
11139 }
11140
11141 /// SimplifyStoreAtEndOfBlock - Turn things like:
11142 ///   if () { *P = v1; } else { *P = v2 }
11143 /// into a phi node with a store in the successor.
11144 ///
11145 /// Simplify things like:
11146 ///   *P = v1; if () { *P = v2; }
11147 /// into a phi node with a store in the successor.
11148 ///
11149 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11150   BasicBlock *StoreBB = SI.getParent();
11151   
11152   // Check to see if the successor block has exactly two incoming edges.  If
11153   // so, see if the other predecessor contains a store to the same location.
11154   // if so, insert a PHI node (if needed) and move the stores down.
11155   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11156   
11157   // Determine whether Dest has exactly two predecessors and, if so, compute
11158   // the other predecessor.
11159   pred_iterator PI = pred_begin(DestBB);
11160   BasicBlock *OtherBB = 0;
11161   if (*PI != StoreBB)
11162     OtherBB = *PI;
11163   ++PI;
11164   if (PI == pred_end(DestBB))
11165     return false;
11166   
11167   if (*PI != StoreBB) {
11168     if (OtherBB)
11169       return false;
11170     OtherBB = *PI;
11171   }
11172   if (++PI != pred_end(DestBB))
11173     return false;
11174
11175   // Bail out if all the relevant blocks aren't distinct (this can happen,
11176   // for example, if SI is in an infinite loop)
11177   if (StoreBB == DestBB || OtherBB == DestBB)
11178     return false;
11179
11180   // Verify that the other block ends in a branch and is not otherwise empty.
11181   BasicBlock::iterator BBI = OtherBB->getTerminator();
11182   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11183   if (!OtherBr || BBI == OtherBB->begin())
11184     return false;
11185   
11186   // If the other block ends in an unconditional branch, check for the 'if then
11187   // else' case.  there is an instruction before the branch.
11188   StoreInst *OtherStore = 0;
11189   if (OtherBr->isUnconditional()) {
11190     // If this isn't a store, or isn't a store to the same location, bail out.
11191     --BBI;
11192     OtherStore = dyn_cast<StoreInst>(BBI);
11193     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11194       return false;
11195   } else {
11196     // Otherwise, the other block ended with a conditional branch. If one of the
11197     // destinations is StoreBB, then we have the if/then case.
11198     if (OtherBr->getSuccessor(0) != StoreBB && 
11199         OtherBr->getSuccessor(1) != StoreBB)
11200       return false;
11201     
11202     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11203     // if/then triangle.  See if there is a store to the same ptr as SI that
11204     // lives in OtherBB.
11205     for (;; --BBI) {
11206       // Check to see if we find the matching store.
11207       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11208         if (OtherStore->getOperand(1) != SI.getOperand(1))
11209           return false;
11210         break;
11211       }
11212       // If we find something that may be using or overwriting the stored
11213       // value, or if we run out of instructions, we can't do the xform.
11214       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11215           BBI == OtherBB->begin())
11216         return false;
11217     }
11218     
11219     // In order to eliminate the store in OtherBr, we have to
11220     // make sure nothing reads or overwrites the stored value in
11221     // StoreBB.
11222     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11223       // FIXME: This should really be AA driven.
11224       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11225         return false;
11226     }
11227   }
11228   
11229   // Insert a PHI node now if we need it.
11230   Value *MergedVal = OtherStore->getOperand(0);
11231   if (MergedVal != SI.getOperand(0)) {
11232     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11233     PN->reserveOperandSpace(2);
11234     PN->addIncoming(SI.getOperand(0), SI.getParent());
11235     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11236     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11237   }
11238   
11239   // Advance to a place where it is safe to insert the new store and
11240   // insert it.
11241   BBI = DestBB->getFirstNonPHI();
11242   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11243                                     OtherStore->isVolatile()), *BBI);
11244   
11245   // Nuke the old stores.
11246   EraseInstFromFunction(SI);
11247   EraseInstFromFunction(*OtherStore);
11248   ++NumCombined;
11249   return true;
11250 }
11251
11252
11253 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11254   // Change br (not X), label True, label False to: br X, label False, True
11255   Value *X = 0;
11256   BasicBlock *TrueDest;
11257   BasicBlock *FalseDest;
11258   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11259       !isa<Constant>(X)) {
11260     // Swap Destinations and condition...
11261     BI.setCondition(X);
11262     BI.setSuccessor(0, FalseDest);
11263     BI.setSuccessor(1, TrueDest);
11264     return &BI;
11265   }
11266
11267   // Cannonicalize fcmp_one -> fcmp_oeq
11268   FCmpInst::Predicate FPred; Value *Y;
11269   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11270                              TrueDest, FalseDest)))
11271     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11272          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11273       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11274       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11275       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11276       NewSCC->takeName(I);
11277       // Swap Destinations and condition...
11278       BI.setCondition(NewSCC);
11279       BI.setSuccessor(0, FalseDest);
11280       BI.setSuccessor(1, TrueDest);
11281       RemoveFromWorkList(I);
11282       I->eraseFromParent();
11283       AddToWorkList(NewSCC);
11284       return &BI;
11285     }
11286
11287   // Cannonicalize icmp_ne -> icmp_eq
11288   ICmpInst::Predicate IPred;
11289   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11290                       TrueDest, FalseDest)))
11291     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11292          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11293          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11294       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11295       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11296       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11297       NewSCC->takeName(I);
11298       // Swap Destinations and condition...
11299       BI.setCondition(NewSCC);
11300       BI.setSuccessor(0, FalseDest);
11301       BI.setSuccessor(1, TrueDest);
11302       RemoveFromWorkList(I);
11303       I->eraseFromParent();;
11304       AddToWorkList(NewSCC);
11305       return &BI;
11306     }
11307
11308   return 0;
11309 }
11310
11311 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11312   Value *Cond = SI.getCondition();
11313   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11314     if (I->getOpcode() == Instruction::Add)
11315       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11316         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11317         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11318           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11319                                                 AddRHS));
11320         SI.setOperand(0, I->getOperand(0));
11321         AddToWorkList(I);
11322         return &SI;
11323       }
11324   }
11325   return 0;
11326 }
11327
11328 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11329   Value *Agg = EV.getAggregateOperand();
11330
11331   if (!EV.hasIndices())
11332     return ReplaceInstUsesWith(EV, Agg);
11333
11334   if (Constant *C = dyn_cast<Constant>(Agg)) {
11335     if (isa<UndefValue>(C))
11336       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11337       
11338     if (isa<ConstantAggregateZero>(C))
11339       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11340
11341     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11342       // Extract the element indexed by the first index out of the constant
11343       Value *V = C->getOperand(*EV.idx_begin());
11344       if (EV.getNumIndices() > 1)
11345         // Extract the remaining indices out of the constant indexed by the
11346         // first index
11347         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11348       else
11349         return ReplaceInstUsesWith(EV, V);
11350     }
11351     return 0; // Can't handle other constants
11352   } 
11353   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11354     // We're extracting from an insertvalue instruction, compare the indices
11355     const unsigned *exti, *exte, *insi, *inse;
11356     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11357          exte = EV.idx_end(), inse = IV->idx_end();
11358          exti != exte && insi != inse;
11359          ++exti, ++insi) {
11360       if (*insi != *exti)
11361         // The insert and extract both reference distinctly different elements.
11362         // This means the extract is not influenced by the insert, and we can
11363         // replace the aggregate operand of the extract with the aggregate
11364         // operand of the insert. i.e., replace
11365         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11366         // %E = extractvalue { i32, { i32 } } %I, 0
11367         // with
11368         // %E = extractvalue { i32, { i32 } } %A, 0
11369         return ExtractValueInst::Create(IV->getAggregateOperand(),
11370                                         EV.idx_begin(), EV.idx_end());
11371     }
11372     if (exti == exte && insi == inse)
11373       // Both iterators are at the end: Index lists are identical. Replace
11374       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11375       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11376       // with "i32 42"
11377       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11378     if (exti == exte) {
11379       // The extract list is a prefix of the insert list. i.e. replace
11380       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11381       // %E = extractvalue { i32, { i32 } } %I, 1
11382       // with
11383       // %X = extractvalue { i32, { i32 } } %A, 1
11384       // %E = insertvalue { i32 } %X, i32 42, 0
11385       // by switching the order of the insert and extract (though the
11386       // insertvalue should be left in, since it may have other uses).
11387       Value *NewEV = InsertNewInstBefore(
11388         ExtractValueInst::Create(IV->getAggregateOperand(),
11389                                  EV.idx_begin(), EV.idx_end()),
11390         EV);
11391       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11392                                      insi, inse);
11393     }
11394     if (insi == inse)
11395       // The insert list is a prefix of the extract list
11396       // We can simply remove the common indices from the extract and make it
11397       // operate on the inserted value instead of the insertvalue result.
11398       // i.e., replace
11399       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11400       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11401       // with
11402       // %E extractvalue { i32 } { i32 42 }, 0
11403       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11404                                       exti, exte);
11405   }
11406   // Can't simplify extracts from other values. Note that nested extracts are
11407   // already simplified implicitely by the above (extract ( extract (insert) )
11408   // will be translated into extract ( insert ( extract ) ) first and then just
11409   // the value inserted, if appropriate).
11410   return 0;
11411 }
11412
11413 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11414 /// is to leave as a vector operation.
11415 static bool CheapToScalarize(Value *V, bool isConstant) {
11416   if (isa<ConstantAggregateZero>(V)) 
11417     return true;
11418   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11419     if (isConstant) return true;
11420     // If all elts are the same, we can extract.
11421     Constant *Op0 = C->getOperand(0);
11422     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11423       if (C->getOperand(i) != Op0)
11424         return false;
11425     return true;
11426   }
11427   Instruction *I = dyn_cast<Instruction>(V);
11428   if (!I) return false;
11429   
11430   // Insert element gets simplified to the inserted element or is deleted if
11431   // this is constant idx extract element and its a constant idx insertelt.
11432   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11433       isa<ConstantInt>(I->getOperand(2)))
11434     return true;
11435   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11436     return true;
11437   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11438     if (BO->hasOneUse() &&
11439         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11440          CheapToScalarize(BO->getOperand(1), isConstant)))
11441       return true;
11442   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11443     if (CI->hasOneUse() &&
11444         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11445          CheapToScalarize(CI->getOperand(1), isConstant)))
11446       return true;
11447   
11448   return false;
11449 }
11450
11451 /// Read and decode a shufflevector mask.
11452 ///
11453 /// It turns undef elements into values that are larger than the number of
11454 /// elements in the input.
11455 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11456   unsigned NElts = SVI->getType()->getNumElements();
11457   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11458     return std::vector<unsigned>(NElts, 0);
11459   if (isa<UndefValue>(SVI->getOperand(2)))
11460     return std::vector<unsigned>(NElts, 2*NElts);
11461
11462   std::vector<unsigned> Result;
11463   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11464   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11465     if (isa<UndefValue>(*i))
11466       Result.push_back(NElts*2);  // undef -> 8
11467     else
11468       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11469   return Result;
11470 }
11471
11472 /// FindScalarElement - Given a vector and an element number, see if the scalar
11473 /// value is already around as a register, for example if it were inserted then
11474 /// extracted from the vector.
11475 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11476   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11477   const VectorType *PTy = cast<VectorType>(V->getType());
11478   unsigned Width = PTy->getNumElements();
11479   if (EltNo >= Width)  // Out of range access.
11480     return UndefValue::get(PTy->getElementType());
11481   
11482   if (isa<UndefValue>(V))
11483     return UndefValue::get(PTy->getElementType());
11484   else if (isa<ConstantAggregateZero>(V))
11485     return Constant::getNullValue(PTy->getElementType());
11486   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11487     return CP->getOperand(EltNo);
11488   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11489     // If this is an insert to a variable element, we don't know what it is.
11490     if (!isa<ConstantInt>(III->getOperand(2))) 
11491       return 0;
11492     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11493     
11494     // If this is an insert to the element we are looking for, return the
11495     // inserted value.
11496     if (EltNo == IIElt) 
11497       return III->getOperand(1);
11498     
11499     // Otherwise, the insertelement doesn't modify the value, recurse on its
11500     // vector input.
11501     return FindScalarElement(III->getOperand(0), EltNo);
11502   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11503     unsigned LHSWidth =
11504       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11505     unsigned InEl = getShuffleMask(SVI)[EltNo];
11506     if (InEl < LHSWidth)
11507       return FindScalarElement(SVI->getOperand(0), InEl);
11508     else if (InEl < LHSWidth*2)
11509       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11510     else
11511       return UndefValue::get(PTy->getElementType());
11512   }
11513   
11514   // Otherwise, we don't know.
11515   return 0;
11516 }
11517
11518 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11519   // If vector val is undef, replace extract with scalar undef.
11520   if (isa<UndefValue>(EI.getOperand(0)))
11521     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11522
11523   // If vector val is constant 0, replace extract with scalar 0.
11524   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11525     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11526   
11527   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11528     // If vector val is constant with all elements the same, replace EI with
11529     // that element. When the elements are not identical, we cannot replace yet
11530     // (we do that below, but only when the index is constant).
11531     Constant *op0 = C->getOperand(0);
11532     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11533       if (C->getOperand(i) != op0) {
11534         op0 = 0; 
11535         break;
11536       }
11537     if (op0)
11538       return ReplaceInstUsesWith(EI, op0);
11539   }
11540   
11541   // If extracting a specified index from the vector, see if we can recursively
11542   // find a previously computed scalar that was inserted into the vector.
11543   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11544     unsigned IndexVal = IdxC->getZExtValue();
11545     unsigned VectorWidth = 
11546       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11547       
11548     // If this is extracting an invalid index, turn this into undef, to avoid
11549     // crashing the code below.
11550     if (IndexVal >= VectorWidth)
11551       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11552     
11553     // This instruction only demands the single element from the input vector.
11554     // If the input vector has a single use, simplify it based on this use
11555     // property.
11556     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11557       uint64_t UndefElts;
11558       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11559                                                 1 << IndexVal,
11560                                                 UndefElts)) {
11561         EI.setOperand(0, V);
11562         return &EI;
11563       }
11564     }
11565     
11566     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11567       return ReplaceInstUsesWith(EI, Elt);
11568     
11569     // If the this extractelement is directly using a bitcast from a vector of
11570     // the same number of elements, see if we can find the source element from
11571     // it.  In this case, we will end up needing to bitcast the scalars.
11572     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11573       if (const VectorType *VT = 
11574               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11575         if (VT->getNumElements() == VectorWidth)
11576           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11577             return new BitCastInst(Elt, EI.getType());
11578     }
11579   }
11580   
11581   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11582     if (I->hasOneUse()) {
11583       // Push extractelement into predecessor operation if legal and
11584       // profitable to do so
11585       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11586         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11587         if (CheapToScalarize(BO, isConstantElt)) {
11588           ExtractElementInst *newEI0 = 
11589             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11590                                    EI.getName()+".lhs");
11591           ExtractElementInst *newEI1 =
11592             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11593                                    EI.getName()+".rhs");
11594           InsertNewInstBefore(newEI0, EI);
11595           InsertNewInstBefore(newEI1, EI);
11596           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11597         }
11598       } else if (isa<LoadInst>(I)) {
11599         unsigned AS = 
11600           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11601         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11602                                          PointerType::get(EI.getType(), AS),EI);
11603         GetElementPtrInst *GEP =
11604           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11605         InsertNewInstBefore(GEP, EI);
11606         return new LoadInst(GEP);
11607       }
11608     }
11609     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11610       // Extracting the inserted element?
11611       if (IE->getOperand(2) == EI.getOperand(1))
11612         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11613       // If the inserted and extracted elements are constants, they must not
11614       // be the same value, extract from the pre-inserted value instead.
11615       if (isa<Constant>(IE->getOperand(2)) &&
11616           isa<Constant>(EI.getOperand(1))) {
11617         AddUsesToWorkList(EI);
11618         EI.setOperand(0, IE->getOperand(0));
11619         return &EI;
11620       }
11621     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11622       // If this is extracting an element from a shufflevector, figure out where
11623       // it came from and extract from the appropriate input element instead.
11624       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11625         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11626         Value *Src;
11627         unsigned LHSWidth =
11628           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11629
11630         if (SrcIdx < LHSWidth)
11631           Src = SVI->getOperand(0);
11632         else if (SrcIdx < LHSWidth*2) {
11633           SrcIdx -= LHSWidth;
11634           Src = SVI->getOperand(1);
11635         } else {
11636           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11637         }
11638         return new ExtractElementInst(Src, SrcIdx);
11639       }
11640     }
11641   }
11642   return 0;
11643 }
11644
11645 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11646 /// elements from either LHS or RHS, return the shuffle mask and true. 
11647 /// Otherwise, return false.
11648 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11649                                          std::vector<Constant*> &Mask) {
11650   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11651          "Invalid CollectSingleShuffleElements");
11652   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11653
11654   if (isa<UndefValue>(V)) {
11655     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11656     return true;
11657   } else if (V == LHS) {
11658     for (unsigned i = 0; i != NumElts; ++i)
11659       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11660     return true;
11661   } else if (V == RHS) {
11662     for (unsigned i = 0; i != NumElts; ++i)
11663       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11664     return true;
11665   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11666     // If this is an insert of an extract from some other vector, include it.
11667     Value *VecOp    = IEI->getOperand(0);
11668     Value *ScalarOp = IEI->getOperand(1);
11669     Value *IdxOp    = IEI->getOperand(2);
11670     
11671     if (!isa<ConstantInt>(IdxOp))
11672       return false;
11673     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11674     
11675     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11676       // Okay, we can handle this if the vector we are insertinting into is
11677       // transitively ok.
11678       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11679         // If so, update the mask to reflect the inserted undef.
11680         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11681         return true;
11682       }      
11683     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11684       if (isa<ConstantInt>(EI->getOperand(1)) &&
11685           EI->getOperand(0)->getType() == V->getType()) {
11686         unsigned ExtractedIdx =
11687           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11688         
11689         // This must be extracting from either LHS or RHS.
11690         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11691           // Okay, we can handle this if the vector we are insertinting into is
11692           // transitively ok.
11693           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11694             // If so, update the mask to reflect the inserted value.
11695             if (EI->getOperand(0) == LHS) {
11696               Mask[InsertedIdx % NumElts] = 
11697                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11698             } else {
11699               assert(EI->getOperand(0) == RHS);
11700               Mask[InsertedIdx % NumElts] = 
11701                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11702               
11703             }
11704             return true;
11705           }
11706         }
11707       }
11708     }
11709   }
11710   // TODO: Handle shufflevector here!
11711   
11712   return false;
11713 }
11714
11715 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11716 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11717 /// that computes V and the LHS value of the shuffle.
11718 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11719                                      Value *&RHS) {
11720   assert(isa<VectorType>(V->getType()) && 
11721          (RHS == 0 || V->getType() == RHS->getType()) &&
11722          "Invalid shuffle!");
11723   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11724
11725   if (isa<UndefValue>(V)) {
11726     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11727     return V;
11728   } else if (isa<ConstantAggregateZero>(V)) {
11729     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11730     return V;
11731   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11732     // If this is an insert of an extract from some other vector, include it.
11733     Value *VecOp    = IEI->getOperand(0);
11734     Value *ScalarOp = IEI->getOperand(1);
11735     Value *IdxOp    = IEI->getOperand(2);
11736     
11737     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11738       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11739           EI->getOperand(0)->getType() == V->getType()) {
11740         unsigned ExtractedIdx =
11741           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11742         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11743         
11744         // Either the extracted from or inserted into vector must be RHSVec,
11745         // otherwise we'd end up with a shuffle of three inputs.
11746         if (EI->getOperand(0) == RHS || RHS == 0) {
11747           RHS = EI->getOperand(0);
11748           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11749           Mask[InsertedIdx % NumElts] = 
11750             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11751           return V;
11752         }
11753         
11754         if (VecOp == RHS) {
11755           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11756           // Everything but the extracted element is replaced with the RHS.
11757           for (unsigned i = 0; i != NumElts; ++i) {
11758             if (i != InsertedIdx)
11759               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11760           }
11761           return V;
11762         }
11763         
11764         // If this insertelement is a chain that comes from exactly these two
11765         // vectors, return the vector and the effective shuffle.
11766         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11767           return EI->getOperand(0);
11768         
11769       }
11770     }
11771   }
11772   // TODO: Handle shufflevector here!
11773   
11774   // Otherwise, can't do anything fancy.  Return an identity vector.
11775   for (unsigned i = 0; i != NumElts; ++i)
11776     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11777   return V;
11778 }
11779
11780 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11781   Value *VecOp    = IE.getOperand(0);
11782   Value *ScalarOp = IE.getOperand(1);
11783   Value *IdxOp    = IE.getOperand(2);
11784   
11785   // Inserting an undef or into an undefined place, remove this.
11786   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11787     ReplaceInstUsesWith(IE, VecOp);
11788   
11789   // If the inserted element was extracted from some other vector, and if the 
11790   // indexes are constant, try to turn this into a shufflevector operation.
11791   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11792     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11793         EI->getOperand(0)->getType() == IE.getType()) {
11794       unsigned NumVectorElts = IE.getType()->getNumElements();
11795       unsigned ExtractedIdx =
11796         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11797       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11798       
11799       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11800         return ReplaceInstUsesWith(IE, VecOp);
11801       
11802       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11803         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11804       
11805       // If we are extracting a value from a vector, then inserting it right
11806       // back into the same place, just use the input vector.
11807       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11808         return ReplaceInstUsesWith(IE, VecOp);      
11809       
11810       // We could theoretically do this for ANY input.  However, doing so could
11811       // turn chains of insertelement instructions into a chain of shufflevector
11812       // instructions, and right now we do not merge shufflevectors.  As such,
11813       // only do this in a situation where it is clear that there is benefit.
11814       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11815         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11816         // the values of VecOp, except then one read from EIOp0.
11817         // Build a new shuffle mask.
11818         std::vector<Constant*> Mask;
11819         if (isa<UndefValue>(VecOp))
11820           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11821         else {
11822           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11823           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11824                                                        NumVectorElts));
11825         } 
11826         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11827         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11828                                      ConstantVector::get(Mask));
11829       }
11830       
11831       // If this insertelement isn't used by some other insertelement, turn it
11832       // (and any insertelements it points to), into one big shuffle.
11833       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11834         std::vector<Constant*> Mask;
11835         Value *RHS = 0;
11836         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11837         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11838         // We now have a shuffle of LHS, RHS, Mask.
11839         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11840       }
11841     }
11842   }
11843
11844   return 0;
11845 }
11846
11847
11848 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11849   Value *LHS = SVI.getOperand(0);
11850   Value *RHS = SVI.getOperand(1);
11851   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11852
11853   bool MadeChange = false;
11854
11855   // Undefined shuffle mask -> undefined value.
11856   if (isa<UndefValue>(SVI.getOperand(2)))
11857     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11858
11859   uint64_t UndefElts;
11860   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
11861
11862   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
11863     return 0;
11864
11865   uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
11866   if (VWidth <= 64 &&
11867       SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11868     LHS = SVI.getOperand(0);
11869     RHS = SVI.getOperand(1);
11870     MadeChange = true;
11871   }
11872   
11873   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11874   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11875   if (LHS == RHS || isa<UndefValue>(LHS)) {
11876     if (isa<UndefValue>(LHS) && LHS == RHS) {
11877       // shuffle(undef,undef,mask) -> undef.
11878       return ReplaceInstUsesWith(SVI, LHS);
11879     }
11880     
11881     // Remap any references to RHS to use LHS.
11882     std::vector<Constant*> Elts;
11883     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11884       if (Mask[i] >= 2*e)
11885         Elts.push_back(UndefValue::get(Type::Int32Ty));
11886       else {
11887         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11888             (Mask[i] <  e && isa<UndefValue>(LHS))) {
11889           Mask[i] = 2*e;     // Turn into undef.
11890           Elts.push_back(UndefValue::get(Type::Int32Ty));
11891         } else {
11892           Mask[i] = Mask[i] % e;  // Force to LHS.
11893           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11894         }
11895       }
11896     }
11897     SVI.setOperand(0, SVI.getOperand(1));
11898     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11899     SVI.setOperand(2, ConstantVector::get(Elts));
11900     LHS = SVI.getOperand(0);
11901     RHS = SVI.getOperand(1);
11902     MadeChange = true;
11903   }
11904   
11905   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11906   bool isLHSID = true, isRHSID = true;
11907     
11908   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11909     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11910     // Is this an identity shuffle of the LHS value?
11911     isLHSID &= (Mask[i] == i);
11912       
11913     // Is this an identity shuffle of the RHS value?
11914     isRHSID &= (Mask[i]-e == i);
11915   }
11916
11917   // Eliminate identity shuffles.
11918   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11919   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11920   
11921   // If the LHS is a shufflevector itself, see if we can combine it with this
11922   // one without producing an unusual shuffle.  Here we are really conservative:
11923   // we are absolutely afraid of producing a shuffle mask not in the input
11924   // program, because the code gen may not be smart enough to turn a merged
11925   // shuffle into two specific shuffles: it may produce worse code.  As such,
11926   // we only merge two shuffles if the result is one of the two input shuffle
11927   // masks.  In this case, merging the shuffles just removes one instruction,
11928   // which we know is safe.  This is good for things like turning:
11929   // (splat(splat)) -> splat.
11930   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11931     if (isa<UndefValue>(RHS)) {
11932       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11933
11934       std::vector<unsigned> NewMask;
11935       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11936         if (Mask[i] >= 2*e)
11937           NewMask.push_back(2*e);
11938         else
11939           NewMask.push_back(LHSMask[Mask[i]]);
11940       
11941       // If the result mask is equal to the src shuffle or this shuffle mask, do
11942       // the replacement.
11943       if (NewMask == LHSMask || NewMask == Mask) {
11944         std::vector<Constant*> Elts;
11945         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11946           if (NewMask[i] >= e*2) {
11947             Elts.push_back(UndefValue::get(Type::Int32Ty));
11948           } else {
11949             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11950           }
11951         }
11952         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11953                                      LHSSVI->getOperand(1),
11954                                      ConstantVector::get(Elts));
11955       }
11956     }
11957   }
11958
11959   return MadeChange ? &SVI : 0;
11960 }
11961
11962
11963
11964
11965 /// TryToSinkInstruction - Try to move the specified instruction from its
11966 /// current block into the beginning of DestBlock, which can only happen if it's
11967 /// safe to move the instruction past all of the instructions between it and the
11968 /// end of its block.
11969 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11970   assert(I->hasOneUse() && "Invariants didn't hold!");
11971
11972   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11973   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11974     return false;
11975
11976   // Do not sink alloca instructions out of the entry block.
11977   if (isa<AllocaInst>(I) && I->getParent() ==
11978         &DestBlock->getParent()->getEntryBlock())
11979     return false;
11980
11981   // We can only sink load instructions if there is nothing between the load and
11982   // the end of block that could change the value.
11983   if (I->mayReadFromMemory()) {
11984     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11985          Scan != E; ++Scan)
11986       if (Scan->mayWriteToMemory())
11987         return false;
11988   }
11989
11990   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11991
11992   I->moveBefore(InsertPos);
11993   ++NumSunkInst;
11994   return true;
11995 }
11996
11997
11998 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11999 /// all reachable code to the worklist.
12000 ///
12001 /// This has a couple of tricks to make the code faster and more powerful.  In
12002 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12003 /// them to the worklist (this significantly speeds up instcombine on code where
12004 /// many instructions are dead or constant).  Additionally, if we find a branch
12005 /// whose condition is a known constant, we only visit the reachable successors.
12006 ///
12007 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12008                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12009                                        InstCombiner &IC,
12010                                        const TargetData *TD) {
12011   SmallVector<BasicBlock*, 256> Worklist;
12012   Worklist.push_back(BB);
12013
12014   while (!Worklist.empty()) {
12015     BB = Worklist.back();
12016     Worklist.pop_back();
12017     
12018     // We have now visited this block!  If we've already been here, ignore it.
12019     if (!Visited.insert(BB)) continue;
12020
12021     DbgInfoIntrinsic *DBI_Prev = NULL;
12022     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12023       Instruction *Inst = BBI++;
12024       
12025       // DCE instruction if trivially dead.
12026       if (isInstructionTriviallyDead(Inst)) {
12027         ++NumDeadInst;
12028         DOUT << "IC: DCE: " << *Inst;
12029         Inst->eraseFromParent();
12030         continue;
12031       }
12032       
12033       // ConstantProp instruction if trivially constant.
12034       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12035         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12036         Inst->replaceAllUsesWith(C);
12037         ++NumConstProp;
12038         Inst->eraseFromParent();
12039         continue;
12040       }
12041      
12042       // If there are two consecutive llvm.dbg.stoppoint calls then
12043       // it is likely that the optimizer deleted code in between these
12044       // two intrinsics. 
12045       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12046       if (DBI_Next) {
12047         if (DBI_Prev
12048             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12049             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12050           IC.RemoveFromWorkList(DBI_Prev);
12051           DBI_Prev->eraseFromParent();
12052         }
12053         DBI_Prev = DBI_Next;
12054       }
12055
12056       IC.AddToWorkList(Inst);
12057     }
12058
12059     // Recursively visit successors.  If this is a branch or switch on a
12060     // constant, only visit the reachable successor.
12061     TerminatorInst *TI = BB->getTerminator();
12062     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12063       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12064         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12065         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12066         Worklist.push_back(ReachableBB);
12067         continue;
12068       }
12069     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12070       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12071         // See if this is an explicit destination.
12072         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12073           if (SI->getCaseValue(i) == Cond) {
12074             BasicBlock *ReachableBB = SI->getSuccessor(i);
12075             Worklist.push_back(ReachableBB);
12076             continue;
12077           }
12078         
12079         // Otherwise it is the default destination.
12080         Worklist.push_back(SI->getSuccessor(0));
12081         continue;
12082       }
12083     }
12084     
12085     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12086       Worklist.push_back(TI->getSuccessor(i));
12087   }
12088 }
12089
12090 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12091   bool Changed = false;
12092   TD = &getAnalysis<TargetData>();
12093   
12094   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12095              << F.getNameStr() << "\n");
12096
12097   {
12098     // Do a depth-first traversal of the function, populate the worklist with
12099     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12100     // track of which blocks we visit.
12101     SmallPtrSet<BasicBlock*, 64> Visited;
12102     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12103
12104     // Do a quick scan over the function.  If we find any blocks that are
12105     // unreachable, remove any instructions inside of them.  This prevents
12106     // the instcombine code from having to deal with some bad special cases.
12107     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12108       if (!Visited.count(BB)) {
12109         Instruction *Term = BB->getTerminator();
12110         while (Term != BB->begin()) {   // Remove instrs bottom-up
12111           BasicBlock::iterator I = Term; --I;
12112
12113           DOUT << "IC: DCE: " << *I;
12114           ++NumDeadInst;
12115
12116           if (!I->use_empty())
12117             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12118           I->eraseFromParent();
12119         }
12120       }
12121   }
12122
12123   while (!Worklist.empty()) {
12124     Instruction *I = RemoveOneFromWorkList();
12125     if (I == 0) continue;  // skip null values.
12126
12127     // Check to see if we can DCE the instruction.
12128     if (isInstructionTriviallyDead(I)) {
12129       // Add operands to the worklist.
12130       if (I->getNumOperands() < 4)
12131         AddUsesToWorkList(*I);
12132       ++NumDeadInst;
12133
12134       DOUT << "IC: DCE: " << *I;
12135
12136       I->eraseFromParent();
12137       RemoveFromWorkList(I);
12138       continue;
12139     }
12140
12141     // Instruction isn't dead, see if we can constant propagate it.
12142     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12143       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12144
12145       // Add operands to the worklist.
12146       AddUsesToWorkList(*I);
12147       ReplaceInstUsesWith(*I, C);
12148
12149       ++NumConstProp;
12150       I->eraseFromParent();
12151       RemoveFromWorkList(I);
12152       continue;
12153     }
12154
12155     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12156       // See if we can constant fold its operands.
12157       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12158         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12159           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12160             i->set(NewC);
12161         }
12162       }
12163     }
12164
12165     // See if we can trivially sink this instruction to a successor basic block.
12166     if (I->hasOneUse()) {
12167       BasicBlock *BB = I->getParent();
12168       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12169       if (UserParent != BB) {
12170         bool UserIsSuccessor = false;
12171         // See if the user is one of our successors.
12172         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12173           if (*SI == UserParent) {
12174             UserIsSuccessor = true;
12175             break;
12176           }
12177
12178         // If the user is one of our immediate successors, and if that successor
12179         // only has us as a predecessors (we'd have to split the critical edge
12180         // otherwise), we can keep going.
12181         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12182             next(pred_begin(UserParent)) == pred_end(UserParent))
12183           // Okay, the CFG is simple enough, try to sink this instruction.
12184           Changed |= TryToSinkInstruction(I, UserParent);
12185       }
12186     }
12187
12188     // Now that we have an instruction, try combining it to simplify it...
12189 #ifndef NDEBUG
12190     std::string OrigI;
12191 #endif
12192     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12193     if (Instruction *Result = visit(*I)) {
12194       ++NumCombined;
12195       // Should we replace the old instruction with a new one?
12196       if (Result != I) {
12197         DOUT << "IC: Old = " << *I
12198              << "    New = " << *Result;
12199
12200         // Everything uses the new instruction now.
12201         I->replaceAllUsesWith(Result);
12202
12203         // Push the new instruction and any users onto the worklist.
12204         AddToWorkList(Result);
12205         AddUsersToWorkList(*Result);
12206
12207         // Move the name to the new instruction first.
12208         Result->takeName(I);
12209
12210         // Insert the new instruction into the basic block...
12211         BasicBlock *InstParent = I->getParent();
12212         BasicBlock::iterator InsertPos = I;
12213
12214         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12215           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12216             ++InsertPos;
12217
12218         InstParent->getInstList().insert(InsertPos, Result);
12219
12220         // Make sure that we reprocess all operands now that we reduced their
12221         // use counts.
12222         AddUsesToWorkList(*I);
12223
12224         // Instructions can end up on the worklist more than once.  Make sure
12225         // we do not process an instruction that has been deleted.
12226         RemoveFromWorkList(I);
12227
12228         // Erase the old instruction.
12229         InstParent->getInstList().erase(I);
12230       } else {
12231 #ifndef NDEBUG
12232         DOUT << "IC: Mod = " << OrigI
12233              << "    New = " << *I;
12234 #endif
12235
12236         // If the instruction was modified, it's possible that it is now dead.
12237         // if so, remove it.
12238         if (isInstructionTriviallyDead(I)) {
12239           // Make sure we process all operands now that we are reducing their
12240           // use counts.
12241           AddUsesToWorkList(*I);
12242
12243           // Instructions may end up in the worklist more than once.  Erase all
12244           // occurrences of this instruction.
12245           RemoveFromWorkList(I);
12246           I->eraseFromParent();
12247         } else {
12248           AddToWorkList(I);
12249           AddUsersToWorkList(*I);
12250         }
12251       }
12252       Changed = true;
12253     }
12254   }
12255
12256   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12257     
12258   // Do an explicit clear, this shrinks the map if needed.
12259   WorklistMap.clear();
12260   return Changed;
12261 }
12262
12263
12264 bool InstCombiner::runOnFunction(Function &F) {
12265   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12266   
12267   bool EverMadeChange = false;
12268
12269   // Iterate while there is work to do.
12270   unsigned Iteration = 0;
12271   while (DoOneIteration(F, Iteration++))
12272     EverMadeChange = true;
12273   return EverMadeChange;
12274 }
12275
12276 FunctionPass *llvm::createInstructionCombiningPass() {
12277   return new InstCombiner();
12278 }
12279
12280