Fix typos and whitespaces. Other cosmetic changes based on feedback.
[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((intptr_t)&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).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 *visitAnd(BinaryOperator &I);
184     Instruction *visitOr (BinaryOperator &I);
185     Instruction *visitXor(BinaryOperator &I);
186     Instruction *visitShl(BinaryOperator &I);
187     Instruction *visitAShr(BinaryOperator &I);
188     Instruction *visitLShr(BinaryOperator &I);
189     Instruction *commonShiftTransforms(BinaryOperator &I);
190     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
191                                       Constant *RHSC);
192     Instruction *visitFCmpInst(FCmpInst &I);
193     Instruction *visitICmpInst(ICmpInst &I);
194     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
195     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
196                                                 Instruction *LHS,
197                                                 ConstantInt *RHS);
198     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
199                                 ConstantInt *DivRHS);
200
201     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
202                              ICmpInst::Predicate Cond, Instruction &I);
203     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
204                                      BinaryOperator &I);
205     Instruction *commonCastTransforms(CastInst &CI);
206     Instruction *commonIntCastTransforms(CastInst &CI);
207     Instruction *commonPointerCastTransforms(CastInst &CI);
208     Instruction *visitTrunc(TruncInst &CI);
209     Instruction *visitZExt(ZExtInst &CI);
210     Instruction *visitSExt(SExtInst &CI);
211     Instruction *visitFPTrunc(FPTruncInst &CI);
212     Instruction *visitFPExt(CastInst &CI);
213     Instruction *visitFPToUI(FPToUIInst &FI);
214     Instruction *visitFPToSI(FPToSIInst &FI);
215     Instruction *visitUIToFP(CastInst &CI);
216     Instruction *visitSIToFP(CastInst &CI);
217     Instruction *visitPtrToInt(CastInst &CI);
218     Instruction *visitIntToPtr(IntToPtrInst &CI);
219     Instruction *visitBitCast(BitCastInst &CI);
220     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
221                                 Instruction *FI);
222     Instruction *visitSelectInst(SelectInst &CI);
223     Instruction *visitCallInst(CallInst &CI);
224     Instruction *visitInvokeInst(InvokeInst &II);
225     Instruction *visitPHINode(PHINode &PN);
226     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
227     Instruction *visitAllocationInst(AllocationInst &AI);
228     Instruction *visitFreeInst(FreeInst &FI);
229     Instruction *visitLoadInst(LoadInst &LI);
230     Instruction *visitStoreInst(StoreInst &SI);
231     Instruction *visitBranchInst(BranchInst &BI);
232     Instruction *visitSwitchInst(SwitchInst &SI);
233     Instruction *visitInsertElementInst(InsertElementInst &IE);
234     Instruction *visitExtractElementInst(ExtractElementInst &EI);
235     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
236     Instruction *visitExtractValueInst(ExtractValueInst &EV);
237
238     // visitInstruction - Specify what to return for unhandled instructions...
239     Instruction *visitInstruction(Instruction &I) { return 0; }
240
241   private:
242     Instruction *visitCallSite(CallSite CS);
243     bool transformConstExprCastCall(CallSite CS);
244     Instruction *transformCallThroughTrampoline(CallSite CS);
245     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
246                                    bool DoXform = true);
247     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
248
249   public:
250     // InsertNewInstBefore - insert an instruction New before instruction Old
251     // in the program.  Add the new instruction to the worklist.
252     //
253     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
254       assert(New && New->getParent() == 0 &&
255              "New instruction already inserted into a basic block!");
256       BasicBlock *BB = Old.getParent();
257       BB->getInstList().insert(&Old, New);  // Insert inst
258       AddToWorkList(New);
259       return New;
260     }
261
262     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
263     /// This also adds the cast to the worklist.  Finally, this returns the
264     /// cast.
265     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
266                             Instruction &Pos) {
267       if (V->getType() == Ty) return V;
268
269       if (Constant *CV = dyn_cast<Constant>(V))
270         return ConstantExpr::getCast(opc, CV, Ty);
271       
272       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
273       AddToWorkList(C);
274       return C;
275     }
276         
277     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
278       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
279     }
280
281
282     // ReplaceInstUsesWith - This method is to be used when an instruction is
283     // found to be dead, replacable with another preexisting expression.  Here
284     // we add all uses of I to the worklist, replace all uses of I with the new
285     // value, then return I, so that the inst combiner will know that I was
286     // modified.
287     //
288     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
289       AddUsersToWorkList(I);         // Add all modified instrs to worklist
290       if (&I != V) {
291         I.replaceAllUsesWith(V);
292         return &I;
293       } else {
294         // If we are replacing the instruction with itself, this must be in a
295         // segment of unreachable code, so just clobber the instruction.
296         I.replaceAllUsesWith(UndefValue::get(I.getType()));
297         return &I;
298       }
299     }
300
301     // UpdateValueUsesWith - This method is to be used when an value is
302     // found to be replacable with another preexisting expression or was
303     // updated.  Here we add all uses of I to the worklist, replace all uses of
304     // I with the new value (unless the instruction was just updated), then
305     // return true, so that the inst combiner will know that I was modified.
306     //
307     bool UpdateValueUsesWith(Value *Old, Value *New) {
308       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
309       if (Old != New)
310         Old->replaceAllUsesWith(New);
311       if (Instruction *I = dyn_cast<Instruction>(Old))
312         AddToWorkList(I);
313       if (Instruction *I = dyn_cast<Instruction>(New))
314         AddToWorkList(I);
315       return true;
316     }
317     
318     // EraseInstFromFunction - When dealing with an instruction that has side
319     // effects or produces a void value, we can't rely on DCE to delete the
320     // instruction.  Instead, visit methods should return the value returned by
321     // this function.
322     Instruction *EraseInstFromFunction(Instruction &I) {
323       assert(I.use_empty() && "Cannot erase instruction that is used!");
324       AddUsesToWorkList(I);
325       RemoveFromWorkList(&I);
326       I.eraseFromParent();
327       return 0;  // Don't do anything with FI
328     }
329         
330     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
331                            APInt &KnownOne, unsigned Depth = 0) const {
332       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
333     }
334     
335     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
336                            unsigned Depth = 0) const {
337       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
338     }
339     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
340       return llvm::ComputeNumSignBits(Op, TD, Depth);
341     }
342
343   private:
344     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
345     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
346     /// casts that are known to not do anything...
347     ///
348     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
349                                    Value *V, const Type *DestTy,
350                                    Instruction *InsertBefore);
351
352     /// SimplifyCommutative - This performs a few simplifications for 
353     /// commutative operators.
354     bool SimplifyCommutative(BinaryOperator &I);
355
356     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
357     /// most-complex to least-complex order.
358     bool SimplifyCompare(CmpInst &I);
359
360     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
361     /// on the demanded bits.
362     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
363                               APInt& KnownZero, APInt& KnownOne,
364                               unsigned Depth = 0);
365
366     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
367                                       uint64_t &UndefElts, unsigned Depth = 0);
368       
369     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370     // PHI node as operand #0, see if we can fold the instruction into the PHI
371     // (which is only possible if all operands to the PHI are constants).
372     Instruction *FoldOpIntoPhi(Instruction &I);
373
374     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375     // operator and they all are only used by the PHI, PHI together their
376     // inputs, and do the operation once, to the result of the PHI.
377     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
378     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
379     
380     
381     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
383     
384     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
385                               bool isSub, Instruction &I);
386     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
387                                  bool isSigned, bool Inside, Instruction &IB);
388     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
389     Instruction *MatchBSwap(BinaryOperator &I);
390     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
391     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
392     Instruction *SimplifyMemSet(MemSetInst *MI);
393
394
395     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
396
397     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
398                                     unsigned CastOpc,
399                                     int &NumCastsRemoved);
400     unsigned GetOrEnforceKnownAlignment(Value *V,
401                                         unsigned PrefAlign = 0);
402
403   };
404 }
405
406 char InstCombiner::ID = 0;
407 static RegisterPass<InstCombiner>
408 X("instcombine", "Combine redundant instructions");
409
410 // getComplexity:  Assign a complexity or rank value to LLVM Values...
411 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
412 static unsigned getComplexity(Value *V) {
413   if (isa<Instruction>(V)) {
414     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
415       return 3;
416     return 4;
417   }
418   if (isa<Argument>(V)) return 3;
419   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
420 }
421
422 // isOnlyUse - Return true if this instruction will be deleted if we stop using
423 // it.
424 static bool isOnlyUse(Value *V) {
425   return V->hasOneUse() || isa<Constant>(V);
426 }
427
428 // getPromotedType - Return the specified type promoted as it would be to pass
429 // though a va_arg area...
430 static const Type *getPromotedType(const Type *Ty) {
431   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
432     if (ITy->getBitWidth() < 32)
433       return Type::Int32Ty;
434   }
435   return Ty;
436 }
437
438 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
439 /// expression bitcast,  return the operand value, otherwise return null.
440 static Value *getBitCastOperand(Value *V) {
441   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
442     return I->getOperand(0);
443   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
444     if (CE->getOpcode() == Instruction::BitCast)
445       return CE->getOperand(0);
446   return 0;
447 }
448
449 /// This function is a wrapper around CastInst::isEliminableCastPair. It
450 /// simply extracts arguments and returns what that function returns.
451 static Instruction::CastOps 
452 isEliminableCastPair(
453   const CastInst *CI, ///< The first cast instruction
454   unsigned opcode,       ///< The opcode of the second cast instruction
455   const Type *DstTy,     ///< The target type for the second cast instruction
456   TargetData *TD         ///< The target data for pointer size
457 ) {
458   
459   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
460   const Type *MidTy = CI->getType();                  // B from above
461
462   // Get the opcodes of the two Cast instructions
463   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
464   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
465
466   return Instruction::CastOps(
467       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
468                                      DstTy, TD->getIntPtrType()));
469 }
470
471 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
472 /// in any code being generated.  It does not require codegen if V is simple
473 /// enough or if the cast can be folded into other casts.
474 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
475                               const Type *Ty, TargetData *TD) {
476   if (V->getType() == Ty || isa<Constant>(V)) return false;
477   
478   // If this is another cast that can be eliminated, it isn't codegen either.
479   if (const CastInst *CI = dyn_cast<CastInst>(V))
480     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
481       return false;
482   return true;
483 }
484
485 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
486 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
487 /// casts that are known to not do anything...
488 ///
489 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
490                                              Value *V, const Type *DestTy,
491                                              Instruction *InsertBefore) {
492   if (V->getType() == DestTy) return V;
493   if (Constant *C = dyn_cast<Constant>(V))
494     return ConstantExpr::getCast(opcode, C, DestTy);
495   
496   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
497 }
498
499 // SimplifyCommutative - This performs a few simplifications for commutative
500 // operators:
501 //
502 //  1. Order operands such that they are listed from right (least complex) to
503 //     left (most complex).  This puts constants before unary operators before
504 //     binary operators.
505 //
506 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
507 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
508 //
509 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
510   bool Changed = false;
511   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
512     Changed = !I.swapOperands();
513
514   if (!I.isAssociative()) return Changed;
515   Instruction::BinaryOps Opcode = I.getOpcode();
516   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
517     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
518       if (isa<Constant>(I.getOperand(1))) {
519         Constant *Folded = ConstantExpr::get(I.getOpcode(),
520                                              cast<Constant>(I.getOperand(1)),
521                                              cast<Constant>(Op->getOperand(1)));
522         I.setOperand(0, Op->getOperand(0));
523         I.setOperand(1, Folded);
524         return true;
525       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
526         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
527             isOnlyUse(Op) && isOnlyUse(Op1)) {
528           Constant *C1 = cast<Constant>(Op->getOperand(1));
529           Constant *C2 = cast<Constant>(Op1->getOperand(1));
530
531           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
532           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
533           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
534                                                     Op1->getOperand(0),
535                                                     Op1->getName(), &I);
536           AddToWorkList(New);
537           I.setOperand(0, New);
538           I.setOperand(1, Folded);
539           return true;
540         }
541     }
542   return Changed;
543 }
544
545 /// SimplifyCompare - For a CmpInst this function just orders the operands
546 /// so that theyare listed from right (least complex) to left (most complex).
547 /// This puts constants before unary operators before binary operators.
548 bool InstCombiner::SimplifyCompare(CmpInst &I) {
549   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
550     return false;
551   I.swapOperands();
552   // Compare instructions are not associative so there's nothing else we can do.
553   return true;
554 }
555
556 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
557 // if the LHS is a constant zero (which is the 'negate' form).
558 //
559 static inline Value *dyn_castNegVal(Value *V) {
560   if (BinaryOperator::isNeg(V))
561     return BinaryOperator::getNegArgument(V);
562
563   // Constants can be considered to be negated values if they can be folded.
564   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
565     return ConstantExpr::getNeg(C);
566
567   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
568     if (C->getType()->getElementType()->isInteger())
569       return ConstantExpr::getNeg(C);
570
571   return 0;
572 }
573
574 static inline Value *dyn_castNotVal(Value *V) {
575   if (BinaryOperator::isNot(V))
576     return BinaryOperator::getNotArgument(V);
577
578   // Constants can be considered to be not'ed values...
579   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
580     return ConstantInt::get(~C->getValue());
581   return 0;
582 }
583
584 // dyn_castFoldableMul - If this value is a multiply that can be folded into
585 // other computations (because it has a constant operand), return the
586 // non-constant operand of the multiply, and set CST to point to the multiplier.
587 // Otherwise, return null.
588 //
589 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
590   if (V->hasOneUse() && V->getType()->isInteger())
591     if (Instruction *I = dyn_cast<Instruction>(V)) {
592       if (I->getOpcode() == Instruction::Mul)
593         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
594           return I->getOperand(0);
595       if (I->getOpcode() == Instruction::Shl)
596         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
597           // The multiplier is really 1 << CST.
598           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
599           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
600           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
601           return I->getOperand(0);
602         }
603     }
604   return 0;
605 }
606
607 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
608 /// expression, return it.
609 static User *dyn_castGetElementPtr(Value *V) {
610   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
611   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
612     if (CE->getOpcode() == Instruction::GetElementPtr)
613       return cast<User>(V);
614   return false;
615 }
616
617 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
618 /// opcode value. Otherwise return UserOp1.
619 static unsigned getOpcode(const Value *V) {
620   if (const Instruction *I = dyn_cast<Instruction>(V))
621     return I->getOpcode();
622   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
623     return CE->getOpcode();
624   // Use UserOp1 to mean there's no opcode.
625   return Instruction::UserOp1;
626 }
627
628 /// AddOne - Add one to a ConstantInt
629 static ConstantInt *AddOne(ConstantInt *C) {
630   APInt Val(C->getValue());
631   return ConstantInt::get(++Val);
632 }
633 /// SubOne - Subtract one from a ConstantInt
634 static ConstantInt *SubOne(ConstantInt *C) {
635   APInt Val(C->getValue());
636   return ConstantInt::get(--Val);
637 }
638 /// Add - Add two ConstantInts together
639 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
640   return ConstantInt::get(C1->getValue() + C2->getValue());
641 }
642 /// And - Bitwise AND two ConstantInts together
643 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
644   return ConstantInt::get(C1->getValue() & C2->getValue());
645 }
646 /// Subtract - Subtract one ConstantInt from another
647 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
648   return ConstantInt::get(C1->getValue() - C2->getValue());
649 }
650 /// Multiply - Multiply two ConstantInts together
651 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
652   return ConstantInt::get(C1->getValue() * C2->getValue());
653 }
654 /// MultiplyOverflows - True if the multiply can not be expressed in an int
655 /// this size.
656 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
657   uint32_t W = C1->getBitWidth();
658   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
659   if (sign) {
660     LHSExt.sext(W * 2);
661     RHSExt.sext(W * 2);
662   } else {
663     LHSExt.zext(W * 2);
664     RHSExt.zext(W * 2);
665   }
666
667   APInt MulExt = LHSExt * RHSExt;
668
669   if (sign) {
670     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
671     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
672     return MulExt.slt(Min) || MulExt.sgt(Max);
673   } else 
674     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
675 }
676
677
678 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
679 /// specified instruction is a constant integer.  If so, check to see if there
680 /// are any bits set in the constant that are not demanded.  If so, shrink the
681 /// constant and return true.
682 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
683                                    APInt Demanded) {
684   assert(I && "No instruction?");
685   assert(OpNo < I->getNumOperands() && "Operand index too large");
686
687   // If the operand is not a constant integer, nothing to do.
688   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
689   if (!OpC) return false;
690
691   // If there are no bits set that aren't demanded, nothing to do.
692   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
693   if ((~Demanded & OpC->getValue()) == 0)
694     return false;
695
696   // This instruction is producing bits that are not demanded. Shrink the RHS.
697   Demanded &= OpC->getValue();
698   I->setOperand(OpNo, ConstantInt::get(Demanded));
699   return true;
700 }
701
702 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
703 // set of known zero and one bits, compute the maximum and minimum values that
704 // could have the specified known zero and known one bits, returning them in
705 // min/max.
706 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
707                                                    const APInt& KnownZero,
708                                                    const APInt& KnownOne,
709                                                    APInt& Min, APInt& Max) {
710   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
711   assert(KnownZero.getBitWidth() == BitWidth && 
712          KnownOne.getBitWidth() == BitWidth &&
713          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
714          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
715   APInt UnknownBits = ~(KnownZero|KnownOne);
716
717   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
718   // bit if it is unknown.
719   Min = KnownOne;
720   Max = KnownOne|UnknownBits;
721   
722   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
723     Min.set(BitWidth-1);
724     Max.clear(BitWidth-1);
725   }
726 }
727
728 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
729 // a set of known zero and one bits, compute the maximum and minimum values that
730 // could have the specified known zero and known one bits, returning them in
731 // min/max.
732 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
733                                                      const APInt &KnownZero,
734                                                      const APInt &KnownOne,
735                                                      APInt &Min, APInt &Max) {
736   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
737   assert(KnownZero.getBitWidth() == BitWidth && 
738          KnownOne.getBitWidth() == BitWidth &&
739          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
740          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
741   APInt UnknownBits = ~(KnownZero|KnownOne);
742   
743   // The minimum value is when the unknown bits are all zeros.
744   Min = KnownOne;
745   // The maximum value is when the unknown bits are all ones.
746   Max = KnownOne|UnknownBits;
747 }
748
749 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
750 /// value based on the demanded bits. When this function is called, it is known
751 /// that only the bits set in DemandedMask of the result of V are ever used
752 /// downstream. Consequently, depending on the mask and V, it may be possible
753 /// to replace V with a constant or one of its operands. In such cases, this
754 /// function does the replacement and returns true. In all other cases, it
755 /// returns false after analyzing the expression and setting KnownOne and known
756 /// to be one in the expression. KnownZero contains all the bits that are known
757 /// to be zero in the expression. These are provided to potentially allow the
758 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
759 /// the expression. KnownOne and KnownZero always follow the invariant that 
760 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
761 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
762 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
763 /// and KnownOne must all be the same.
764 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
765                                         APInt& KnownZero, APInt& KnownOne,
766                                         unsigned Depth) {
767   assert(V != 0 && "Null pointer of Value???");
768   assert(Depth <= 6 && "Limit Search Depth");
769   uint32_t BitWidth = DemandedMask.getBitWidth();
770   const IntegerType *VTy = cast<IntegerType>(V->getType());
771   assert(VTy->getBitWidth() == BitWidth && 
772          KnownZero.getBitWidth() == BitWidth && 
773          KnownOne.getBitWidth() == BitWidth &&
774          "Value *V, DemandedMask, KnownZero and KnownOne \
775           must have same BitWidth");
776   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
777     // We know all of the bits for a constant!
778     KnownOne = CI->getValue() & DemandedMask;
779     KnownZero = ~KnownOne & DemandedMask;
780     return false;
781   }
782   
783   KnownZero.clear(); 
784   KnownOne.clear();
785   if (!V->hasOneUse()) {    // Other users may use these bits.
786     if (Depth != 0) {       // Not at the root.
787       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
788       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
789       return false;
790     }
791     // If this is the root being simplified, allow it to have multiple uses,
792     // just set the DemandedMask to all bits.
793     DemandedMask = APInt::getAllOnesValue(BitWidth);
794   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
795     if (V != UndefValue::get(VTy))
796       return UpdateValueUsesWith(V, UndefValue::get(VTy));
797     return false;
798   } else if (Depth == 6) {        // Limit search depth.
799     return false;
800   }
801   
802   Instruction *I = dyn_cast<Instruction>(V);
803   if (!I) return false;        // Only analyze instructions.
804
805   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
806   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
807   switch (I->getOpcode()) {
808   default:
809     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
810     break;
811   case Instruction::And:
812     // If either the LHS or the RHS are Zero, the result is zero.
813     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
814                              RHSKnownZero, RHSKnownOne, Depth+1))
815       return true;
816     assert((RHSKnownZero & RHSKnownOne) == 0 && 
817            "Bits known to be one AND zero?"); 
818
819     // If something is known zero on the RHS, the bits aren't demanded on the
820     // LHS.
821     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
822                              LHSKnownZero, LHSKnownOne, Depth+1))
823       return true;
824     assert((LHSKnownZero & LHSKnownOne) == 0 && 
825            "Bits known to be one AND zero?"); 
826
827     // If all of the demanded bits are known 1 on one side, return the other.
828     // These bits cannot contribute to the result of the 'and'.
829     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
830         (DemandedMask & ~LHSKnownZero))
831       return UpdateValueUsesWith(I, I->getOperand(0));
832     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
833         (DemandedMask & ~RHSKnownZero))
834       return UpdateValueUsesWith(I, I->getOperand(1));
835     
836     // If all of the demanded bits in the inputs are known zeros, return zero.
837     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
838       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
839       
840     // If the RHS is a constant, see if we can simplify it.
841     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
842       return UpdateValueUsesWith(I, I);
843       
844     // Output known-1 bits are only known if set in both the LHS & RHS.
845     RHSKnownOne &= LHSKnownOne;
846     // Output known-0 are known to be clear if zero in either the LHS | RHS.
847     RHSKnownZero |= LHSKnownZero;
848     break;
849   case Instruction::Or:
850     // If either the LHS or the RHS are One, the result is One.
851     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
852                              RHSKnownZero, RHSKnownOne, Depth+1))
853       return true;
854     assert((RHSKnownZero & RHSKnownOne) == 0 && 
855            "Bits known to be one AND zero?"); 
856     // If something is known one on the RHS, the bits aren't demanded on the
857     // LHS.
858     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
859                              LHSKnownZero, LHSKnownOne, Depth+1))
860       return true;
861     assert((LHSKnownZero & LHSKnownOne) == 0 && 
862            "Bits known to be one AND zero?"); 
863     
864     // If all of the demanded bits are known zero on one side, return the other.
865     // These bits cannot contribute to the result of the 'or'.
866     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
867         (DemandedMask & ~LHSKnownOne))
868       return UpdateValueUsesWith(I, I->getOperand(0));
869     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
870         (DemandedMask & ~RHSKnownOne))
871       return UpdateValueUsesWith(I, I->getOperand(1));
872
873     // If all of the potentially set bits on one side are known to be set on
874     // the other side, just use the 'other' side.
875     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
876         (DemandedMask & (~RHSKnownZero)))
877       return UpdateValueUsesWith(I, I->getOperand(0));
878     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
879         (DemandedMask & (~LHSKnownZero)))
880       return UpdateValueUsesWith(I, I->getOperand(1));
881         
882     // If the RHS is a constant, see if we can simplify it.
883     if (ShrinkDemandedConstant(I, 1, DemandedMask))
884       return UpdateValueUsesWith(I, I);
885           
886     // Output known-0 bits are only known if clear in both the LHS & RHS.
887     RHSKnownZero &= LHSKnownZero;
888     // Output known-1 are known to be set if set in either the LHS | RHS.
889     RHSKnownOne |= LHSKnownOne;
890     break;
891   case Instruction::Xor: {
892     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
893                              RHSKnownZero, RHSKnownOne, Depth+1))
894       return true;
895     assert((RHSKnownZero & RHSKnownOne) == 0 && 
896            "Bits known to be one AND zero?"); 
897     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
898                              LHSKnownZero, LHSKnownOne, Depth+1))
899       return true;
900     assert((LHSKnownZero & LHSKnownOne) == 0 && 
901            "Bits known to be one AND zero?"); 
902     
903     // If all of the demanded bits are known zero on one side, return the other.
904     // These bits cannot contribute to the result of the 'xor'.
905     if ((DemandedMask & RHSKnownZero) == DemandedMask)
906       return UpdateValueUsesWith(I, I->getOperand(0));
907     if ((DemandedMask & LHSKnownZero) == DemandedMask)
908       return UpdateValueUsesWith(I, I->getOperand(1));
909     
910     // Output known-0 bits are known if clear or set in both the LHS & RHS.
911     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
912                          (RHSKnownOne & LHSKnownOne);
913     // Output known-1 are known to be set if set in only one of the LHS, RHS.
914     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
915                         (RHSKnownOne & LHSKnownZero);
916     
917     // If all of the demanded bits are known to be zero on one side or the
918     // other, turn this into an *inclusive* or.
919     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
920     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
921       Instruction *Or =
922         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
923                                  I->getName());
924       InsertNewInstBefore(Or, *I);
925       return UpdateValueUsesWith(I, Or);
926     }
927     
928     // If all of the demanded bits on one side are known, and all of the set
929     // bits on that side are also known to be set on the other side, turn this
930     // into an AND, as we know the bits will be cleared.
931     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
932     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
933       // all known
934       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
935         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
936         Instruction *And = 
937           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
938         InsertNewInstBefore(And, *I);
939         return UpdateValueUsesWith(I, And);
940       }
941     }
942     
943     // If the RHS is a constant, see if we can simplify it.
944     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
945     if (ShrinkDemandedConstant(I, 1, DemandedMask))
946       return UpdateValueUsesWith(I, I);
947     
948     RHSKnownZero = KnownZeroOut;
949     RHSKnownOne  = KnownOneOut;
950     break;
951   }
952   case Instruction::Select:
953     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
954                              RHSKnownZero, RHSKnownOne, Depth+1))
955       return true;
956     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
957                              LHSKnownZero, LHSKnownOne, Depth+1))
958       return true;
959     assert((RHSKnownZero & RHSKnownOne) == 0 && 
960            "Bits known to be one AND zero?"); 
961     assert((LHSKnownZero & LHSKnownOne) == 0 && 
962            "Bits known to be one AND zero?"); 
963     
964     // If the operands are constants, see if we can simplify them.
965     if (ShrinkDemandedConstant(I, 1, DemandedMask))
966       return UpdateValueUsesWith(I, I);
967     if (ShrinkDemandedConstant(I, 2, DemandedMask))
968       return UpdateValueUsesWith(I, I);
969     
970     // Only known if known in both the LHS and RHS.
971     RHSKnownOne &= LHSKnownOne;
972     RHSKnownZero &= LHSKnownZero;
973     break;
974   case Instruction::Trunc: {
975     uint32_t truncBf = 
976       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
977     DemandedMask.zext(truncBf);
978     RHSKnownZero.zext(truncBf);
979     RHSKnownOne.zext(truncBf);
980     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
981                              RHSKnownZero, RHSKnownOne, Depth+1))
982       return true;
983     DemandedMask.trunc(BitWidth);
984     RHSKnownZero.trunc(BitWidth);
985     RHSKnownOne.trunc(BitWidth);
986     assert((RHSKnownZero & RHSKnownOne) == 0 && 
987            "Bits known to be one AND zero?"); 
988     break;
989   }
990   case Instruction::BitCast:
991     if (!I->getOperand(0)->getType()->isInteger())
992       return false;
993       
994     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
995                              RHSKnownZero, RHSKnownOne, Depth+1))
996       return true;
997     assert((RHSKnownZero & RHSKnownOne) == 0 && 
998            "Bits known to be one AND zero?"); 
999     break;
1000   case Instruction::ZExt: {
1001     // Compute the bits in the result that are not present in the input.
1002     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1003     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1004     
1005     DemandedMask.trunc(SrcBitWidth);
1006     RHSKnownZero.trunc(SrcBitWidth);
1007     RHSKnownOne.trunc(SrcBitWidth);
1008     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1009                              RHSKnownZero, RHSKnownOne, Depth+1))
1010       return true;
1011     DemandedMask.zext(BitWidth);
1012     RHSKnownZero.zext(BitWidth);
1013     RHSKnownOne.zext(BitWidth);
1014     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1015            "Bits known to be one AND zero?"); 
1016     // The top bits are known to be zero.
1017     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1018     break;
1019   }
1020   case Instruction::SExt: {
1021     // Compute the bits in the result that are not present in the input.
1022     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1023     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1024     
1025     APInt InputDemandedBits = DemandedMask & 
1026                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1027
1028     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1029     // If any of the sign extended bits are demanded, we know that the sign
1030     // bit is demanded.
1031     if ((NewBits & DemandedMask) != 0)
1032       InputDemandedBits.set(SrcBitWidth-1);
1033       
1034     InputDemandedBits.trunc(SrcBitWidth);
1035     RHSKnownZero.trunc(SrcBitWidth);
1036     RHSKnownOne.trunc(SrcBitWidth);
1037     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1038                              RHSKnownZero, RHSKnownOne, Depth+1))
1039       return true;
1040     InputDemandedBits.zext(BitWidth);
1041     RHSKnownZero.zext(BitWidth);
1042     RHSKnownOne.zext(BitWidth);
1043     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1044            "Bits known to be one AND zero?"); 
1045       
1046     // If the sign bit of the input is known set or clear, then we know the
1047     // top bits of the result.
1048
1049     // If the input sign bit is known zero, or if the NewBits are not demanded
1050     // convert this into a zero extension.
1051     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1052     {
1053       // Convert to ZExt cast
1054       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1055       return UpdateValueUsesWith(I, NewCast);
1056     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1057       RHSKnownOne |= NewBits;
1058     }
1059     break;
1060   }
1061   case Instruction::Add: {
1062     // Figure out what the input bits are.  If the top bits of the and result
1063     // are not demanded, then the add doesn't demand them from its input
1064     // either.
1065     uint32_t NLZ = DemandedMask.countLeadingZeros();
1066       
1067     // If there is a constant on the RHS, there are a variety of xformations
1068     // we can do.
1069     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070       // If null, this should be simplified elsewhere.  Some of the xforms here
1071       // won't work if the RHS is zero.
1072       if (RHS->isZero())
1073         break;
1074       
1075       // If the top bit of the output is demanded, demand everything from the
1076       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1077       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1078
1079       // Find information about known zero/one bits in the input.
1080       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1081                                LHSKnownZero, LHSKnownOne, Depth+1))
1082         return true;
1083
1084       // If the RHS of the add has bits set that can't affect the input, reduce
1085       // the constant.
1086       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1087         return UpdateValueUsesWith(I, I);
1088       
1089       // Avoid excess work.
1090       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1091         break;
1092       
1093       // Turn it into OR if input bits are zero.
1094       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1095         Instruction *Or =
1096           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1097                                    I->getName());
1098         InsertNewInstBefore(Or, *I);
1099         return UpdateValueUsesWith(I, Or);
1100       }
1101       
1102       // We can say something about the output known-zero and known-one bits,
1103       // depending on potential carries from the input constant and the
1104       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1105       // bits set and the RHS constant is 0x01001, then we know we have a known
1106       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1107       
1108       // To compute this, we first compute the potential carry bits.  These are
1109       // the bits which may be modified.  I'm not aware of a better way to do
1110       // this scan.
1111       const APInt& RHSVal = RHS->getValue();
1112       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1113       
1114       // Now that we know which bits have carries, compute the known-1/0 sets.
1115       
1116       // Bits are known one if they are known zero in one operand and one in the
1117       // other, and there is no input carry.
1118       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1119                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1120       
1121       // Bits are known zero if they are known zero in both operands and there
1122       // is no input carry.
1123       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1124     } else {
1125       // If the high-bits of this ADD are not demanded, then it does not demand
1126       // the high bits of its LHS or RHS.
1127       if (DemandedMask[BitWidth-1] == 0) {
1128         // Right fill the mask of bits for this ADD to demand the most
1129         // significant bit and all those below it.
1130         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1131         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1132                                  LHSKnownZero, LHSKnownOne, Depth+1))
1133           return true;
1134         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1135                                  LHSKnownZero, LHSKnownOne, Depth+1))
1136           return true;
1137       }
1138     }
1139     break;
1140   }
1141   case Instruction::Sub:
1142     // If the high-bits of this SUB are not demanded, then it does not demand
1143     // the high bits of its LHS or RHS.
1144     if (DemandedMask[BitWidth-1] == 0) {
1145       // Right fill the mask of bits for this SUB to demand the most
1146       // significant bit and all those below it.
1147       uint32_t NLZ = DemandedMask.countLeadingZeros();
1148       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1149       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1150                                LHSKnownZero, LHSKnownOne, Depth+1))
1151         return true;
1152       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1153                                LHSKnownZero, LHSKnownOne, Depth+1))
1154         return true;
1155     }
1156     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1157     // the known zeros and ones.
1158     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1159     break;
1160   case Instruction::Shl:
1161     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1162       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1163       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1164       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1165                                RHSKnownZero, RHSKnownOne, Depth+1))
1166         return true;
1167       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1168              "Bits known to be one AND zero?"); 
1169       RHSKnownZero <<= ShiftAmt;
1170       RHSKnownOne  <<= ShiftAmt;
1171       // low bits known zero.
1172       if (ShiftAmt)
1173         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1174     }
1175     break;
1176   case Instruction::LShr:
1177     // For a logical shift right
1178     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1179       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1180       
1181       // Unsigned shift right.
1182       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1183       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1184                                RHSKnownZero, RHSKnownOne, Depth+1))
1185         return true;
1186       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1187              "Bits known to be one AND zero?"); 
1188       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1189       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1190       if (ShiftAmt) {
1191         // Compute the new bits that are at the top now.
1192         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1193         RHSKnownZero |= HighBits;  // high bits known zero.
1194       }
1195     }
1196     break;
1197   case Instruction::AShr:
1198     // If this is an arithmetic shift right and only the low-bit is set, we can
1199     // always convert this into a logical shr, even if the shift amount is
1200     // variable.  The low bit of the shift cannot be an input sign bit unless
1201     // the shift amount is >= the size of the datatype, which is undefined.
1202     if (DemandedMask == 1) {
1203       // Perform the logical shift right.
1204       Value *NewVal = BinaryOperator::CreateLShr(
1205                         I->getOperand(0), I->getOperand(1), I->getName());
1206       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1207       return UpdateValueUsesWith(I, NewVal);
1208     }    
1209
1210     // If the sign bit is the only bit demanded by this ashr, then there is no
1211     // need to do it, the shift doesn't change the high bit.
1212     if (DemandedMask.isSignBit())
1213       return UpdateValueUsesWith(I, I->getOperand(0));
1214     
1215     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1216       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1217       
1218       // Signed shift right.
1219       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1220       // If any of the "high bits" are demanded, we should set the sign bit as
1221       // demanded.
1222       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1223         DemandedMaskIn.set(BitWidth-1);
1224       if (SimplifyDemandedBits(I->getOperand(0),
1225                                DemandedMaskIn,
1226                                RHSKnownZero, RHSKnownOne, Depth+1))
1227         return true;
1228       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1229              "Bits known to be one AND zero?"); 
1230       // Compute the new bits that are at the top now.
1231       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1232       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1233       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1234         
1235       // Handle the sign bits.
1236       APInt SignBit(APInt::getSignBit(BitWidth));
1237       // Adjust to where it is now in the mask.
1238       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1239         
1240       // If the input sign bit is known to be zero, or if none of the top bits
1241       // are demanded, turn this into an unsigned shift right.
1242       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1243           (HighBits & ~DemandedMask) == HighBits) {
1244         // Perform the logical shift right.
1245         Value *NewVal = BinaryOperator::CreateLShr(
1246                           I->getOperand(0), SA, I->getName());
1247         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1248         return UpdateValueUsesWith(I, NewVal);
1249       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1250         RHSKnownOne |= HighBits;
1251       }
1252     }
1253     break;
1254   case Instruction::SRem:
1255     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1256       APInt RA = Rem->getValue();
1257       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1258         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1259           return UpdateValueUsesWith(I, I->getOperand(0));
1260
1261         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1262         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1263         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1264                                  LHSKnownZero, LHSKnownOne, Depth+1))
1265           return true;
1266
1267         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1268           LHSKnownZero |= ~LowBits;
1269
1270         KnownZero |= LHSKnownZero & DemandedMask;
1271
1272         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1273       }
1274     }
1275     break;
1276   case Instruction::URem: {
1277     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1278     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1279     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1280                              KnownZero2, KnownOne2, Depth+1))
1281       return true;
1282
1283     uint32_t Leaders = KnownZero2.countLeadingOnes();
1284     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1285                              KnownZero2, KnownOne2, Depth+1))
1286       return true;
1287
1288     Leaders = std::max(Leaders,
1289                        KnownZero2.countLeadingOnes());
1290     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1291     break;
1292   }
1293   case Instruction::Call:
1294     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1295       switch (II->getIntrinsicID()) {
1296       default: break;
1297       case Intrinsic::bswap: {
1298         // If the only bits demanded come from one byte of the bswap result,
1299         // just shift the input byte into position to eliminate the bswap.
1300         unsigned NLZ = DemandedMask.countLeadingZeros();
1301         unsigned NTZ = DemandedMask.countTrailingZeros();
1302           
1303         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1304         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1305         // have 14 leading zeros, round to 8.
1306         NLZ &= ~7;
1307         NTZ &= ~7;
1308         // If we need exactly one byte, we can do this transformation.
1309         if (BitWidth-NLZ-NTZ == 8) {
1310           unsigned ResultBit = NTZ;
1311           unsigned InputBit = BitWidth-NTZ-8;
1312           
1313           // Replace this with either a left or right shift to get the byte into
1314           // the right place.
1315           Instruction *NewVal;
1316           if (InputBit > ResultBit)
1317             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1318                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1319           else
1320             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1321                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1322           NewVal->takeName(I);
1323           InsertNewInstBefore(NewVal, *I);
1324           return UpdateValueUsesWith(I, NewVal);
1325         }
1326           
1327         // TODO: Could compute known zero/one bits based on the input.
1328         break;
1329       }
1330       }
1331     }
1332     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1333     break;
1334   }
1335   
1336   // If the client is only demanding bits that we know, return the known
1337   // constant.
1338   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1339     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1340   return false;
1341 }
1342
1343
1344 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1345 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1346 /// actually used by the caller.  This method analyzes which elements of the
1347 /// operand are undef and returns that information in UndefElts.
1348 ///
1349 /// If the information about demanded elements can be used to simplify the
1350 /// operation, the operation is simplified, then the resultant value is
1351 /// returned.  This returns null if no change was made.
1352 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1353                                                 uint64_t &UndefElts,
1354                                                 unsigned Depth) {
1355   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1356   assert(VWidth <= 64 && "Vector too wide to analyze!");
1357   uint64_t EltMask = ~0ULL >> (64-VWidth);
1358   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1359          "Invalid DemandedElts!");
1360
1361   if (isa<UndefValue>(V)) {
1362     // If the entire vector is undefined, just return this info.
1363     UndefElts = EltMask;
1364     return 0;
1365   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1366     UndefElts = EltMask;
1367     return UndefValue::get(V->getType());
1368   }
1369   
1370   UndefElts = 0;
1371   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1372     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1373     Constant *Undef = UndefValue::get(EltTy);
1374
1375     std::vector<Constant*> Elts;
1376     for (unsigned i = 0; i != VWidth; ++i)
1377       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1378         Elts.push_back(Undef);
1379         UndefElts |= (1ULL << i);
1380       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1381         Elts.push_back(Undef);
1382         UndefElts |= (1ULL << i);
1383       } else {                               // Otherwise, defined.
1384         Elts.push_back(CP->getOperand(i));
1385       }
1386         
1387     // If we changed the constant, return it.
1388     Constant *NewCP = ConstantVector::get(Elts);
1389     return NewCP != CP ? NewCP : 0;
1390   } else if (isa<ConstantAggregateZero>(V)) {
1391     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1392     // set to undef.
1393     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1394     Constant *Zero = Constant::getNullValue(EltTy);
1395     Constant *Undef = UndefValue::get(EltTy);
1396     std::vector<Constant*> Elts;
1397     for (unsigned i = 0; i != VWidth; ++i)
1398       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1399     UndefElts = DemandedElts ^ EltMask;
1400     return ConstantVector::get(Elts);
1401   }
1402   
1403   if (!V->hasOneUse()) {    // Other users may use these bits.
1404     if (Depth != 0) {       // Not at the root.
1405       // TODO: Just compute the UndefElts information recursively.
1406       return false;
1407     }
1408     return false;
1409   } else if (Depth == 10) {        // Limit search depth.
1410     return false;
1411   }
1412   
1413   Instruction *I = dyn_cast<Instruction>(V);
1414   if (!I) return false;        // Only analyze instructions.
1415   
1416   bool MadeChange = false;
1417   uint64_t UndefElts2;
1418   Value *TmpV;
1419   switch (I->getOpcode()) {
1420   default: break;
1421     
1422   case Instruction::InsertElement: {
1423     // If this is a variable index, we don't know which element it overwrites.
1424     // demand exactly the same input as we produce.
1425     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1426     if (Idx == 0) {
1427       // Note that we can't propagate undef elt info, because we don't know
1428       // which elt is getting updated.
1429       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1430                                         UndefElts2, Depth+1);
1431       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1432       break;
1433     }
1434     
1435     // If this is inserting an element that isn't demanded, remove this
1436     // insertelement.
1437     unsigned IdxNo = Idx->getZExtValue();
1438     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1439       return AddSoonDeadInstToWorklist(*I, 0);
1440     
1441     // Otherwise, the element inserted overwrites whatever was there, so the
1442     // input demanded set is simpler than the output set.
1443     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1444                                       DemandedElts & ~(1ULL << IdxNo),
1445                                       UndefElts, Depth+1);
1446     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1447
1448     // The inserted element is defined.
1449     UndefElts |= 1ULL << IdxNo;
1450     break;
1451   }
1452   case Instruction::BitCast: {
1453     // Vector->vector casts only.
1454     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1455     if (!VTy) break;
1456     unsigned InVWidth = VTy->getNumElements();
1457     uint64_t InputDemandedElts = 0;
1458     unsigned Ratio;
1459
1460     if (VWidth == InVWidth) {
1461       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1462       // elements as are demanded of us.
1463       Ratio = 1;
1464       InputDemandedElts = DemandedElts;
1465     } else if (VWidth > InVWidth) {
1466       // Untested so far.
1467       break;
1468       
1469       // If there are more elements in the result than there are in the source,
1470       // then an input element is live if any of the corresponding output
1471       // elements are live.
1472       Ratio = VWidth/InVWidth;
1473       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1474         if (DemandedElts & (1ULL << OutIdx))
1475           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1476       }
1477     } else {
1478       // Untested so far.
1479       break;
1480       
1481       // If there are more elements in the source than there are in the result,
1482       // then an input element is live if the corresponding output element is
1483       // live.
1484       Ratio = InVWidth/VWidth;
1485       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1486         if (DemandedElts & (1ULL << InIdx/Ratio))
1487           InputDemandedElts |= 1ULL << InIdx;
1488     }
1489     
1490     // div/rem demand all inputs, because they don't want divide by zero.
1491     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1492                                       UndefElts2, Depth+1);
1493     if (TmpV) {
1494       I->setOperand(0, TmpV);
1495       MadeChange = true;
1496     }
1497     
1498     UndefElts = UndefElts2;
1499     if (VWidth > InVWidth) {
1500       assert(0 && "Unimp");
1501       // If there are more elements in the result than there are in the source,
1502       // then an output element is undef if the corresponding input element is
1503       // undef.
1504       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1505         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1506           UndefElts |= 1ULL << OutIdx;
1507     } else if (VWidth < InVWidth) {
1508       assert(0 && "Unimp");
1509       // If there are more elements in the source than there are in the result,
1510       // then a result element is undef if all of the corresponding input
1511       // elements are undef.
1512       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1513       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1514         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1515           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1516     }
1517     break;
1518   }
1519   case Instruction::And:
1520   case Instruction::Or:
1521   case Instruction::Xor:
1522   case Instruction::Add:
1523   case Instruction::Sub:
1524   case Instruction::Mul:
1525     // div/rem demand all inputs, because they don't want divide by zero.
1526     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1527                                       UndefElts, Depth+1);
1528     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1529     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1530                                       UndefElts2, Depth+1);
1531     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1532       
1533     // Output elements are undefined if both are undefined.  Consider things
1534     // like undef&0.  The result is known zero, not undef.
1535     UndefElts &= UndefElts2;
1536     break;
1537     
1538   case Instruction::Call: {
1539     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1540     if (!II) break;
1541     switch (II->getIntrinsicID()) {
1542     default: break;
1543       
1544     // Binary vector operations that work column-wise.  A dest element is a
1545     // function of the corresponding input elements from the two inputs.
1546     case Intrinsic::x86_sse_sub_ss:
1547     case Intrinsic::x86_sse_mul_ss:
1548     case Intrinsic::x86_sse_min_ss:
1549     case Intrinsic::x86_sse_max_ss:
1550     case Intrinsic::x86_sse2_sub_sd:
1551     case Intrinsic::x86_sse2_mul_sd:
1552     case Intrinsic::x86_sse2_min_sd:
1553     case Intrinsic::x86_sse2_max_sd:
1554       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1555                                         UndefElts, Depth+1);
1556       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1557       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1558                                         UndefElts2, Depth+1);
1559       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1560
1561       // If only the low elt is demanded and this is a scalarizable intrinsic,
1562       // scalarize it now.
1563       if (DemandedElts == 1) {
1564         switch (II->getIntrinsicID()) {
1565         default: break;
1566         case Intrinsic::x86_sse_sub_ss:
1567         case Intrinsic::x86_sse_mul_ss:
1568         case Intrinsic::x86_sse2_sub_sd:
1569         case Intrinsic::x86_sse2_mul_sd:
1570           // TODO: Lower MIN/MAX/ABS/etc
1571           Value *LHS = II->getOperand(1);
1572           Value *RHS = II->getOperand(2);
1573           // Extract the element as scalars.
1574           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1575           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1576           
1577           switch (II->getIntrinsicID()) {
1578           default: assert(0 && "Case stmts out of sync!");
1579           case Intrinsic::x86_sse_sub_ss:
1580           case Intrinsic::x86_sse2_sub_sd:
1581             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1582                                                         II->getName()), *II);
1583             break;
1584           case Intrinsic::x86_sse_mul_ss:
1585           case Intrinsic::x86_sse2_mul_sd:
1586             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1587                                                          II->getName()), *II);
1588             break;
1589           }
1590           
1591           Instruction *New =
1592             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1593                                       II->getName());
1594           InsertNewInstBefore(New, *II);
1595           AddSoonDeadInstToWorklist(*II, 0);
1596           return New;
1597         }            
1598       }
1599         
1600       // Output elements are undefined if both are undefined.  Consider things
1601       // like undef&0.  The result is known zero, not undef.
1602       UndefElts &= UndefElts2;
1603       break;
1604     }
1605     break;
1606   }
1607   }
1608   return MadeChange ? I : 0;
1609 }
1610
1611
1612 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1613 /// function is designed to check a chain of associative operators for a
1614 /// potential to apply a certain optimization.  Since the optimization may be
1615 /// applicable if the expression was reassociated, this checks the chain, then
1616 /// reassociates the expression as necessary to expose the optimization
1617 /// opportunity.  This makes use of a special Functor, which must define
1618 /// 'shouldApply' and 'apply' methods.
1619 ///
1620 template<typename Functor>
1621 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1622   unsigned Opcode = Root.getOpcode();
1623   Value *LHS = Root.getOperand(0);
1624
1625   // Quick check, see if the immediate LHS matches...
1626   if (F.shouldApply(LHS))
1627     return F.apply(Root);
1628
1629   // Otherwise, if the LHS is not of the same opcode as the root, return.
1630   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1631   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1632     // Should we apply this transform to the RHS?
1633     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1634
1635     // If not to the RHS, check to see if we should apply to the LHS...
1636     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1637       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1638       ShouldApply = true;
1639     }
1640
1641     // If the functor wants to apply the optimization to the RHS of LHSI,
1642     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1643     if (ShouldApply) {
1644       // Now all of the instructions are in the current basic block, go ahead
1645       // and perform the reassociation.
1646       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1647
1648       // First move the selected RHS to the LHS of the root...
1649       Root.setOperand(0, LHSI->getOperand(1));
1650
1651       // Make what used to be the LHS of the root be the user of the root...
1652       Value *ExtraOperand = TmpLHSI->getOperand(1);
1653       if (&Root == TmpLHSI) {
1654         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1655         return 0;
1656       }
1657       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1658       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1659       BasicBlock::iterator ARI = &Root; ++ARI;
1660       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1661       ARI = Root;
1662
1663       // Now propagate the ExtraOperand down the chain of instructions until we
1664       // get to LHSI.
1665       while (TmpLHSI != LHSI) {
1666         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1667         // Move the instruction to immediately before the chain we are
1668         // constructing to avoid breaking dominance properties.
1669         NextLHSI->moveBefore(ARI);
1670         ARI = NextLHSI;
1671
1672         Value *NextOp = NextLHSI->getOperand(1);
1673         NextLHSI->setOperand(1, ExtraOperand);
1674         TmpLHSI = NextLHSI;
1675         ExtraOperand = NextOp;
1676       }
1677
1678       // Now that the instructions are reassociated, have the functor perform
1679       // the transformation...
1680       return F.apply(Root);
1681     }
1682
1683     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1684   }
1685   return 0;
1686 }
1687
1688 namespace {
1689
1690 // AddRHS - Implements: X + X --> X << 1
1691 struct AddRHS {
1692   Value *RHS;
1693   AddRHS(Value *rhs) : RHS(rhs) {}
1694   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1695   Instruction *apply(BinaryOperator &Add) const {
1696     return BinaryOperator::CreateShl(Add.getOperand(0),
1697                                      ConstantInt::get(Add.getType(), 1));
1698   }
1699 };
1700
1701 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1702 //                 iff C1&C2 == 0
1703 struct AddMaskingAnd {
1704   Constant *C2;
1705   AddMaskingAnd(Constant *c) : C2(c) {}
1706   bool shouldApply(Value *LHS) const {
1707     ConstantInt *C1;
1708     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1709            ConstantExpr::getAnd(C1, C2)->isNullValue();
1710   }
1711   Instruction *apply(BinaryOperator &Add) const {
1712     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1713   }
1714 };
1715
1716 }
1717
1718 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1719                                              InstCombiner *IC) {
1720   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1721     if (Constant *SOC = dyn_cast<Constant>(SO))
1722       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1723
1724     return IC->InsertNewInstBefore(CastInst::Create(
1725           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1726   }
1727
1728   // Figure out if the constant is the left or the right argument.
1729   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1730   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1731
1732   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1733     if (ConstIsRHS)
1734       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1735     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1736   }
1737
1738   Value *Op0 = SO, *Op1 = ConstOperand;
1739   if (!ConstIsRHS)
1740     std::swap(Op0, Op1);
1741   Instruction *New;
1742   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1743     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1744   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1745     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1746                           SO->getName()+".cmp");
1747   else {
1748     assert(0 && "Unknown binary instruction type!");
1749     abort();
1750   }
1751   return IC->InsertNewInstBefore(New, I);
1752 }
1753
1754 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1755 // constant as the other operand, try to fold the binary operator into the
1756 // select arguments.  This also works for Cast instructions, which obviously do
1757 // not have a second operand.
1758 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1759                                      InstCombiner *IC) {
1760   // Don't modify shared select instructions
1761   if (!SI->hasOneUse()) return 0;
1762   Value *TV = SI->getOperand(1);
1763   Value *FV = SI->getOperand(2);
1764
1765   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1766     // Bool selects with constant operands can be folded to logical ops.
1767     if (SI->getType() == Type::Int1Ty) return 0;
1768
1769     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1770     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1771
1772     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1773                               SelectFalseVal);
1774   }
1775   return 0;
1776 }
1777
1778
1779 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1780 /// node as operand #0, see if we can fold the instruction into the PHI (which
1781 /// is only possible if all operands to the PHI are constants).
1782 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1783   PHINode *PN = cast<PHINode>(I.getOperand(0));
1784   unsigned NumPHIValues = PN->getNumIncomingValues();
1785   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1786
1787   // Check to see if all of the operands of the PHI are constants.  If there is
1788   // one non-constant value, remember the BB it is.  If there is more than one
1789   // or if *it* is a PHI, bail out.
1790   BasicBlock *NonConstBB = 0;
1791   for (unsigned i = 0; i != NumPHIValues; ++i)
1792     if (!isa<Constant>(PN->getIncomingValue(i))) {
1793       if (NonConstBB) return 0;  // More than one non-const value.
1794       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1795       NonConstBB = PN->getIncomingBlock(i);
1796       
1797       // If the incoming non-constant value is in I's block, we have an infinite
1798       // loop.
1799       if (NonConstBB == I.getParent())
1800         return 0;
1801     }
1802   
1803   // If there is exactly one non-constant value, we can insert a copy of the
1804   // operation in that block.  However, if this is a critical edge, we would be
1805   // inserting the computation one some other paths (e.g. inside a loop).  Only
1806   // do this if the pred block is unconditionally branching into the phi block.
1807   if (NonConstBB) {
1808     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1809     if (!BI || !BI->isUnconditional()) return 0;
1810   }
1811
1812   // Okay, we can do the transformation: create the new PHI node.
1813   PHINode *NewPN = PHINode::Create(I.getType(), "");
1814   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1815   InsertNewInstBefore(NewPN, *PN);
1816   NewPN->takeName(PN);
1817
1818   // Next, add all of the operands to the PHI.
1819   if (I.getNumOperands() == 2) {
1820     Constant *C = cast<Constant>(I.getOperand(1));
1821     for (unsigned i = 0; i != NumPHIValues; ++i) {
1822       Value *InV = 0;
1823       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1824         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1825           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1826         else
1827           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1828       } else {
1829         assert(PN->getIncomingBlock(i) == NonConstBB);
1830         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1831           InV = BinaryOperator::Create(BO->getOpcode(),
1832                                        PN->getIncomingValue(i), C, "phitmp",
1833                                        NonConstBB->getTerminator());
1834         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1835           InV = CmpInst::Create(CI->getOpcode(), 
1836                                 CI->getPredicate(),
1837                                 PN->getIncomingValue(i), C, "phitmp",
1838                                 NonConstBB->getTerminator());
1839         else
1840           assert(0 && "Unknown binop!");
1841         
1842         AddToWorkList(cast<Instruction>(InV));
1843       }
1844       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1845     }
1846   } else { 
1847     CastInst *CI = cast<CastInst>(&I);
1848     const Type *RetTy = CI->getType();
1849     for (unsigned i = 0; i != NumPHIValues; ++i) {
1850       Value *InV;
1851       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1852         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1853       } else {
1854         assert(PN->getIncomingBlock(i) == NonConstBB);
1855         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1856                                I.getType(), "phitmp", 
1857                                NonConstBB->getTerminator());
1858         AddToWorkList(cast<Instruction>(InV));
1859       }
1860       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1861     }
1862   }
1863   return ReplaceInstUsesWith(I, NewPN);
1864 }
1865
1866
1867 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1868 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1869 /// This basically requires proving that the add in the original type would not
1870 /// overflow to change the sign bit or have a carry out.
1871 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1872   // There are different heuristics we can use for this.  Here are some simple
1873   // ones.
1874   
1875   // Add has the property that adding any two 2's complement numbers can only 
1876   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1877   // have at least two sign bits, we know that the addition of the two values will
1878   // sign extend fine.
1879   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1880     return true;
1881   
1882   
1883   // If one of the operands only has one non-zero bit, and if the other operand
1884   // has a known-zero bit in a more significant place than it (not including the
1885   // sign bit) the ripple may go up to and fill the zero, but won't change the
1886   // sign.  For example, (X & ~4) + 1.
1887   
1888   // TODO: Implement.
1889   
1890   return false;
1891 }
1892
1893
1894 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1895   bool Changed = SimplifyCommutative(I);
1896   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1897
1898   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1899     // X + undef -> undef
1900     if (isa<UndefValue>(RHS))
1901       return ReplaceInstUsesWith(I, RHS);
1902
1903     // X + 0 --> X
1904     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1905       if (RHSC->isNullValue())
1906         return ReplaceInstUsesWith(I, LHS);
1907     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1908       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1909                               (I.getType())->getValueAPF()))
1910         return ReplaceInstUsesWith(I, LHS);
1911     }
1912
1913     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1914       // X + (signbit) --> X ^ signbit
1915       const APInt& Val = CI->getValue();
1916       uint32_t BitWidth = Val.getBitWidth();
1917       if (Val == APInt::getSignBit(BitWidth))
1918         return BinaryOperator::CreateXor(LHS, RHS);
1919       
1920       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1921       // (X & 254)+1 -> (X&254)|1
1922       if (!isa<VectorType>(I.getType())) {
1923         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1924         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1925                                  KnownZero, KnownOne))
1926           return &I;
1927       }
1928     }
1929
1930     if (isa<PHINode>(LHS))
1931       if (Instruction *NV = FoldOpIntoPhi(I))
1932         return NV;
1933     
1934     ConstantInt *XorRHS = 0;
1935     Value *XorLHS = 0;
1936     if (isa<ConstantInt>(RHSC) &&
1937         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1938       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1939       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1940       
1941       uint32_t Size = TySizeBits / 2;
1942       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1943       APInt CFF80Val(-C0080Val);
1944       do {
1945         if (TySizeBits > Size) {
1946           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1947           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1948           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1949               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1950             // This is a sign extend if the top bits are known zero.
1951             if (!MaskedValueIsZero(XorLHS, 
1952                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1953               Size = 0;  // Not a sign ext, but can't be any others either.
1954             break;
1955           }
1956         }
1957         Size >>= 1;
1958         C0080Val = APIntOps::lshr(C0080Val, Size);
1959         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1960       } while (Size >= 1);
1961       
1962       // FIXME: This shouldn't be necessary. When the backends can handle types
1963       // with funny bit widths then this switch statement should be removed. It
1964       // is just here to get the size of the "middle" type back up to something
1965       // that the back ends can handle.
1966       const Type *MiddleType = 0;
1967       switch (Size) {
1968         default: break;
1969         case 32: MiddleType = Type::Int32Ty; break;
1970         case 16: MiddleType = Type::Int16Ty; break;
1971         case  8: MiddleType = Type::Int8Ty; break;
1972       }
1973       if (MiddleType) {
1974         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1975         InsertNewInstBefore(NewTrunc, I);
1976         return new SExtInst(NewTrunc, I.getType(), I.getName());
1977       }
1978     }
1979   }
1980
1981   if (I.getType() == Type::Int1Ty)
1982     return BinaryOperator::CreateXor(LHS, RHS);
1983
1984   // X + X --> X << 1
1985   if (I.getType()->isInteger()) {
1986     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1987
1988     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1989       if (RHSI->getOpcode() == Instruction::Sub)
1990         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1991           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1992     }
1993     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1994       if (LHSI->getOpcode() == Instruction::Sub)
1995         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1996           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1997     }
1998   }
1999
2000   // -A + B  -->  B - A
2001   // -A + -B  -->  -(A + B)
2002   if (Value *LHSV = dyn_castNegVal(LHS)) {
2003     if (LHS->getType()->isIntOrIntVector()) {
2004       if (Value *RHSV = dyn_castNegVal(RHS)) {
2005         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2006         InsertNewInstBefore(NewAdd, I);
2007         return BinaryOperator::CreateNeg(NewAdd);
2008       }
2009     }
2010     
2011     return BinaryOperator::CreateSub(RHS, LHSV);
2012   }
2013
2014   // A + -B  -->  A - B
2015   if (!isa<Constant>(RHS))
2016     if (Value *V = dyn_castNegVal(RHS))
2017       return BinaryOperator::CreateSub(LHS, V);
2018
2019
2020   ConstantInt *C2;
2021   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2022     if (X == RHS)   // X*C + X --> X * (C+1)
2023       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2024
2025     // X*C1 + X*C2 --> X * (C1+C2)
2026     ConstantInt *C1;
2027     if (X == dyn_castFoldableMul(RHS, C1))
2028       return BinaryOperator::CreateMul(X, Add(C1, C2));
2029   }
2030
2031   // X + X*C --> X * (C+1)
2032   if (dyn_castFoldableMul(RHS, C2) == LHS)
2033     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2034
2035   // X + ~X --> -1   since   ~X = -X-1
2036   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2037     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2038   
2039
2040   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2041   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2042     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2043       return R;
2044   
2045   // A+B --> A|B iff A and B have no bits set in common.
2046   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2047     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2048     APInt LHSKnownOne(IT->getBitWidth(), 0);
2049     APInt LHSKnownZero(IT->getBitWidth(), 0);
2050     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2051     if (LHSKnownZero != 0) {
2052       APInt RHSKnownOne(IT->getBitWidth(), 0);
2053       APInt RHSKnownZero(IT->getBitWidth(), 0);
2054       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2055       
2056       // No bits in common -> bitwise or.
2057       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2058         return BinaryOperator::CreateOr(LHS, RHS);
2059     }
2060   }
2061
2062   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2063   if (I.getType()->isIntOrIntVector()) {
2064     Value *W, *X, *Y, *Z;
2065     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2066         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2067       if (W != Y) {
2068         if (W == Z) {
2069           std::swap(Y, Z);
2070         } else if (Y == X) {
2071           std::swap(W, X);
2072         } else if (X == Z) {
2073           std::swap(Y, Z);
2074           std::swap(W, X);
2075         }
2076       }
2077
2078       if (W == Y) {
2079         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2080                                                             LHS->getName()), I);
2081         return BinaryOperator::CreateMul(W, NewAdd);
2082       }
2083     }
2084   }
2085
2086   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2087     Value *X = 0;
2088     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2089       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2090
2091     // (X & FF00) + xx00  -> (X+xx00) & FF00
2092     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2093       Constant *Anded = And(CRHS, C2);
2094       if (Anded == CRHS) {
2095         // See if all bits from the first bit set in the Add RHS up are included
2096         // in the mask.  First, get the rightmost bit.
2097         const APInt& AddRHSV = CRHS->getValue();
2098
2099         // Form a mask of all bits from the lowest bit added through the top.
2100         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2101
2102         // See if the and mask includes all of these bits.
2103         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2104
2105         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2106           // Okay, the xform is safe.  Insert the new add pronto.
2107           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2108                                                             LHS->getName()), I);
2109           return BinaryOperator::CreateAnd(NewAdd, C2);
2110         }
2111       }
2112     }
2113
2114     // Try to fold constant add into select arguments.
2115     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2116       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2117         return R;
2118   }
2119
2120   // add (cast *A to intptrtype) B -> 
2121   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2122   {
2123     CastInst *CI = dyn_cast<CastInst>(LHS);
2124     Value *Other = RHS;
2125     if (!CI) {
2126       CI = dyn_cast<CastInst>(RHS);
2127       Other = LHS;
2128     }
2129     if (CI && CI->getType()->isSized() && 
2130         (CI->getType()->getPrimitiveSizeInBits() == 
2131          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2132         && isa<PointerType>(CI->getOperand(0)->getType())) {
2133       unsigned AS =
2134         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2135       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2136                                       PointerType::get(Type::Int8Ty, AS), I);
2137       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2138       return new PtrToIntInst(I2, CI->getType());
2139     }
2140   }
2141   
2142   // add (select X 0 (sub n A)) A  -->  select X A n
2143   {
2144     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2145     Value *Other = RHS;
2146     if (!SI) {
2147       SI = dyn_cast<SelectInst>(RHS);
2148       Other = LHS;
2149     }
2150     if (SI && SI->hasOneUse()) {
2151       Value *TV = SI->getTrueValue();
2152       Value *FV = SI->getFalseValue();
2153       Value *A, *N;
2154
2155       // Can we fold the add into the argument of the select?
2156       // We check both true and false select arguments for a matching subtract.
2157       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2158           A == Other)  // Fold the add into the true select value.
2159         return SelectInst::Create(SI->getCondition(), N, A);
2160       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2161           A == Other)  // Fold the add into the false select value.
2162         return SelectInst::Create(SI->getCondition(), A, N);
2163     }
2164   }
2165   
2166   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2167   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2168     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2169       return ReplaceInstUsesWith(I, LHS);
2170
2171   // Check for (add (sext x), y), see if we can merge this into an
2172   // integer add followed by a sext.
2173   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2174     // (add (sext x), cst) --> (sext (add x, cst'))
2175     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2176       Constant *CI = 
2177         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2178       if (LHSConv->hasOneUse() &&
2179           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2180           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2181         // Insert the new, smaller add.
2182         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2183                                                         CI, "addconv");
2184         InsertNewInstBefore(NewAdd, I);
2185         return new SExtInst(NewAdd, I.getType());
2186       }
2187     }
2188     
2189     // (add (sext x), (sext y)) --> (sext (add int x, y))
2190     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2191       // Only do this if x/y have the same type, if at last one of them has a
2192       // single use (so we don't increase the number of sexts), and if the
2193       // integer add will not overflow.
2194       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2195           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2196           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2197                                    RHSConv->getOperand(0))) {
2198         // Insert the new integer add.
2199         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2200                                                         RHSConv->getOperand(0),
2201                                                         "addconv");
2202         InsertNewInstBefore(NewAdd, I);
2203         return new SExtInst(NewAdd, I.getType());
2204       }
2205     }
2206   }
2207   
2208   // Check for (add double (sitofp x), y), see if we can merge this into an
2209   // integer add followed by a promotion.
2210   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2211     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2212     // ... if the constant fits in the integer value.  This is useful for things
2213     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2214     // requires a constant pool load, and generally allows the add to be better
2215     // instcombined.
2216     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2217       Constant *CI = 
2218       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2219       if (LHSConv->hasOneUse() &&
2220           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2221           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2222         // Insert the new integer add.
2223         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2224                                                         CI, "addconv");
2225         InsertNewInstBefore(NewAdd, I);
2226         return new SIToFPInst(NewAdd, I.getType());
2227       }
2228     }
2229     
2230     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2231     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2232       // Only do this if x/y have the same type, if at last one of them has a
2233       // single use (so we don't increase the number of int->fp conversions),
2234       // and if the integer add will not overflow.
2235       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2236           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2237           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2238                                    RHSConv->getOperand(0))) {
2239         // Insert the new integer add.
2240         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2241                                                         RHSConv->getOperand(0),
2242                                                         "addconv");
2243         InsertNewInstBefore(NewAdd, I);
2244         return new SIToFPInst(NewAdd, I.getType());
2245       }
2246     }
2247   }
2248   
2249   return Changed ? &I : 0;
2250 }
2251
2252 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2253   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2254
2255   if (Op0 == Op1 &&                        // sub X, X  -> 0
2256       !I.getType()->isFPOrFPVector())
2257     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2258
2259   // If this is a 'B = x-(-A)', change to B = x+A...
2260   if (Value *V = dyn_castNegVal(Op1))
2261     return BinaryOperator::CreateAdd(Op0, V);
2262
2263   if (isa<UndefValue>(Op0))
2264     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2265   if (isa<UndefValue>(Op1))
2266     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2267
2268   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2269     // Replace (-1 - A) with (~A)...
2270     if (C->isAllOnesValue())
2271       return BinaryOperator::CreateNot(Op1);
2272
2273     // C - ~X == X + (1+C)
2274     Value *X = 0;
2275     if (match(Op1, m_Not(m_Value(X))))
2276       return BinaryOperator::CreateAdd(X, AddOne(C));
2277
2278     // -(X >>u 31) -> (X >>s 31)
2279     // -(X >>s 31) -> (X >>u 31)
2280     if (C->isZero()) {
2281       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2282         if (SI->getOpcode() == Instruction::LShr) {
2283           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2284             // Check to see if we are shifting out everything but the sign bit.
2285             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2286                 SI->getType()->getPrimitiveSizeInBits()-1) {
2287               // Ok, the transformation is safe.  Insert AShr.
2288               return BinaryOperator::Create(Instruction::AShr, 
2289                                           SI->getOperand(0), CU, SI->getName());
2290             }
2291           }
2292         }
2293         else if (SI->getOpcode() == Instruction::AShr) {
2294           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2295             // Check to see if we are shifting out everything but the sign bit.
2296             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2297                 SI->getType()->getPrimitiveSizeInBits()-1) {
2298               // Ok, the transformation is safe.  Insert LShr. 
2299               return BinaryOperator::CreateLShr(
2300                                           SI->getOperand(0), CU, SI->getName());
2301             }
2302           }
2303         }
2304       }
2305     }
2306
2307     // Try to fold constant sub into select arguments.
2308     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2309       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2310         return R;
2311
2312     if (isa<PHINode>(Op0))
2313       if (Instruction *NV = FoldOpIntoPhi(I))
2314         return NV;
2315   }
2316
2317   if (I.getType() == Type::Int1Ty)
2318     return BinaryOperator::CreateXor(Op0, Op1);
2319
2320   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2321     if (Op1I->getOpcode() == Instruction::Add &&
2322         !Op0->getType()->isFPOrFPVector()) {
2323       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2324         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2325       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2326         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2327       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2328         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2329           // C1-(X+C2) --> (C1-C2)-X
2330           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2331                                            Op1I->getOperand(0));
2332       }
2333     }
2334
2335     if (Op1I->hasOneUse()) {
2336       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2337       // is not used by anyone else...
2338       //
2339       if (Op1I->getOpcode() == Instruction::Sub &&
2340           !Op1I->getType()->isFPOrFPVector()) {
2341         // Swap the two operands of the subexpr...
2342         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2343         Op1I->setOperand(0, IIOp1);
2344         Op1I->setOperand(1, IIOp0);
2345
2346         // Create the new top level add instruction...
2347         return BinaryOperator::CreateAdd(Op0, Op1);
2348       }
2349
2350       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2351       //
2352       if (Op1I->getOpcode() == Instruction::And &&
2353           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2354         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2355
2356         Value *NewNot =
2357           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2358         return BinaryOperator::CreateAnd(Op0, NewNot);
2359       }
2360
2361       // 0 - (X sdiv C)  -> (X sdiv -C)
2362       if (Op1I->getOpcode() == Instruction::SDiv)
2363         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2364           if (CSI->isZero())
2365             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2366               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2367                                                ConstantExpr::getNeg(DivRHS));
2368
2369       // X - X*C --> X * (1-C)
2370       ConstantInt *C2 = 0;
2371       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2372         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2373         return BinaryOperator::CreateMul(Op0, CP1);
2374       }
2375
2376       // X - ((X / Y) * Y) --> X % Y
2377       if (Op1I->getOpcode() == Instruction::Mul)
2378         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2379           if (Op0 == I->getOperand(0) &&
2380               Op1I->getOperand(1) == I->getOperand(1)) {
2381             if (I->getOpcode() == Instruction::SDiv)
2382               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2383             if (I->getOpcode() == Instruction::UDiv)
2384               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2385           }
2386     }
2387   }
2388
2389   if (!Op0->getType()->isFPOrFPVector())
2390     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2391       if (Op0I->getOpcode() == Instruction::Add) {
2392         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2393           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2394         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2395           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2396       } else if (Op0I->getOpcode() == Instruction::Sub) {
2397         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2398           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2399       }
2400     }
2401
2402   ConstantInt *C1;
2403   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2404     if (X == Op1)  // X*C - X --> X * (C-1)
2405       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2406
2407     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2408     if (X == dyn_castFoldableMul(Op1, C2))
2409       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2410   }
2411   return 0;
2412 }
2413
2414 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2415 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2416 /// TrueIfSigned if the result of the comparison is true when the input value is
2417 /// signed.
2418 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2419                            bool &TrueIfSigned) {
2420   switch (pred) {
2421   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2422     TrueIfSigned = true;
2423     return RHS->isZero();
2424   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2425     TrueIfSigned = true;
2426     return RHS->isAllOnesValue();
2427   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2428     TrueIfSigned = false;
2429     return RHS->isAllOnesValue();
2430   case ICmpInst::ICMP_UGT:
2431     // True if LHS u> RHS and RHS == high-bit-mask - 1
2432     TrueIfSigned = true;
2433     return RHS->getValue() ==
2434       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2435   case ICmpInst::ICMP_UGE: 
2436     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2437     TrueIfSigned = true;
2438     return RHS->getValue().isSignBit();
2439   default:
2440     return false;
2441   }
2442 }
2443
2444 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2445   bool Changed = SimplifyCommutative(I);
2446   Value *Op0 = I.getOperand(0);
2447
2448   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2449     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2450
2451   // Simplify mul instructions with a constant RHS...
2452   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2453     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2454
2455       // ((X << C1)*C2) == (X * (C2 << C1))
2456       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2457         if (SI->getOpcode() == Instruction::Shl)
2458           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2459             return BinaryOperator::CreateMul(SI->getOperand(0),
2460                                              ConstantExpr::getShl(CI, ShOp));
2461
2462       if (CI->isZero())
2463         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2464       if (CI->equalsInt(1))                  // X * 1  == X
2465         return ReplaceInstUsesWith(I, Op0);
2466       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2467         return BinaryOperator::CreateNeg(Op0, I.getName());
2468
2469       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2470       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2471         return BinaryOperator::CreateShl(Op0,
2472                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2473       }
2474     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2475       if (Op1F->isNullValue())
2476         return ReplaceInstUsesWith(I, Op1);
2477
2478       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2479       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2480       if (Op1F->isExactlyValue(1.0))
2481         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2482     } else if (isa<VectorType>(Op1->getType())) {
2483       if (isa<ConstantAggregateZero>(Op1))
2484         return ReplaceInstUsesWith(I, Op1);
2485       
2486       // As above, vector X*splat(1.0) -> X in all defined cases.
2487       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1))
2488         if (ConstantFP *F = dyn_cast_or_null<ConstantFP>(Op1V->getSplatValue()))
2489           if (F->isExactlyValue(1.0))
2490             return ReplaceInstUsesWith(I, Op0);
2491     }
2492     
2493     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2494       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2495           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2496         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2497         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2498                                                      Op1, "tmp");
2499         InsertNewInstBefore(Add, I);
2500         Value *C1C2 = ConstantExpr::getMul(Op1, 
2501                                            cast<Constant>(Op0I->getOperand(1)));
2502         return BinaryOperator::CreateAdd(Add, C1C2);
2503         
2504       }
2505
2506     // Try to fold constant mul into select arguments.
2507     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2508       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2509         return R;
2510
2511     if (isa<PHINode>(Op0))
2512       if (Instruction *NV = FoldOpIntoPhi(I))
2513         return NV;
2514   }
2515
2516   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2517     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2518       return BinaryOperator::CreateMul(Op0v, Op1v);
2519
2520   if (I.getType() == Type::Int1Ty)
2521     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2522
2523   // If one of the operands of the multiply is a cast from a boolean value, then
2524   // we know the bool is either zero or one, so this is a 'masking' multiply.
2525   // See if we can simplify things based on how the boolean was originally
2526   // formed.
2527   CastInst *BoolCast = 0;
2528   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2529     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2530       BoolCast = CI;
2531   if (!BoolCast)
2532     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2533       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2534         BoolCast = CI;
2535   if (BoolCast) {
2536     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2537       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2538       const Type *SCOpTy = SCIOp0->getType();
2539       bool TIS = false;
2540       
2541       // If the icmp is true iff the sign bit of X is set, then convert this
2542       // multiply into a shift/and combination.
2543       if (isa<ConstantInt>(SCIOp1) &&
2544           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2545           TIS) {
2546         // Shift the X value right to turn it into "all signbits".
2547         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2548                                           SCOpTy->getPrimitiveSizeInBits()-1);
2549         Value *V =
2550           InsertNewInstBefore(
2551             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2552                                             BoolCast->getOperand(0)->getName()+
2553                                             ".mask"), I);
2554
2555         // If the multiply type is not the same as the source type, sign extend
2556         // or truncate to the multiply type.
2557         if (I.getType() != V->getType()) {
2558           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2559           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2560           Instruction::CastOps opcode = 
2561             (SrcBits == DstBits ? Instruction::BitCast : 
2562              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2563           V = InsertCastBefore(opcode, V, I.getType(), I);
2564         }
2565
2566         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2567         return BinaryOperator::CreateAnd(V, OtherOp);
2568       }
2569     }
2570   }
2571
2572   return Changed ? &I : 0;
2573 }
2574
2575 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2576 /// instruction.
2577 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2578   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2579   
2580   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2581   int NonNullOperand = -1;
2582   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2583     if (ST->isNullValue())
2584       NonNullOperand = 2;
2585   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2586   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2587     if (ST->isNullValue())
2588       NonNullOperand = 1;
2589   
2590   if (NonNullOperand == -1)
2591     return false;
2592   
2593   Value *SelectCond = SI->getOperand(0);
2594   
2595   // Change the div/rem to use 'Y' instead of the select.
2596   I.setOperand(1, SI->getOperand(NonNullOperand));
2597   
2598   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2599   // problem.  However, the select, or the condition of the select may have
2600   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2601   // propagate the known value for the select into other uses of it, and
2602   // propagate a known value of the condition into its other users.
2603   
2604   // If the select and condition only have a single use, don't bother with this,
2605   // early exit.
2606   if (SI->use_empty() && SelectCond->hasOneUse())
2607     return true;
2608   
2609   // Scan the current block backward, looking for other uses of SI.
2610   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2611   
2612   while (BBI != BBFront) {
2613     --BBI;
2614     // If we found a call to a function, we can't assume it will return, so
2615     // information from below it cannot be propagated above it.
2616     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2617       break;
2618     
2619     // Replace uses of the select or its condition with the known values.
2620     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2621          I != E; ++I) {
2622       if (*I == SI) {
2623         *I = SI->getOperand(NonNullOperand);
2624         AddToWorkList(BBI);
2625       } else if (*I == SelectCond) {
2626         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2627                                    ConstantInt::getFalse();
2628         AddToWorkList(BBI);
2629       }
2630     }
2631     
2632     // If we past the instruction, quit looking for it.
2633     if (&*BBI == SI)
2634       SI = 0;
2635     if (&*BBI == SelectCond)
2636       SelectCond = 0;
2637     
2638     // If we ran out of things to eliminate, break out of the loop.
2639     if (SelectCond == 0 && SI == 0)
2640       break;
2641     
2642   }
2643   return true;
2644 }
2645
2646
2647 /// This function implements the transforms on div instructions that work
2648 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2649 /// used by the visitors to those instructions.
2650 /// @brief Transforms common to all three div instructions
2651 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2652   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2653
2654   // undef / X -> 0        for integer.
2655   // undef / X -> undef    for FP (the undef could be a snan).
2656   if (isa<UndefValue>(Op0)) {
2657     if (Op0->getType()->isFPOrFPVector())
2658       return ReplaceInstUsesWith(I, Op0);
2659     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2660   }
2661
2662   // X / undef -> undef
2663   if (isa<UndefValue>(Op1))
2664     return ReplaceInstUsesWith(I, Op1);
2665
2666   return 0;
2667 }
2668
2669 /// This function implements the transforms common to both integer division
2670 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2671 /// division instructions.
2672 /// @brief Common integer divide transforms
2673 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2674   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2675
2676   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2677   if (Op0 == Op1) {
2678     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2679       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2680       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2681       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2682     }
2683
2684     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2685     return ReplaceInstUsesWith(I, CI);
2686   }
2687   
2688   if (Instruction *Common = commonDivTransforms(I))
2689     return Common;
2690   
2691   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2692   // This does not apply for fdiv.
2693   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2694     return &I;
2695
2696   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2697     // div X, 1 == X
2698     if (RHS->equalsInt(1))
2699       return ReplaceInstUsesWith(I, Op0);
2700
2701     // (X / C1) / C2  -> X / (C1*C2)
2702     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2703       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2704         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2705           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2706             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2707           else 
2708             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2709                                           Multiply(RHS, LHSRHS));
2710         }
2711
2712     if (!RHS->isZero()) { // avoid X udiv 0
2713       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2714         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2715           return R;
2716       if (isa<PHINode>(Op0))
2717         if (Instruction *NV = FoldOpIntoPhi(I))
2718           return NV;
2719     }
2720   }
2721
2722   // 0 / X == 0, we don't need to preserve faults!
2723   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2724     if (LHS->equalsInt(0))
2725       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2726
2727   // It can't be division by zero, hence it must be division by one.
2728   if (I.getType() == Type::Int1Ty)
2729     return ReplaceInstUsesWith(I, Op0);
2730
2731   return 0;
2732 }
2733
2734 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2735   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2736
2737   // Handle the integer div common cases
2738   if (Instruction *Common = commonIDivTransforms(I))
2739     return Common;
2740
2741   // X udiv C^2 -> X >> C
2742   // Check to see if this is an unsigned division with an exact power of 2,
2743   // if so, convert to a right shift.
2744   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2745     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2746       return BinaryOperator::CreateLShr(Op0, 
2747                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2748   }
2749
2750   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2751   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2752     if (RHSI->getOpcode() == Instruction::Shl &&
2753         isa<ConstantInt>(RHSI->getOperand(0))) {
2754       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2755       if (C1.isPowerOf2()) {
2756         Value *N = RHSI->getOperand(1);
2757         const Type *NTy = N->getType();
2758         if (uint32_t C2 = C1.logBase2()) {
2759           Constant *C2V = ConstantInt::get(NTy, C2);
2760           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2761         }
2762         return BinaryOperator::CreateLShr(Op0, N);
2763       }
2764     }
2765   }
2766   
2767   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2768   // where C1&C2 are powers of two.
2769   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2770     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2771       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2772         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2773         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2774           // Compute the shift amounts
2775           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2776           // Construct the "on true" case of the select
2777           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2778           Instruction *TSI = BinaryOperator::CreateLShr(
2779                                                  Op0, TC, SI->getName()+".t");
2780           TSI = InsertNewInstBefore(TSI, I);
2781   
2782           // Construct the "on false" case of the select
2783           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2784           Instruction *FSI = BinaryOperator::CreateLShr(
2785                                                  Op0, FC, SI->getName()+".f");
2786           FSI = InsertNewInstBefore(FSI, I);
2787
2788           // construct the select instruction and return it.
2789           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2790         }
2791       }
2792   return 0;
2793 }
2794
2795 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2796   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2797
2798   // Handle the integer div common cases
2799   if (Instruction *Common = commonIDivTransforms(I))
2800     return Common;
2801
2802   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2803     // sdiv X, -1 == -X
2804     if (RHS->isAllOnesValue())
2805       return BinaryOperator::CreateNeg(Op0);
2806
2807     // -X/C -> X/-C
2808     if (Value *LHSNeg = dyn_castNegVal(Op0))
2809       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2810   }
2811
2812   // If the sign bits of both operands are zero (i.e. we can prove they are
2813   // unsigned inputs), turn this into a udiv.
2814   if (I.getType()->isInteger()) {
2815     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2816     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2817       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2818       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2819     }
2820   }      
2821   
2822   return 0;
2823 }
2824
2825 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2826   return commonDivTransforms(I);
2827 }
2828
2829 /// This function implements the transforms on rem instructions that work
2830 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2831 /// is used by the visitors to those instructions.
2832 /// @brief Transforms common to all three rem instructions
2833 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2834   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2835
2836   // 0 % X == 0 for integer, we don't need to preserve faults!
2837   if (Constant *LHS = dyn_cast<Constant>(Op0))
2838     if (LHS->isNullValue())
2839       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2840
2841   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2842     if (I.getType()->isFPOrFPVector())
2843       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2844     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2845   }
2846   if (isa<UndefValue>(Op1))
2847     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2848
2849   // Handle cases involving: rem X, (select Cond, Y, Z)
2850   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2851     return &I;
2852
2853   return 0;
2854 }
2855
2856 /// This function implements the transforms common to both integer remainder
2857 /// instructions (urem and srem). It is called by the visitors to those integer
2858 /// remainder instructions.
2859 /// @brief Common integer remainder transforms
2860 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2861   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2862
2863   if (Instruction *common = commonRemTransforms(I))
2864     return common;
2865
2866   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2867     // X % 0 == undef, we don't need to preserve faults!
2868     if (RHS->equalsInt(0))
2869       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2870     
2871     if (RHS->equalsInt(1))  // X % 1 == 0
2872       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2873
2874     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2875       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2876         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2877           return R;
2878       } else if (isa<PHINode>(Op0I)) {
2879         if (Instruction *NV = FoldOpIntoPhi(I))
2880           return NV;
2881       }
2882
2883       // See if we can fold away this rem instruction.
2884       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2885       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2886       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2887                                KnownZero, KnownOne))
2888         return &I;
2889     }
2890   }
2891
2892   return 0;
2893 }
2894
2895 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2896   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2897
2898   if (Instruction *common = commonIRemTransforms(I))
2899     return common;
2900   
2901   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2902     // X urem C^2 -> X and C
2903     // Check to see if this is an unsigned remainder with an exact power of 2,
2904     // if so, convert to a bitwise and.
2905     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2906       if (C->getValue().isPowerOf2())
2907         return BinaryOperator::CreateAnd(Op0, SubOne(C));
2908   }
2909
2910   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2911     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2912     if (RHSI->getOpcode() == Instruction::Shl &&
2913         isa<ConstantInt>(RHSI->getOperand(0))) {
2914       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2915         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2916         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2917                                                                    "tmp"), I);
2918         return BinaryOperator::CreateAnd(Op0, Add);
2919       }
2920     }
2921   }
2922
2923   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2924   // where C1&C2 are powers of two.
2925   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2926     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2927       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2928         // STO == 0 and SFO == 0 handled above.
2929         if ((STO->getValue().isPowerOf2()) && 
2930             (SFO->getValue().isPowerOf2())) {
2931           Value *TrueAnd = InsertNewInstBefore(
2932             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2933           Value *FalseAnd = InsertNewInstBefore(
2934             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2935           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2936         }
2937       }
2938   }
2939   
2940   return 0;
2941 }
2942
2943 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2944   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2945
2946   // Handle the integer rem common cases
2947   if (Instruction *common = commonIRemTransforms(I))
2948     return common;
2949   
2950   if (Value *RHSNeg = dyn_castNegVal(Op1))
2951     if (!isa<ConstantInt>(RHSNeg) || 
2952         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2953       // X % -Y -> X % Y
2954       AddUsesToWorkList(I);
2955       I.setOperand(1, RHSNeg);
2956       return &I;
2957     }
2958  
2959   // If the sign bits of both operands are zero (i.e. we can prove they are
2960   // unsigned inputs), turn this into a urem.
2961   if (I.getType()->isInteger()) {
2962     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2963     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2964       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2965       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2966     }
2967   }
2968
2969   return 0;
2970 }
2971
2972 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2973   return commonRemTransforms(I);
2974 }
2975
2976 // isOneBitSet - Return true if there is exactly one bit set in the specified
2977 // constant.
2978 static bool isOneBitSet(const ConstantInt *CI) {
2979   return CI->getValue().isPowerOf2();
2980 }
2981
2982 // isHighOnes - Return true if the constant is of the form 1+0+.
2983 // This is the same as lowones(~X).
2984 static bool isHighOnes(const ConstantInt *CI) {
2985   return (~CI->getValue() + 1).isPowerOf2();
2986 }
2987
2988 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2989 /// are carefully arranged to allow folding of expressions such as:
2990 ///
2991 ///      (A < B) | (A > B) --> (A != B)
2992 ///
2993 /// Note that this is only valid if the first and second predicates have the
2994 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2995 ///
2996 /// Three bits are used to represent the condition, as follows:
2997 ///   0  A > B
2998 ///   1  A == B
2999 ///   2  A < B
3000 ///
3001 /// <=>  Value  Definition
3002 /// 000     0   Always false
3003 /// 001     1   A >  B
3004 /// 010     2   A == B
3005 /// 011     3   A >= B
3006 /// 100     4   A <  B
3007 /// 101     5   A != B
3008 /// 110     6   A <= B
3009 /// 111     7   Always true
3010 ///  
3011 static unsigned getICmpCode(const ICmpInst *ICI) {
3012   switch (ICI->getPredicate()) {
3013     // False -> 0
3014   case ICmpInst::ICMP_UGT: return 1;  // 001
3015   case ICmpInst::ICMP_SGT: return 1;  // 001
3016   case ICmpInst::ICMP_EQ:  return 2;  // 010
3017   case ICmpInst::ICMP_UGE: return 3;  // 011
3018   case ICmpInst::ICMP_SGE: return 3;  // 011
3019   case ICmpInst::ICMP_ULT: return 4;  // 100
3020   case ICmpInst::ICMP_SLT: return 4;  // 100
3021   case ICmpInst::ICMP_NE:  return 5;  // 101
3022   case ICmpInst::ICMP_ULE: return 6;  // 110
3023   case ICmpInst::ICMP_SLE: return 6;  // 110
3024     // True -> 7
3025   default:
3026     assert(0 && "Invalid ICmp predicate!");
3027     return 0;
3028   }
3029 }
3030
3031 /// getICmpValue - This is the complement of getICmpCode, which turns an
3032 /// opcode and two operands into either a constant true or false, or a brand 
3033 /// new ICmp instruction. The sign is passed in to determine which kind
3034 /// of predicate to use in new icmp instructions.
3035 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3036   switch (code) {
3037   default: assert(0 && "Illegal ICmp code!");
3038   case  0: return ConstantInt::getFalse();
3039   case  1: 
3040     if (sign)
3041       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3042     else
3043       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3044   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3045   case  3: 
3046     if (sign)
3047       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3048     else
3049       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3050   case  4: 
3051     if (sign)
3052       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3053     else
3054       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3055   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3056   case  6: 
3057     if (sign)
3058       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3059     else
3060       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3061   case  7: return ConstantInt::getTrue();
3062   }
3063 }
3064
3065 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3066   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3067     (ICmpInst::isSignedPredicate(p1) && 
3068      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3069     (ICmpInst::isSignedPredicate(p2) && 
3070      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3071 }
3072
3073 namespace { 
3074 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3075 struct FoldICmpLogical {
3076   InstCombiner &IC;
3077   Value *LHS, *RHS;
3078   ICmpInst::Predicate pred;
3079   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3080     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3081       pred(ICI->getPredicate()) {}
3082   bool shouldApply(Value *V) const {
3083     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3084       if (PredicatesFoldable(pred, ICI->getPredicate()))
3085         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3086                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3087     return false;
3088   }
3089   Instruction *apply(Instruction &Log) const {
3090     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3091     if (ICI->getOperand(0) != LHS) {
3092       assert(ICI->getOperand(1) == LHS);
3093       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3094     }
3095
3096     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3097     unsigned LHSCode = getICmpCode(ICI);
3098     unsigned RHSCode = getICmpCode(RHSICI);
3099     unsigned Code;
3100     switch (Log.getOpcode()) {
3101     case Instruction::And: Code = LHSCode & RHSCode; break;
3102     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3103     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3104     default: assert(0 && "Illegal logical opcode!"); return 0;
3105     }
3106
3107     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3108                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3109       
3110     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3111     if (Instruction *I = dyn_cast<Instruction>(RV))
3112       return I;
3113     // Otherwise, it's a constant boolean value...
3114     return IC.ReplaceInstUsesWith(Log, RV);
3115   }
3116 };
3117 } // end anonymous namespace
3118
3119 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3120 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3121 // guaranteed to be a binary operator.
3122 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3123                                     ConstantInt *OpRHS,
3124                                     ConstantInt *AndRHS,
3125                                     BinaryOperator &TheAnd) {
3126   Value *X = Op->getOperand(0);
3127   Constant *Together = 0;
3128   if (!Op->isShift())
3129     Together = And(AndRHS, OpRHS);
3130
3131   switch (Op->getOpcode()) {
3132   case Instruction::Xor:
3133     if (Op->hasOneUse()) {
3134       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3135       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3136       InsertNewInstBefore(And, TheAnd);
3137       And->takeName(Op);
3138       return BinaryOperator::CreateXor(And, Together);
3139     }
3140     break;
3141   case Instruction::Or:
3142     if (Together == AndRHS) // (X | C) & C --> C
3143       return ReplaceInstUsesWith(TheAnd, AndRHS);
3144
3145     if (Op->hasOneUse() && Together != OpRHS) {
3146       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3147       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3148       InsertNewInstBefore(Or, TheAnd);
3149       Or->takeName(Op);
3150       return BinaryOperator::CreateAnd(Or, AndRHS);
3151     }
3152     break;
3153   case Instruction::Add:
3154     if (Op->hasOneUse()) {
3155       // Adding a one to a single bit bit-field should be turned into an XOR
3156       // of the bit.  First thing to check is to see if this AND is with a
3157       // single bit constant.
3158       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3159
3160       // If there is only one bit set...
3161       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3162         // Ok, at this point, we know that we are masking the result of the
3163         // ADD down to exactly one bit.  If the constant we are adding has
3164         // no bits set below this bit, then we can eliminate the ADD.
3165         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3166
3167         // Check to see if any bits below the one bit set in AndRHSV are set.
3168         if ((AddRHS & (AndRHSV-1)) == 0) {
3169           // If not, the only thing that can effect the output of the AND is
3170           // the bit specified by AndRHSV.  If that bit is set, the effect of
3171           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3172           // no effect.
3173           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3174             TheAnd.setOperand(0, X);
3175             return &TheAnd;
3176           } else {
3177             // Pull the XOR out of the AND.
3178             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3179             InsertNewInstBefore(NewAnd, TheAnd);
3180             NewAnd->takeName(Op);
3181             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3182           }
3183         }
3184       }
3185     }
3186     break;
3187
3188   case Instruction::Shl: {
3189     // We know that the AND will not produce any of the bits shifted in, so if
3190     // the anded constant includes them, clear them now!
3191     //
3192     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3193     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3194     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3195     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3196
3197     if (CI->getValue() == ShlMask) { 
3198     // Masking out bits that the shift already masks
3199       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3200     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3201       TheAnd.setOperand(1, CI);
3202       return &TheAnd;
3203     }
3204     break;
3205   }
3206   case Instruction::LShr:
3207   {
3208     // We know that the AND will not produce any of the bits shifted in, so if
3209     // the anded constant includes them, clear them now!  This only applies to
3210     // unsigned shifts, because a signed shr may bring in set bits!
3211     //
3212     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3213     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3214     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3215     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3216
3217     if (CI->getValue() == ShrMask) {   
3218     // Masking out bits that the shift already masks.
3219       return ReplaceInstUsesWith(TheAnd, Op);
3220     } else if (CI != AndRHS) {
3221       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3222       return &TheAnd;
3223     }
3224     break;
3225   }
3226   case Instruction::AShr:
3227     // Signed shr.
3228     // See if this is shifting in some sign extension, then masking it out
3229     // with an and.
3230     if (Op->hasOneUse()) {
3231       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3232       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3233       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3234       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3235       if (C == AndRHS) {          // Masking out bits shifted in.
3236         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3237         // Make the argument unsigned.
3238         Value *ShVal = Op->getOperand(0);
3239         ShVal = InsertNewInstBefore(
3240             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3241                                    Op->getName()), TheAnd);
3242         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3243       }
3244     }
3245     break;
3246   }
3247   return 0;
3248 }
3249
3250
3251 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3252 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3253 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3254 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3255 /// insert new instructions.
3256 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3257                                            bool isSigned, bool Inside, 
3258                                            Instruction &IB) {
3259   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3260             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3261          "Lo is not <= Hi in range emission code!");
3262     
3263   if (Inside) {
3264     if (Lo == Hi)  // Trivially false.
3265       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3266
3267     // V >= Min && V < Hi --> V < Hi
3268     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3269       ICmpInst::Predicate pred = (isSigned ? 
3270         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3271       return new ICmpInst(pred, V, Hi);
3272     }
3273
3274     // Emit V-Lo <u Hi-Lo
3275     Constant *NegLo = ConstantExpr::getNeg(Lo);
3276     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3277     InsertNewInstBefore(Add, IB);
3278     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3279     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3280   }
3281
3282   if (Lo == Hi)  // Trivially true.
3283     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3284
3285   // V < Min || V >= Hi -> V > Hi-1
3286   Hi = SubOne(cast<ConstantInt>(Hi));
3287   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3288     ICmpInst::Predicate pred = (isSigned ? 
3289         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3290     return new ICmpInst(pred, V, Hi);
3291   }
3292
3293   // Emit V-Lo >u Hi-1-Lo
3294   // Note that Hi has already had one subtracted from it, above.
3295   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3296   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3297   InsertNewInstBefore(Add, IB);
3298   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3299   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3300 }
3301
3302 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3303 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3304 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3305 // not, since all 1s are not contiguous.
3306 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3307   const APInt& V = Val->getValue();
3308   uint32_t BitWidth = Val->getType()->getBitWidth();
3309   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3310
3311   // look for the first zero bit after the run of ones
3312   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3313   // look for the first non-zero bit
3314   ME = V.getActiveBits(); 
3315   return true;
3316 }
3317
3318 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3319 /// where isSub determines whether the operator is a sub.  If we can fold one of
3320 /// the following xforms:
3321 /// 
3322 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3323 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3324 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3325 ///
3326 /// return (A +/- B).
3327 ///
3328 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3329                                         ConstantInt *Mask, bool isSub,
3330                                         Instruction &I) {
3331   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3332   if (!LHSI || LHSI->getNumOperands() != 2 ||
3333       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3334
3335   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3336
3337   switch (LHSI->getOpcode()) {
3338   default: return 0;
3339   case Instruction::And:
3340     if (And(N, Mask) == Mask) {
3341       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3342       if ((Mask->getValue().countLeadingZeros() + 
3343            Mask->getValue().countPopulation()) == 
3344           Mask->getValue().getBitWidth())
3345         break;
3346
3347       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3348       // part, we don't need any explicit masks to take them out of A.  If that
3349       // is all N is, ignore it.
3350       uint32_t MB = 0, ME = 0;
3351       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3352         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3353         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3354         if (MaskedValueIsZero(RHS, Mask))
3355           break;
3356       }
3357     }
3358     return 0;
3359   case Instruction::Or:
3360   case Instruction::Xor:
3361     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3362     if ((Mask->getValue().countLeadingZeros() + 
3363          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3364         && And(N, Mask)->isZero())
3365       break;
3366     return 0;
3367   }
3368   
3369   Instruction *New;
3370   if (isSub)
3371     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3372   else
3373     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3374   return InsertNewInstBefore(New, I);
3375 }
3376
3377 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3378   bool Changed = SimplifyCommutative(I);
3379   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3380
3381   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3382     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3383
3384   // and X, X = X
3385   if (Op0 == Op1)
3386     return ReplaceInstUsesWith(I, Op1);
3387
3388   // See if we can simplify any instructions used by the instruction whose sole 
3389   // purpose is to compute bits we don't care about.
3390   if (!isa<VectorType>(I.getType())) {
3391     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3392     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3393     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3394                              KnownZero, KnownOne))
3395       return &I;
3396   } else {
3397     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3398       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3399         return ReplaceInstUsesWith(I, I.getOperand(0));
3400     } else if (isa<ConstantAggregateZero>(Op1)) {
3401       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3402     }
3403   }
3404   
3405   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3406     const APInt& AndRHSMask = AndRHS->getValue();
3407     APInt NotAndRHS(~AndRHSMask);
3408
3409     // Optimize a variety of ((val OP C1) & C2) combinations...
3410     if (isa<BinaryOperator>(Op0)) {
3411       Instruction *Op0I = cast<Instruction>(Op0);
3412       Value *Op0LHS = Op0I->getOperand(0);
3413       Value *Op0RHS = Op0I->getOperand(1);
3414       switch (Op0I->getOpcode()) {
3415       case Instruction::Xor:
3416       case Instruction::Or:
3417         // If the mask is only needed on one incoming arm, push it up.
3418         if (Op0I->hasOneUse()) {
3419           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3420             // Not masking anything out for the LHS, move to RHS.
3421             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3422                                                    Op0RHS->getName()+".masked");
3423             InsertNewInstBefore(NewRHS, I);
3424             return BinaryOperator::Create(
3425                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3426           }
3427           if (!isa<Constant>(Op0RHS) &&
3428               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3429             // Not masking anything out for the RHS, move to LHS.
3430             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3431                                                    Op0LHS->getName()+".masked");
3432             InsertNewInstBefore(NewLHS, I);
3433             return BinaryOperator::Create(
3434                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3435           }
3436         }
3437
3438         break;
3439       case Instruction::Add:
3440         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3441         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3442         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3443         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3444           return BinaryOperator::CreateAnd(V, AndRHS);
3445         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3446           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3447         break;
3448
3449       case Instruction::Sub:
3450         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3451         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3452         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3453         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3454           return BinaryOperator::CreateAnd(V, AndRHS);
3455
3456         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3457         // has 1's for all bits that the subtraction with A might affect.
3458         if (Op0I->hasOneUse()) {
3459           uint32_t BitWidth = AndRHSMask.getBitWidth();
3460           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3461           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3462
3463           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3464           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3465               MaskedValueIsZero(Op0LHS, Mask)) {
3466             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3467             InsertNewInstBefore(NewNeg, I);
3468             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3469           }
3470         }
3471         break;
3472
3473       case Instruction::Shl:
3474       case Instruction::LShr:
3475         // (1 << x) & 1 --> zext(x == 0)
3476         // (1 >> x) & 1 --> zext(x == 0)
3477         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3478           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3479                                            Constant::getNullValue(I.getType()));
3480           InsertNewInstBefore(NewICmp, I);
3481           return new ZExtInst(NewICmp, I.getType());
3482         }
3483         break;
3484       }
3485
3486       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3487         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3488           return Res;
3489     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3490       // If this is an integer truncation or change from signed-to-unsigned, and
3491       // if the source is an and/or with immediate, transform it.  This
3492       // frequently occurs for bitfield accesses.
3493       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3494         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3495             CastOp->getNumOperands() == 2)
3496           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3497             if (CastOp->getOpcode() == Instruction::And) {
3498               // Change: and (cast (and X, C1) to T), C2
3499               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3500               // This will fold the two constants together, which may allow 
3501               // other simplifications.
3502               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3503                 CastOp->getOperand(0), I.getType(), 
3504                 CastOp->getName()+".shrunk");
3505               NewCast = InsertNewInstBefore(NewCast, I);
3506               // trunc_or_bitcast(C1)&C2
3507               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3508               C3 = ConstantExpr::getAnd(C3, AndRHS);
3509               return BinaryOperator::CreateAnd(NewCast, C3);
3510             } else if (CastOp->getOpcode() == Instruction::Or) {
3511               // Change: and (cast (or X, C1) to T), C2
3512               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3513               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3514               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3515                 return ReplaceInstUsesWith(I, AndRHS);
3516             }
3517           }
3518       }
3519     }
3520
3521     // Try to fold constant and into select arguments.
3522     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3523       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3524         return R;
3525     if (isa<PHINode>(Op0))
3526       if (Instruction *NV = FoldOpIntoPhi(I))
3527         return NV;
3528   }
3529
3530   Value *Op0NotVal = dyn_castNotVal(Op0);
3531   Value *Op1NotVal = dyn_castNotVal(Op1);
3532
3533   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3534     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3535
3536   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3537   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3538     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3539                                                I.getName()+".demorgan");
3540     InsertNewInstBefore(Or, I);
3541     return BinaryOperator::CreateNot(Or);
3542   }
3543   
3544   {
3545     Value *A = 0, *B = 0, *C = 0, *D = 0;
3546     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3547       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3548         return ReplaceInstUsesWith(I, Op1);
3549     
3550       // (A|B) & ~(A&B) -> A^B
3551       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3552         if ((A == C && B == D) || (A == D && B == C))
3553           return BinaryOperator::CreateXor(A, B);
3554       }
3555     }
3556     
3557     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3558       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3559         return ReplaceInstUsesWith(I, Op0);
3560
3561       // ~(A&B) & (A|B) -> A^B
3562       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3563         if ((A == C && B == D) || (A == D && B == C))
3564           return BinaryOperator::CreateXor(A, B);
3565       }
3566     }
3567     
3568     if (Op0->hasOneUse() &&
3569         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3570       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3571         I.swapOperands();     // Simplify below
3572         std::swap(Op0, Op1);
3573       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3574         cast<BinaryOperator>(Op0)->swapOperands();
3575         I.swapOperands();     // Simplify below
3576         std::swap(Op0, Op1);
3577       }
3578     }
3579     if (Op1->hasOneUse() &&
3580         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3581       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3582         cast<BinaryOperator>(Op1)->swapOperands();
3583         std::swap(A, B);
3584       }
3585       if (A == Op0) {                                // A&(A^B) -> A & ~B
3586         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3587         InsertNewInstBefore(NotB, I);
3588         return BinaryOperator::CreateAnd(A, NotB);
3589       }
3590     }
3591   }
3592   
3593   { // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3594     // where C is a power of 2
3595     Value *A, *B;
3596     ConstantInt *C1, *C2;
3597     ICmpInst::Predicate LHSCC = ICmpInst::BAD_ICMP_PREDICATE;
3598     ICmpInst::Predicate RHSCC = ICmpInst::BAD_ICMP_PREDICATE;
3599     if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3600                         m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3601       if (C1 == C2 && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3602           C1->getValue().isPowerOf2()) {
3603         Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3604         InsertNewInstBefore(NewOr, I);
3605         return new ICmpInst(LHSCC, NewOr, C1);
3606       }
3607   }
3608   
3609   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3610     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3611     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3612       return R;
3613
3614     Value *LHSVal, *RHSVal;
3615     ConstantInt *LHSCst, *RHSCst;
3616     ICmpInst::Predicate LHSCC, RHSCC;
3617     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3618       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3619         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3620             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3621             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3622             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3623             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3624             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3625             
3626             // Don't try to fold ICMP_SLT + ICMP_ULT.
3627             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3628              ICmpInst::isSignedPredicate(LHSCC) == 
3629                  ICmpInst::isSignedPredicate(RHSCC))) {
3630           // Ensure that the larger constant is on the RHS.
3631           ICmpInst::Predicate GT;
3632           if (ICmpInst::isSignedPredicate(LHSCC) ||
3633               (ICmpInst::isEquality(LHSCC) && 
3634                ICmpInst::isSignedPredicate(RHSCC)))
3635             GT = ICmpInst::ICMP_SGT;
3636           else
3637             GT = ICmpInst::ICMP_UGT;
3638           
3639           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3640           ICmpInst *LHS = cast<ICmpInst>(Op0);
3641           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3642             std::swap(LHS, RHS);
3643             std::swap(LHSCst, RHSCst);
3644             std::swap(LHSCC, RHSCC);
3645           }
3646
3647           // At this point, we know we have have two icmp instructions
3648           // comparing a value against two constants and and'ing the result
3649           // together.  Because of the above check, we know that we only have
3650           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3651           // (from the FoldICmpLogical check above), that the two constants 
3652           // are not equal and that the larger constant is on the RHS
3653           assert(LHSCst != RHSCst && "Compares not folded above?");
3654
3655           switch (LHSCC) {
3656           default: assert(0 && "Unknown integer condition code!");
3657           case ICmpInst::ICMP_EQ:
3658             switch (RHSCC) {
3659             default: assert(0 && "Unknown integer condition code!");
3660             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3661             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3662             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3663               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3664             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3665             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3666             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3667               return ReplaceInstUsesWith(I, LHS);
3668             }
3669           case ICmpInst::ICMP_NE:
3670             switch (RHSCC) {
3671             default: assert(0 && "Unknown integer condition code!");
3672             case ICmpInst::ICMP_ULT:
3673               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3674                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3675               break;                        // (X != 13 & X u< 15) -> no change
3676             case ICmpInst::ICMP_SLT:
3677               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3678                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3679               break;                        // (X != 13 & X s< 15) -> no change
3680             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3681             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3682             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3683               return ReplaceInstUsesWith(I, RHS);
3684             case ICmpInst::ICMP_NE:
3685               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3686                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3687                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3688                                                       LHSVal->getName()+".off");
3689                 InsertNewInstBefore(Add, I);
3690                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3691                                     ConstantInt::get(Add->getType(), 1));
3692               }
3693               break;                        // (X != 13 & X != 15) -> no change
3694             }
3695             break;
3696           case ICmpInst::ICMP_ULT:
3697             switch (RHSCC) {
3698             default: assert(0 && "Unknown integer condition code!");
3699             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3700             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3701               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3702             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3703               break;
3704             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3705             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3706               return ReplaceInstUsesWith(I, LHS);
3707             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3708               break;
3709             }
3710             break;
3711           case ICmpInst::ICMP_SLT:
3712             switch (RHSCC) {
3713             default: assert(0 && "Unknown integer condition code!");
3714             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3715             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3716               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3717             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3718               break;
3719             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3720             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3721               return ReplaceInstUsesWith(I, LHS);
3722             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3723               break;
3724             }
3725             break;
3726           case ICmpInst::ICMP_UGT:
3727             switch (RHSCC) {
3728             default: assert(0 && "Unknown integer condition code!");
3729             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3730             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3731               return ReplaceInstUsesWith(I, RHS);
3732             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3733               break;
3734             case ICmpInst::ICMP_NE:
3735               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3736                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3737               break;                        // (X u> 13 & X != 15) -> no change
3738             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3739               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3740                                      true, I);
3741             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3742               break;
3743             }
3744             break;
3745           case ICmpInst::ICMP_SGT:
3746             switch (RHSCC) {
3747             default: assert(0 && "Unknown integer condition code!");
3748             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3749             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3750               return ReplaceInstUsesWith(I, RHS);
3751             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3752               break;
3753             case ICmpInst::ICMP_NE:
3754               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3755                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3756               break;                        // (X s> 13 & X != 15) -> no change
3757             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3758               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3759                                      true, I);
3760             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3761               break;
3762             }
3763             break;
3764           }
3765         }
3766   }
3767
3768   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3769   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3770     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3771       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3772         const Type *SrcTy = Op0C->getOperand(0)->getType();
3773         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3774             // Only do this if the casts both really cause code to be generated.
3775             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3776                               I.getType(), TD) &&
3777             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3778                               I.getType(), TD)) {
3779           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3780                                                          Op1C->getOperand(0),
3781                                                          I.getName());
3782           InsertNewInstBefore(NewOp, I);
3783           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3784         }
3785       }
3786     
3787   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3788   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3789     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3790       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3791           SI0->getOperand(1) == SI1->getOperand(1) &&
3792           (SI0->hasOneUse() || SI1->hasOneUse())) {
3793         Instruction *NewOp =
3794           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3795                                                         SI1->getOperand(0),
3796                                                         SI0->getName()), I);
3797         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
3798                                       SI1->getOperand(1));
3799       }
3800   }
3801
3802   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3803   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3804     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3805       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3806           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3807         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3808           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3809             // If either of the constants are nans, then the whole thing returns
3810             // false.
3811             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3812               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3813             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3814                                 RHS->getOperand(0));
3815           }
3816     }
3817   }
3818
3819   return Changed ? &I : 0;
3820 }
3821
3822 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3823 /// in the result.  If it does, and if the specified byte hasn't been filled in
3824 /// yet, fill it in and return false.
3825 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3826   Instruction *I = dyn_cast<Instruction>(V);
3827   if (I == 0) return true;
3828
3829   // If this is an or instruction, it is an inner node of the bswap.
3830   if (I->getOpcode() == Instruction::Or)
3831     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3832            CollectBSwapParts(I->getOperand(1), ByteValues);
3833   
3834   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3835   // If this is a shift by a constant int, and it is "24", then its operand
3836   // defines a byte.  We only handle unsigned types here.
3837   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3838     // Not shifting the entire input by N-1 bytes?
3839     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3840         8*(ByteValues.size()-1))
3841       return true;
3842     
3843     unsigned DestNo;
3844     if (I->getOpcode() == Instruction::Shl) {
3845       // X << 24 defines the top byte with the lowest of the input bytes.
3846       DestNo = ByteValues.size()-1;
3847     } else {
3848       // X >>u 24 defines the low byte with the highest of the input bytes.
3849       DestNo = 0;
3850     }
3851     
3852     // If the destination byte value is already defined, the values are or'd
3853     // together, which isn't a bswap (unless it's an or of the same bits).
3854     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3855       return true;
3856     ByteValues[DestNo] = I->getOperand(0);
3857     return false;
3858   }
3859   
3860   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3861   // don't have this.
3862   Value *Shift = 0, *ShiftLHS = 0;
3863   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3864   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3865       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3866     return true;
3867   Instruction *SI = cast<Instruction>(Shift);
3868
3869   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3870   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3871       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3872     return true;
3873   
3874   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3875   unsigned DestByte;
3876   if (AndAmt->getValue().getActiveBits() > 64)
3877     return true;
3878   uint64_t AndAmtVal = AndAmt->getZExtValue();
3879   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3880     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3881       break;
3882   // Unknown mask for bswap.
3883   if (DestByte == ByteValues.size()) return true;
3884   
3885   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3886   unsigned SrcByte;
3887   if (SI->getOpcode() == Instruction::Shl)
3888     SrcByte = DestByte - ShiftBytes;
3889   else
3890     SrcByte = DestByte + ShiftBytes;
3891   
3892   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3893   if (SrcByte != ByteValues.size()-DestByte-1)
3894     return true;
3895   
3896   // If the destination byte value is already defined, the values are or'd
3897   // together, which isn't a bswap (unless it's an or of the same bits).
3898   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3899     return true;
3900   ByteValues[DestByte] = SI->getOperand(0);
3901   return false;
3902 }
3903
3904 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3905 /// If so, insert the new bswap intrinsic and return it.
3906 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3907   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3908   if (!ITy || ITy->getBitWidth() % 16) 
3909     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3910   
3911   /// ByteValues - For each byte of the result, we keep track of which value
3912   /// defines each byte.
3913   SmallVector<Value*, 8> ByteValues;
3914   ByteValues.resize(ITy->getBitWidth()/8);
3915     
3916   // Try to find all the pieces corresponding to the bswap.
3917   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3918       CollectBSwapParts(I.getOperand(1), ByteValues))
3919     return 0;
3920   
3921   // Check to see if all of the bytes come from the same value.
3922   Value *V = ByteValues[0];
3923   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3924   
3925   // Check to make sure that all of the bytes come from the same value.
3926   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3927     if (ByteValues[i] != V)
3928       return 0;
3929   const Type *Tys[] = { ITy };
3930   Module *M = I.getParent()->getParent()->getParent();
3931   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3932   return CallInst::Create(F, V);
3933 }
3934
3935
3936 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3937   bool Changed = SimplifyCommutative(I);
3938   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3939
3940   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3941     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3942
3943   // or X, X = X
3944   if (Op0 == Op1)
3945     return ReplaceInstUsesWith(I, Op0);
3946
3947   // See if we can simplify any instructions used by the instruction whose sole 
3948   // purpose is to compute bits we don't care about.
3949   if (!isa<VectorType>(I.getType())) {
3950     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3951     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3952     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3953                              KnownZero, KnownOne))
3954       return &I;
3955   } else if (isa<ConstantAggregateZero>(Op1)) {
3956     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3957   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3958     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3959       return ReplaceInstUsesWith(I, I.getOperand(1));
3960   }
3961     
3962
3963   
3964   // or X, -1 == -1
3965   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3966     ConstantInt *C1 = 0; Value *X = 0;
3967     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3968     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3969       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3970       InsertNewInstBefore(Or, I);
3971       Or->takeName(Op0);
3972       return BinaryOperator::CreateAnd(Or, 
3973                ConstantInt::get(RHS->getValue() | C1->getValue()));
3974     }
3975
3976     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3977     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3978       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3979       InsertNewInstBefore(Or, I);
3980       Or->takeName(Op0);
3981       return BinaryOperator::CreateXor(Or,
3982                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3983     }
3984
3985     // Try to fold constant and into select arguments.
3986     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3987       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3988         return R;
3989     if (isa<PHINode>(Op0))
3990       if (Instruction *NV = FoldOpIntoPhi(I))
3991         return NV;
3992   }
3993
3994   Value *A = 0, *B = 0;
3995   ConstantInt *C1 = 0, *C2 = 0;
3996
3997   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3998     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3999       return ReplaceInstUsesWith(I, Op1);
4000   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4001     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4002       return ReplaceInstUsesWith(I, Op0);
4003
4004   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4005   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4006   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4007       match(Op1, m_Or(m_Value(), m_Value())) ||
4008       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4009        match(Op1, m_Shift(m_Value(), m_Value())))) {
4010     if (Instruction *BSwap = MatchBSwap(I))
4011       return BSwap;
4012   }
4013   
4014   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4015   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4016       MaskedValueIsZero(Op1, C1->getValue())) {
4017     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4018     InsertNewInstBefore(NOr, I);
4019     NOr->takeName(Op0);
4020     return BinaryOperator::CreateXor(NOr, C1);
4021   }
4022
4023   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4024   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4025       MaskedValueIsZero(Op0, C1->getValue())) {
4026     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4027     InsertNewInstBefore(NOr, I);
4028     NOr->takeName(Op0);
4029     return BinaryOperator::CreateXor(NOr, C1);
4030   }
4031
4032   // (A & C)|(B & D)
4033   Value *C = 0, *D = 0;
4034   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4035       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4036     Value *V1 = 0, *V2 = 0, *V3 = 0;
4037     C1 = dyn_cast<ConstantInt>(C);
4038     C2 = dyn_cast<ConstantInt>(D);
4039     if (C1 && C2) {  // (A & C1)|(B & C2)
4040       // If we have: ((V + N) & C1) | (V & C2)
4041       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4042       // replace with V+N.
4043       if (C1->getValue() == ~C2->getValue()) {
4044         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4045             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4046           // Add commutes, try both ways.
4047           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4048             return ReplaceInstUsesWith(I, A);
4049           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4050             return ReplaceInstUsesWith(I, A);
4051         }
4052         // Or commutes, try both ways.
4053         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4054             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4055           // Add commutes, try both ways.
4056           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4057             return ReplaceInstUsesWith(I, B);
4058           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4059             return ReplaceInstUsesWith(I, B);
4060         }
4061       }
4062       V1 = 0; V2 = 0; V3 = 0;
4063     }
4064     
4065     // Check to see if we have any common things being and'ed.  If so, find the
4066     // terms for V1 & (V2|V3).
4067     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4068       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4069         V1 = A, V2 = C, V3 = D;
4070       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4071         V1 = A, V2 = B, V3 = C;
4072       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4073         V1 = C, V2 = A, V3 = D;
4074       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4075         V1 = C, V2 = A, V3 = B;
4076       
4077       if (V1) {
4078         Value *Or =
4079           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4080         return BinaryOperator::CreateAnd(V1, Or);
4081       }
4082     }
4083   }
4084   
4085   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4086   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4087     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4088       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4089           SI0->getOperand(1) == SI1->getOperand(1) &&
4090           (SI0->hasOneUse() || SI1->hasOneUse())) {
4091         Instruction *NewOp =
4092         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4093                                                      SI1->getOperand(0),
4094                                                      SI0->getName()), I);
4095         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4096                                       SI1->getOperand(1));
4097       }
4098   }
4099
4100   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4101     if (A == Op1)   // ~A | A == -1
4102       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4103   } else {
4104     A = 0;
4105   }
4106   // Note, A is still live here!
4107   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4108     if (Op0 == B)
4109       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4110
4111     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4112     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4113       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4114                                               I.getName()+".demorgan"), I);
4115       return BinaryOperator::CreateNot(And);
4116     }
4117   }
4118
4119   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4120   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4121     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4122       return R;
4123
4124     Value *LHSVal, *RHSVal;
4125     ConstantInt *LHSCst, *RHSCst;
4126     ICmpInst::Predicate LHSCC, RHSCC;
4127     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4128       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4129         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4130             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4131             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4132             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4133             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4134             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4135             // We can't fold (ugt x, C) | (sgt x, C2).
4136             PredicatesFoldable(LHSCC, RHSCC)) {
4137           // Ensure that the larger constant is on the RHS.
4138           ICmpInst *LHS = cast<ICmpInst>(Op0);
4139           bool NeedsSwap;
4140           if (ICmpInst::isSignedPredicate(LHSCC))
4141             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4142           else
4143             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4144             
4145           if (NeedsSwap) {
4146             std::swap(LHS, RHS);
4147             std::swap(LHSCst, RHSCst);
4148             std::swap(LHSCC, RHSCC);
4149           }
4150
4151           // At this point, we know we have have two icmp instructions
4152           // comparing a value against two constants and or'ing the result
4153           // together.  Because of the above check, we know that we only have
4154           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4155           // FoldICmpLogical check above), that the two constants are not
4156           // equal.
4157           assert(LHSCst != RHSCst && "Compares not folded above?");
4158
4159           switch (LHSCC) {
4160           default: assert(0 && "Unknown integer condition code!");
4161           case ICmpInst::ICMP_EQ:
4162             switch (RHSCC) {
4163             default: assert(0 && "Unknown integer condition code!");
4164             case ICmpInst::ICMP_EQ:
4165               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4166                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4167                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4168                                                       LHSVal->getName()+".off");
4169                 InsertNewInstBefore(Add, I);
4170                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4171                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4172               }
4173               break;                         // (X == 13 | X == 15) -> no change
4174             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4175             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4176               break;
4177             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4178             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4179             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4180               return ReplaceInstUsesWith(I, RHS);
4181             }
4182             break;
4183           case ICmpInst::ICMP_NE:
4184             switch (RHSCC) {
4185             default: assert(0 && "Unknown integer condition code!");
4186             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4187             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4188             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4189               return ReplaceInstUsesWith(I, LHS);
4190             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4191             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4192             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4193               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4194             }
4195             break;
4196           case ICmpInst::ICMP_ULT:
4197             switch (RHSCC) {
4198             default: assert(0 && "Unknown integer condition code!");
4199             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4200               break;
4201             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4202               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4203               // this can cause overflow.
4204               if (RHSCst->isMaxValue(false))
4205                 return ReplaceInstUsesWith(I, LHS);
4206               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4207                                      false, I);
4208             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4209               break;
4210             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4211             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4212               return ReplaceInstUsesWith(I, RHS);
4213             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4214               break;
4215             }
4216             break;
4217           case ICmpInst::ICMP_SLT:
4218             switch (RHSCC) {
4219             default: assert(0 && "Unknown integer condition code!");
4220             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4221               break;
4222             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4223               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4224               // this can cause overflow.
4225               if (RHSCst->isMaxValue(true))
4226                 return ReplaceInstUsesWith(I, LHS);
4227               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4228                                      false, I);
4229             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4230               break;
4231             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4232             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4233               return ReplaceInstUsesWith(I, RHS);
4234             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4235               break;
4236             }
4237             break;
4238           case ICmpInst::ICMP_UGT:
4239             switch (RHSCC) {
4240             default: assert(0 && "Unknown integer condition code!");
4241             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4242             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4243               return ReplaceInstUsesWith(I, LHS);
4244             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4245               break;
4246             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4247             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4248               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4249             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4250               break;
4251             }
4252             break;
4253           case ICmpInst::ICMP_SGT:
4254             switch (RHSCC) {
4255             default: assert(0 && "Unknown integer condition code!");
4256             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4257             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4258               return ReplaceInstUsesWith(I, LHS);
4259             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4260               break;
4261             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4262             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4263               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4264             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4265               break;
4266             }
4267             break;
4268           }
4269         }
4270   }
4271     
4272   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4273   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4274     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4275       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4276         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4277             !isa<ICmpInst>(Op1C->getOperand(0))) {
4278           const Type *SrcTy = Op0C->getOperand(0)->getType();
4279           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4280               // Only do this if the casts both really cause code to be
4281               // generated.
4282               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4283                                 I.getType(), TD) &&
4284               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4285                                 I.getType(), TD)) {
4286             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4287                                                           Op1C->getOperand(0),
4288                                                           I.getName());
4289             InsertNewInstBefore(NewOp, I);
4290             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4291           }
4292         }
4293       }
4294   }
4295   
4296     
4297   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4298   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4299     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4300       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4301           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4302           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4303         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4304           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4305             // If either of the constants are nans, then the whole thing returns
4306             // true.
4307             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4308               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4309             
4310             // Otherwise, no need to compare the two constants, compare the
4311             // rest.
4312             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4313                                 RHS->getOperand(0));
4314           }
4315     }
4316   }
4317
4318   return Changed ? &I : 0;
4319 }
4320
4321 namespace {
4322
4323 // XorSelf - Implements: X ^ X --> 0
4324 struct XorSelf {
4325   Value *RHS;
4326   XorSelf(Value *rhs) : RHS(rhs) {}
4327   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4328   Instruction *apply(BinaryOperator &Xor) const {
4329     return &Xor;
4330   }
4331 };
4332
4333 }
4334
4335 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4336   bool Changed = SimplifyCommutative(I);
4337   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4338
4339   if (isa<UndefValue>(Op1)) {
4340     if (isa<UndefValue>(Op0))
4341       // Handle undef ^ undef -> 0 special case. This is a common
4342       // idiom (misuse).
4343       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4344     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4345   }
4346
4347   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4348   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4349     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4350     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4351   }
4352   
4353   // See if we can simplify any instructions used by the instruction whose sole 
4354   // purpose is to compute bits we don't care about.
4355   if (!isa<VectorType>(I.getType())) {
4356     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4357     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4358     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4359                              KnownZero, KnownOne))
4360       return &I;
4361   } else if (isa<ConstantAggregateZero>(Op1)) {
4362     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4363   }
4364
4365   // Is this a ~ operation?
4366   if (Value *NotOp = dyn_castNotVal(&I)) {
4367     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4368     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4369     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4370       if (Op0I->getOpcode() == Instruction::And || 
4371           Op0I->getOpcode() == Instruction::Or) {
4372         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4373         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4374           Instruction *NotY =
4375             BinaryOperator::CreateNot(Op0I->getOperand(1),
4376                                       Op0I->getOperand(1)->getName()+".not");
4377           InsertNewInstBefore(NotY, I);
4378           if (Op0I->getOpcode() == Instruction::And)
4379             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4380           else
4381             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4382         }
4383       }
4384     }
4385   }
4386   
4387   
4388   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4389     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4390     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4391       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4392         return new ICmpInst(ICI->getInversePredicate(),
4393                             ICI->getOperand(0), ICI->getOperand(1));
4394
4395       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4396         return new FCmpInst(FCI->getInversePredicate(),
4397                             FCI->getOperand(0), FCI->getOperand(1));
4398     }
4399
4400     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4401     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4402       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4403         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4404           Instruction::CastOps Opcode = Op0C->getOpcode();
4405           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4406             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4407                                              Op0C->getDestTy())) {
4408               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4409                                      CI->getOpcode(), CI->getInversePredicate(),
4410                                      CI->getOperand(0), CI->getOperand(1)), I);
4411               NewCI->takeName(CI);
4412               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4413             }
4414           }
4415         }
4416       }
4417     }
4418
4419     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4420       // ~(c-X) == X-c-1 == X+(-c-1)
4421       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4422         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4423           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4424           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4425                                               ConstantInt::get(I.getType(), 1));
4426           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4427         }
4428           
4429       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4430         if (Op0I->getOpcode() == Instruction::Add) {
4431           // ~(X-c) --> (-c-1)-X
4432           if (RHS->isAllOnesValue()) {
4433             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4434             return BinaryOperator::CreateSub(
4435                            ConstantExpr::getSub(NegOp0CI,
4436                                              ConstantInt::get(I.getType(), 1)),
4437                                           Op0I->getOperand(0));
4438           } else if (RHS->getValue().isSignBit()) {
4439             // (X + C) ^ signbit -> (X + C + signbit)
4440             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4441             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4442
4443           }
4444         } else if (Op0I->getOpcode() == Instruction::Or) {
4445           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4446           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4447             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4448             // Anything in both C1 and C2 is known to be zero, remove it from
4449             // NewRHS.
4450             Constant *CommonBits = And(Op0CI, RHS);
4451             NewRHS = ConstantExpr::getAnd(NewRHS, 
4452                                           ConstantExpr::getNot(CommonBits));
4453             AddToWorkList(Op0I);
4454             I.setOperand(0, Op0I->getOperand(0));
4455             I.setOperand(1, NewRHS);
4456             return &I;
4457           }
4458         }
4459       }
4460     }
4461
4462     // Try to fold constant and into select arguments.
4463     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4464       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4465         return R;
4466     if (isa<PHINode>(Op0))
4467       if (Instruction *NV = FoldOpIntoPhi(I))
4468         return NV;
4469   }
4470
4471   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4472     if (X == Op1)
4473       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4474
4475   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4476     if (X == Op0)
4477       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4478
4479   
4480   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4481   if (Op1I) {
4482     Value *A, *B;
4483     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4484       if (A == Op0) {              // B^(B|A) == (A|B)^B
4485         Op1I->swapOperands();
4486         I.swapOperands();
4487         std::swap(Op0, Op1);
4488       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4489         I.swapOperands();     // Simplified below.
4490         std::swap(Op0, Op1);
4491       }
4492     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4493       if (Op0 == A)                                          // A^(A^B) == B
4494         return ReplaceInstUsesWith(I, B);
4495       else if (Op0 == B)                                     // A^(B^A) == B
4496         return ReplaceInstUsesWith(I, A);
4497     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4498       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4499         Op1I->swapOperands();
4500         std::swap(A, B);
4501       }
4502       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4503         I.swapOperands();     // Simplified below.
4504         std::swap(Op0, Op1);
4505       }
4506     }
4507   }
4508   
4509   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4510   if (Op0I) {
4511     Value *A, *B;
4512     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4513       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4514         std::swap(A, B);
4515       if (B == Op1) {                                // (A|B)^B == A & ~B
4516         Instruction *NotB =
4517           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4518         return BinaryOperator::CreateAnd(A, NotB);
4519       }
4520     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4521       if (Op1 == A)                                          // (A^B)^A == B
4522         return ReplaceInstUsesWith(I, B);
4523       else if (Op1 == B)                                     // (B^A)^A == B
4524         return ReplaceInstUsesWith(I, A);
4525     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4526       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4527         std::swap(A, B);
4528       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4529           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4530         Instruction *N =
4531           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4532         return BinaryOperator::CreateAnd(N, Op1);
4533       }
4534     }
4535   }
4536   
4537   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4538   if (Op0I && Op1I && Op0I->isShift() && 
4539       Op0I->getOpcode() == Op1I->getOpcode() && 
4540       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4541       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4542     Instruction *NewOp =
4543       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4544                                                     Op1I->getOperand(0),
4545                                                     Op0I->getName()), I);
4546     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4547                                   Op1I->getOperand(1));
4548   }
4549     
4550   if (Op0I && Op1I) {
4551     Value *A, *B, *C, *D;
4552     // (A & B)^(A | B) -> A ^ B
4553     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4554         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4555       if ((A == C && B == D) || (A == D && B == C)) 
4556         return BinaryOperator::CreateXor(A, B);
4557     }
4558     // (A | B)^(A & B) -> A ^ B
4559     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4560         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4561       if ((A == C && B == D) || (A == D && B == C)) 
4562         return BinaryOperator::CreateXor(A, B);
4563     }
4564     
4565     // (A & B)^(C & D)
4566     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4567         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4568         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4569       // (X & Y)^(X & Y) -> (Y^Z) & X
4570       Value *X = 0, *Y = 0, *Z = 0;
4571       if (A == C)
4572         X = A, Y = B, Z = D;
4573       else if (A == D)
4574         X = A, Y = B, Z = C;
4575       else if (B == C)
4576         X = B, Y = A, Z = D;
4577       else if (B == D)
4578         X = B, Y = A, Z = C;
4579       
4580       if (X) {
4581         Instruction *NewOp =
4582         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4583         return BinaryOperator::CreateAnd(NewOp, X);
4584       }
4585     }
4586   }
4587     
4588   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4589   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4590     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4591       return R;
4592
4593   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4594   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4595     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4596       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4597         const Type *SrcTy = Op0C->getOperand(0)->getType();
4598         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4599             // Only do this if the casts both really cause code to be generated.
4600             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4601                               I.getType(), TD) &&
4602             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4603                               I.getType(), TD)) {
4604           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4605                                                          Op1C->getOperand(0),
4606                                                          I.getName());
4607           InsertNewInstBefore(NewOp, I);
4608           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4609         }
4610       }
4611   }
4612
4613   return Changed ? &I : 0;
4614 }
4615
4616 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4617 /// overflowed for this type.
4618 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4619                             ConstantInt *In2, bool IsSigned = false) {
4620   Result = cast<ConstantInt>(Add(In1, In2));
4621
4622   if (IsSigned)
4623     if (In2->getValue().isNegative())
4624       return Result->getValue().sgt(In1->getValue());
4625     else
4626       return Result->getValue().slt(In1->getValue());
4627   else
4628     return Result->getValue().ult(In1->getValue());
4629 }
4630
4631 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4632 /// code necessary to compute the offset from the base pointer (without adding
4633 /// in the base pointer).  Return the result as a signed integer of intptr size.
4634 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4635   TargetData &TD = IC.getTargetData();
4636   gep_type_iterator GTI = gep_type_begin(GEP);
4637   const Type *IntPtrTy = TD.getIntPtrType();
4638   Value *Result = Constant::getNullValue(IntPtrTy);
4639
4640   // Build a mask for high order bits.
4641   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4642   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4643
4644   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4645        ++i, ++GTI) {
4646     Value *Op = *i;
4647     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4648     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4649       if (OpC->isZero()) continue;
4650       
4651       // Handle a struct index, which adds its field offset to the pointer.
4652       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4653         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4654         
4655         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4656           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4657         else
4658           Result = IC.InsertNewInstBefore(
4659                    BinaryOperator::CreateAdd(Result,
4660                                              ConstantInt::get(IntPtrTy, Size),
4661                                              GEP->getName()+".offs"), I);
4662         continue;
4663       }
4664       
4665       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4666       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4667       Scale = ConstantExpr::getMul(OC, Scale);
4668       if (Constant *RC = dyn_cast<Constant>(Result))
4669         Result = ConstantExpr::getAdd(RC, Scale);
4670       else {
4671         // Emit an add instruction.
4672         Result = IC.InsertNewInstBefore(
4673            BinaryOperator::CreateAdd(Result, Scale,
4674                                      GEP->getName()+".offs"), I);
4675       }
4676       continue;
4677     }
4678     // Convert to correct type.
4679     if (Op->getType() != IntPtrTy) {
4680       if (Constant *OpC = dyn_cast<Constant>(Op))
4681         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4682       else
4683         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4684                                                  Op->getName()+".c"), I);
4685     }
4686     if (Size != 1) {
4687       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4688       if (Constant *OpC = dyn_cast<Constant>(Op))
4689         Op = ConstantExpr::getMul(OpC, Scale);
4690       else    // We'll let instcombine(mul) convert this to a shl if possible.
4691         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4692                                                   GEP->getName()+".idx"), I);
4693     }
4694
4695     // Emit an add instruction.
4696     if (isa<Constant>(Op) && isa<Constant>(Result))
4697       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4698                                     cast<Constant>(Result));
4699     else
4700       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4701                                                   GEP->getName()+".offs"), I);
4702   }
4703   return Result;
4704 }
4705
4706
4707 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4708 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
4709 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
4710 /// complex, and scales are involved.  The above expression would also be legal
4711 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
4712 /// later form is less amenable to optimization though, and we are allowed to
4713 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4714 ///
4715 /// If we can't emit an optimized form for this expression, this returns null.
4716 /// 
4717 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4718                                           InstCombiner &IC) {
4719   TargetData &TD = IC.getTargetData();
4720   gep_type_iterator GTI = gep_type_begin(GEP);
4721
4722   // Check to see if this gep only has a single variable index.  If so, and if
4723   // any constant indices are a multiple of its scale, then we can compute this
4724   // in terms of the scale of the variable index.  For example, if the GEP
4725   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4726   // because the expression will cross zero at the same point.
4727   unsigned i, e = GEP->getNumOperands();
4728   int64_t Offset = 0;
4729   for (i = 1; i != e; ++i, ++GTI) {
4730     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4731       // Compute the aggregate offset of constant indices.
4732       if (CI->isZero()) continue;
4733
4734       // Handle a struct index, which adds its field offset to the pointer.
4735       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4736         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4737       } else {
4738         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4739         Offset += Size*CI->getSExtValue();
4740       }
4741     } else {
4742       // Found our variable index.
4743       break;
4744     }
4745   }
4746   
4747   // If there are no variable indices, we must have a constant offset, just
4748   // evaluate it the general way.
4749   if (i == e) return 0;
4750   
4751   Value *VariableIdx = GEP->getOperand(i);
4752   // Determine the scale factor of the variable element.  For example, this is
4753   // 4 if the variable index is into an array of i32.
4754   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4755   
4756   // Verify that there are no other variable indices.  If so, emit the hard way.
4757   for (++i, ++GTI; i != e; ++i, ++GTI) {
4758     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4759     if (!CI) return 0;
4760    
4761     // Compute the aggregate offset of constant indices.
4762     if (CI->isZero()) continue;
4763     
4764     // Handle a struct index, which adds its field offset to the pointer.
4765     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4766       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4767     } else {
4768       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4769       Offset += Size*CI->getSExtValue();
4770     }
4771   }
4772   
4773   // Okay, we know we have a single variable index, which must be a
4774   // pointer/array/vector index.  If there is no offset, life is simple, return
4775   // the index.
4776   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4777   if (Offset == 0) {
4778     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
4779     // we don't need to bother extending: the extension won't affect where the
4780     // computation crosses zero.
4781     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4782       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4783                                   VariableIdx->getNameStart(), &I);
4784     return VariableIdx;
4785   }
4786   
4787   // Otherwise, there is an index.  The computation we will do will be modulo
4788   // the pointer size, so get it.
4789   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4790   
4791   Offset &= PtrSizeMask;
4792   VariableScale &= PtrSizeMask;
4793
4794   // To do this transformation, any constant index must be a multiple of the
4795   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
4796   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
4797   // multiple of the variable scale.
4798   int64_t NewOffs = Offset / (int64_t)VariableScale;
4799   if (Offset != NewOffs*(int64_t)VariableScale)
4800     return 0;
4801
4802   // Okay, we can do this evaluation.  Start by converting the index to intptr.
4803   const Type *IntPtrTy = TD.getIntPtrType();
4804   if (VariableIdx->getType() != IntPtrTy)
4805     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4806                                               true /*SExt*/, 
4807                                               VariableIdx->getNameStart(), &I);
4808   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4809   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4810 }
4811
4812
4813 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4814 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4815 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4816                                        ICmpInst::Predicate Cond,
4817                                        Instruction &I) {
4818   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4819
4820   // Look through bitcasts.
4821   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4822     RHS = BCI->getOperand(0);
4823
4824   Value *PtrBase = GEPLHS->getOperand(0);
4825   if (PtrBase == RHS) {
4826     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4827     // This transformation (ignoring the base and scales) is valid because we
4828     // know pointers can't overflow.  See if we can output an optimized form.
4829     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4830     
4831     // If not, synthesize the offset the hard way.
4832     if (Offset == 0)
4833       Offset = EmitGEPOffset(GEPLHS, I, *this);
4834     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4835                         Constant::getNullValue(Offset->getType()));
4836   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4837     // If the base pointers are different, but the indices are the same, just
4838     // compare the base pointer.
4839     if (PtrBase != GEPRHS->getOperand(0)) {
4840       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4841       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4842                         GEPRHS->getOperand(0)->getType();
4843       if (IndicesTheSame)
4844         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4845           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4846             IndicesTheSame = false;
4847             break;
4848           }
4849
4850       // If all indices are the same, just compare the base pointers.
4851       if (IndicesTheSame)
4852         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4853                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4854
4855       // Otherwise, the base pointers are different and the indices are
4856       // different, bail out.
4857       return 0;
4858     }
4859
4860     // If one of the GEPs has all zero indices, recurse.
4861     bool AllZeros = true;
4862     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4863       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4864           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4865         AllZeros = false;
4866         break;
4867       }
4868     if (AllZeros)
4869       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4870                           ICmpInst::getSwappedPredicate(Cond), I);
4871
4872     // If the other GEP has all zero indices, recurse.
4873     AllZeros = true;
4874     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4875       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4876           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4877         AllZeros = false;
4878         break;
4879       }
4880     if (AllZeros)
4881       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4882
4883     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4884       // If the GEPs only differ by one index, compare it.
4885       unsigned NumDifferences = 0;  // Keep track of # differences.
4886       unsigned DiffOperand = 0;     // The operand that differs.
4887       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4888         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4889           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4890                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4891             // Irreconcilable differences.
4892             NumDifferences = 2;
4893             break;
4894           } else {
4895             if (NumDifferences++) break;
4896             DiffOperand = i;
4897           }
4898         }
4899
4900       if (NumDifferences == 0)   // SAME GEP?
4901         return ReplaceInstUsesWith(I, // No comparison is needed here.
4902                                    ConstantInt::get(Type::Int1Ty,
4903                                              ICmpInst::isTrueWhenEqual(Cond)));
4904
4905       else if (NumDifferences == 1) {
4906         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4907         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4908         // Make sure we do a signed comparison here.
4909         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4910       }
4911     }
4912
4913     // Only lower this if the icmp is the only user of the GEP or if we expect
4914     // the result to fold to a constant!
4915     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4916         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4917       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4918       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4919       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4920       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4921     }
4922   }
4923   return 0;
4924 }
4925
4926 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4927 ///
4928 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4929                                                 Instruction *LHSI,
4930                                                 Constant *RHSC) {
4931   if (!isa<ConstantFP>(RHSC)) return 0;
4932   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4933   
4934   // Get the width of the mantissa.  We don't want to hack on conversions that
4935   // might lose information from the integer, e.g. "i64 -> float"
4936   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4937   if (MantissaWidth == -1) return 0;  // Unknown.
4938   
4939   // Check to see that the input is converted from an integer type that is small
4940   // enough that preserves all bits.  TODO: check here for "known" sign bits.
4941   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4942   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4943   
4944   // If this is a uitofp instruction, we need an extra bit to hold the sign.
4945   if (isa<UIToFPInst>(LHSI))
4946     ++InputSize;
4947   
4948   // If the conversion would lose info, don't hack on this.
4949   if ((int)InputSize > MantissaWidth)
4950     return 0;
4951   
4952   // Otherwise, we can potentially simplify the comparison.  We know that it
4953   // will always come through as an integer value and we know the constant is
4954   // not a NAN (it would have been previously simplified).
4955   assert(!RHS.isNaN() && "NaN comparison not already folded!");
4956   
4957   ICmpInst::Predicate Pred;
4958   switch (I.getPredicate()) {
4959   default: assert(0 && "Unexpected predicate!");
4960   case FCmpInst::FCMP_UEQ:
4961   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4962   case FCmpInst::FCMP_UGT:
4963   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4964   case FCmpInst::FCMP_UGE:
4965   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4966   case FCmpInst::FCMP_ULT:
4967   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4968   case FCmpInst::FCMP_ULE:
4969   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4970   case FCmpInst::FCMP_UNE:
4971   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4972   case FCmpInst::FCMP_ORD:
4973     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4974   case FCmpInst::FCMP_UNO:
4975     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4976   }
4977   
4978   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4979   
4980   // Now we know that the APFloat is a normal number, zero or inf.
4981   
4982   // See if the FP constant is too large for the integer.  For example,
4983   // comparing an i8 to 300.0.
4984   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4985   
4986   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
4987   // and large values. 
4988   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4989   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4990                         APFloat::rmNearestTiesToEven);
4991   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
4992     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4993         Pred == ICmpInst::ICMP_SLE)
4994       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4995     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4996   }
4997   
4998   // See if the RHS value is < SignedMin.
4999   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5000   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5001                         APFloat::rmNearestTiesToEven);
5002   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5003     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5004         Pred == ICmpInst::ICMP_SGE)
5005       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5006     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5007   }
5008
5009   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5010   // it may still be fractional.  See if it is fractional by casting the FP
5011   // value to the integer value and back, checking for equality.  Don't do this
5012   // for zero, because -0.0 is not fractional.
5013   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5014   if (!RHS.isZero() &&
5015       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5016     // If we had a comparison against a fractional value, we have to adjust
5017     // the compare predicate and sometimes the value.  RHSC is rounded towards
5018     // zero at this point.
5019     switch (Pred) {
5020     default: assert(0 && "Unexpected integer comparison!");
5021     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5022       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5023     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5024       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5025     case ICmpInst::ICMP_SLE:
5026       // (float)int <= 4.4   --> int <= 4
5027       // (float)int <= -4.4  --> int < -4
5028       if (RHS.isNegative())
5029         Pred = ICmpInst::ICMP_SLT;
5030       break;
5031     case ICmpInst::ICMP_SLT:
5032       // (float)int < -4.4   --> int < -4
5033       // (float)int < 4.4    --> int <= 4
5034       if (!RHS.isNegative())
5035         Pred = ICmpInst::ICMP_SLE;
5036       break;
5037     case ICmpInst::ICMP_SGT:
5038       // (float)int > 4.4    --> int > 4
5039       // (float)int > -4.4   --> int >= -4
5040       if (RHS.isNegative())
5041         Pred = ICmpInst::ICMP_SGE;
5042       break;
5043     case ICmpInst::ICMP_SGE:
5044       // (float)int >= -4.4   --> int >= -4
5045       // (float)int >= 4.4    --> int > 4
5046       if (!RHS.isNegative())
5047         Pred = ICmpInst::ICMP_SGT;
5048       break;
5049     }
5050   }
5051
5052   // Lower this FP comparison into an appropriate integer version of the
5053   // comparison.
5054   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5055 }
5056
5057 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5058   bool Changed = SimplifyCompare(I);
5059   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5060
5061   // Fold trivial predicates.
5062   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5063     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5064   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5065     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5066   
5067   // Simplify 'fcmp pred X, X'
5068   if (Op0 == Op1) {
5069     switch (I.getPredicate()) {
5070     default: assert(0 && "Unknown predicate!");
5071     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5072     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5073     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5074       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5075     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5076     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5077     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5078       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5079       
5080     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5081     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5082     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5083     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5084       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5085       I.setPredicate(FCmpInst::FCMP_UNO);
5086       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5087       return &I;
5088       
5089     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5090     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5091     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5092     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5093       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5094       I.setPredicate(FCmpInst::FCMP_ORD);
5095       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5096       return &I;
5097     }
5098   }
5099     
5100   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5101     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5102
5103   // Handle fcmp with constant RHS
5104   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5105     // If the constant is a nan, see if we can fold the comparison based on it.
5106     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5107       if (CFP->getValueAPF().isNaN()) {
5108         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5109           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5110         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5111                "Comparison must be either ordered or unordered!");
5112         // True if unordered.
5113         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5114       }
5115     }
5116     
5117     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5118       switch (LHSI->getOpcode()) {
5119       case Instruction::PHI:
5120         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5121         // block.  If in the same block, we're encouraging jump threading.  If
5122         // not, we are just pessimizing the code by making an i1 phi.
5123         if (LHSI->getParent() == I.getParent())
5124           if (Instruction *NV = FoldOpIntoPhi(I))
5125             return NV;
5126         break;
5127       case Instruction::SIToFP:
5128       case Instruction::UIToFP:
5129         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5130           return NV;
5131         break;
5132       case Instruction::Select:
5133         // If either operand of the select is a constant, we can fold the
5134         // comparison into the select arms, which will cause one to be
5135         // constant folded and the select turned into a bitwise or.
5136         Value *Op1 = 0, *Op2 = 0;
5137         if (LHSI->hasOneUse()) {
5138           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5139             // Fold the known value into the constant operand.
5140             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5141             // Insert a new FCmp of the other select operand.
5142             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5143                                                       LHSI->getOperand(2), RHSC,
5144                                                       I.getName()), I);
5145           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5146             // Fold the known value into the constant operand.
5147             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5148             // Insert a new FCmp of the other select operand.
5149             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5150                                                       LHSI->getOperand(1), RHSC,
5151                                                       I.getName()), I);
5152           }
5153         }
5154
5155         if (Op1)
5156           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5157         break;
5158       }
5159   }
5160
5161   return Changed ? &I : 0;
5162 }
5163
5164 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5165   bool Changed = SimplifyCompare(I);
5166   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5167   const Type *Ty = Op0->getType();
5168
5169   // icmp X, X
5170   if (Op0 == Op1)
5171     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5172                                                    I.isTrueWhenEqual()));
5173
5174   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5175     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5176   
5177   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5178   // addresses never equal each other!  We already know that Op0 != Op1.
5179   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5180        isa<ConstantPointerNull>(Op0)) &&
5181       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5182        isa<ConstantPointerNull>(Op1)))
5183     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5184                                                    !I.isTrueWhenEqual()));
5185
5186   // icmp's with boolean values can always be turned into bitwise operations
5187   if (Ty == Type::Int1Ty) {
5188     switch (I.getPredicate()) {
5189     default: assert(0 && "Invalid icmp instruction!");
5190     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5191       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5192       InsertNewInstBefore(Xor, I);
5193       return BinaryOperator::CreateNot(Xor);
5194     }
5195     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5196       return BinaryOperator::CreateXor(Op0, Op1);
5197
5198     case ICmpInst::ICMP_UGT:
5199       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5200       // FALL THROUGH
5201     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5202       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5203       InsertNewInstBefore(Not, I);
5204       return BinaryOperator::CreateAnd(Not, Op1);
5205     }
5206     case ICmpInst::ICMP_SGT:
5207       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5208       // FALL THROUGH
5209     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5210       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5211       InsertNewInstBefore(Not, I);
5212       return BinaryOperator::CreateAnd(Not, Op0);
5213     }
5214     case ICmpInst::ICMP_UGE:
5215       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5216       // FALL THROUGH
5217     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5218       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5219       InsertNewInstBefore(Not, I);
5220       return BinaryOperator::CreateOr(Not, Op1);
5221     }
5222     case ICmpInst::ICMP_SGE:
5223       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5224       // FALL THROUGH
5225     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5226       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5227       InsertNewInstBefore(Not, I);
5228       return BinaryOperator::CreateOr(Not, Op0);
5229     }
5230     }
5231   }
5232
5233   // See if we are doing a comparison between a constant and an instruction that
5234   // can be folded into the comparison.
5235   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5236     Value *A, *B;
5237     
5238     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5239     if (I.isEquality() && CI->isNullValue() &&
5240         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5241       // (icmp cond A B) if cond is equality
5242       return new ICmpInst(I.getPredicate(), A, B);
5243     }
5244     
5245     // If we have a icmp le or icmp ge instruction, turn it into the appropriate
5246     // icmp lt or icmp gt instruction.  This allows us to rely on them being
5247     // folded in the code below.
5248     switch (I.getPredicate()) {
5249     default: break;
5250     case ICmpInst::ICMP_ULE:
5251       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5252         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5253       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5254     case ICmpInst::ICMP_SLE:
5255       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5256         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5257       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5258     case ICmpInst::ICMP_UGE:
5259       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5260         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5261       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5262     case ICmpInst::ICMP_SGE:
5263       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5264         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5265       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5266     }
5267     
5268     // See if we can fold the comparison based on range information we can get
5269     // by checking whether bits are known to be zero or one in the input.
5270     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5271     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5272     
5273     // If this comparison is a normal comparison, it demands all
5274     // bits, if it is a sign bit comparison, it only demands the sign bit.
5275     bool UnusedBit;
5276     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5277     
5278     if (SimplifyDemandedBits(Op0, 
5279                              isSignBit ? APInt::getSignBit(BitWidth)
5280                                        : APInt::getAllOnesValue(BitWidth),
5281                              KnownZero, KnownOne, 0))
5282       return &I;
5283         
5284     // Given the known and unknown bits, compute a range that the LHS could be
5285     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5286     // EQ and NE we use unsigned values.
5287     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5288     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5289       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5290     else
5291       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5292     
5293     // If Min and Max are known to be the same, then SimplifyDemandedBits
5294     // figured out that the LHS is a constant.  Just constant fold this now so
5295     // that code below can assume that Min != Max.
5296     if (Min == Max)
5297       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5298                                                           ConstantInt::get(Min),
5299                                                           CI));
5300     
5301     // Based on the range information we know about the LHS, see if we can
5302     // simplify this comparison.  For example, (x&4) < 8  is always true.
5303     const APInt &RHSVal = CI->getValue();
5304     switch (I.getPredicate()) {  // LE/GE have been folded already.
5305     default: assert(0 && "Unknown icmp opcode!");
5306     case ICmpInst::ICMP_EQ:
5307       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5308         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5309       break;
5310     case ICmpInst::ICMP_NE:
5311       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5312         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5313       break;
5314     case ICmpInst::ICMP_ULT:
5315       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5316         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5317       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5318         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5319       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5320         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5321       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5322         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5323         
5324       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5325       if (CI->isMinValue(true))
5326         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5327                             ConstantInt::getAllOnesValue(Op0->getType()));
5328       break;
5329     case ICmpInst::ICMP_UGT:
5330       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5331         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5332       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5333         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5334         
5335       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5336         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5337       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5338         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5339       
5340       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5341       if (CI->isMaxValue(true))
5342         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5343                             ConstantInt::getNullValue(Op0->getType()));
5344       break;
5345     case ICmpInst::ICMP_SLT:
5346       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5347         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5348       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5349         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5350       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5351         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5352       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5353         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5354       break;
5355     case ICmpInst::ICMP_SGT: 
5356       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5357         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5358       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5359         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5360         
5361       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5362         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5363       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5364         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5365       break;
5366     }
5367           
5368     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5369     // instruction, see if that instruction also has constants so that the 
5370     // instruction can be folded into the icmp 
5371     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5372       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5373         return Res;
5374   }
5375
5376   // Handle icmp with constant (but not simple integer constant) RHS
5377   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5378     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5379       switch (LHSI->getOpcode()) {
5380       case Instruction::GetElementPtr:
5381         if (RHSC->isNullValue()) {
5382           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5383           bool isAllZeros = true;
5384           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5385             if (!isa<Constant>(LHSI->getOperand(i)) ||
5386                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5387               isAllZeros = false;
5388               break;
5389             }
5390           if (isAllZeros)
5391             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5392                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5393         }
5394         break;
5395
5396       case Instruction::PHI:
5397         // Only fold icmp into the PHI if the phi and fcmp are in the same
5398         // block.  If in the same block, we're encouraging jump threading.  If
5399         // not, we are just pessimizing the code by making an i1 phi.
5400         if (LHSI->getParent() == I.getParent())
5401           if (Instruction *NV = FoldOpIntoPhi(I))
5402             return NV;
5403         break;
5404       case Instruction::Select: {
5405         // If either operand of the select is a constant, we can fold the
5406         // comparison into the select arms, which will cause one to be
5407         // constant folded and the select turned into a bitwise or.
5408         Value *Op1 = 0, *Op2 = 0;
5409         if (LHSI->hasOneUse()) {
5410           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5411             // Fold the known value into the constant operand.
5412             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5413             // Insert a new ICmp of the other select operand.
5414             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5415                                                    LHSI->getOperand(2), RHSC,
5416                                                    I.getName()), I);
5417           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5418             // Fold the known value into the constant operand.
5419             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5420             // Insert a new ICmp of the other select operand.
5421             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5422                                                    LHSI->getOperand(1), RHSC,
5423                                                    I.getName()), I);
5424           }
5425         }
5426
5427         if (Op1)
5428           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5429         break;
5430       }
5431       case Instruction::Malloc:
5432         // If we have (malloc != null), and if the malloc has a single use, we
5433         // can assume it is successful and remove the malloc.
5434         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5435           AddToWorkList(LHSI);
5436           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5437                                                          !I.isTrueWhenEqual()));
5438         }
5439         break;
5440       }
5441   }
5442
5443   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5444   if (User *GEP = dyn_castGetElementPtr(Op0))
5445     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5446       return NI;
5447   if (User *GEP = dyn_castGetElementPtr(Op1))
5448     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5449                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5450       return NI;
5451
5452   // Test to see if the operands of the icmp are casted versions of other
5453   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5454   // now.
5455   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5456     if (isa<PointerType>(Op0->getType()) && 
5457         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5458       // We keep moving the cast from the left operand over to the right
5459       // operand, where it can often be eliminated completely.
5460       Op0 = CI->getOperand(0);
5461
5462       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5463       // so eliminate it as well.
5464       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5465         Op1 = CI2->getOperand(0);
5466
5467       // If Op1 is a constant, we can fold the cast into the constant.
5468       if (Op0->getType() != Op1->getType()) {
5469         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5470           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5471         } else {
5472           // Otherwise, cast the RHS right before the icmp
5473           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5474         }
5475       }
5476       return new ICmpInst(I.getPredicate(), Op0, Op1);
5477     }
5478   }
5479   
5480   if (isa<CastInst>(Op0)) {
5481     // Handle the special case of: icmp (cast bool to X), <cst>
5482     // This comes up when you have code like
5483     //   int X = A < B;
5484     //   if (X) ...
5485     // For generality, we handle any zero-extension of any operand comparison
5486     // with a constant or another cast from the same type.
5487     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5488       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5489         return R;
5490   }
5491   
5492   // See if it's the same type of instruction on the left and right.
5493   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5494     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
5495       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5496           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5497           I.isEquality()) {
5498         switch (Op0I->getOpcode()) {
5499         default: break;
5500         case Instruction::Add:
5501         case Instruction::Sub:
5502         case Instruction::Xor:
5503           // a+x icmp eq/ne b+x --> a icmp b
5504           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5505                               Op1I->getOperand(0));
5506           break;
5507         case Instruction::Mul:
5508           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5509             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5510             // Mask = -1 >> count-trailing-zeros(Cst).
5511             if (!CI->isZero() && !CI->isOne()) {
5512               const APInt &AP = CI->getValue();
5513               ConstantInt *Mask = ConstantInt::get(
5514                                       APInt::getLowBitsSet(AP.getBitWidth(),
5515                                                            AP.getBitWidth() -
5516                                                       AP.countTrailingZeros()));
5517               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5518                                                             Mask);
5519               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5520                                                             Mask);
5521               InsertNewInstBefore(And1, I);
5522               InsertNewInstBefore(And2, I);
5523               return new ICmpInst(I.getPredicate(), And1, And2);
5524             }
5525           }
5526           break;
5527         }
5528       }
5529     }
5530   }
5531   
5532   // ~x < ~y --> y < x
5533   { Value *A, *B;
5534     if (match(Op0, m_Not(m_Value(A))) &&
5535         match(Op1, m_Not(m_Value(B))))
5536       return new ICmpInst(I.getPredicate(), B, A);
5537   }
5538   
5539   if (I.isEquality()) {
5540     Value *A, *B, *C, *D;
5541     
5542     // -x == -y --> x == y
5543     if (match(Op0, m_Neg(m_Value(A))) &&
5544         match(Op1, m_Neg(m_Value(B))))
5545       return new ICmpInst(I.getPredicate(), A, B);
5546     
5547     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5548       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5549         Value *OtherVal = A == Op1 ? B : A;
5550         return new ICmpInst(I.getPredicate(), OtherVal,
5551                             Constant::getNullValue(A->getType()));
5552       }
5553
5554       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5555         // A^c1 == C^c2 --> A == C^(c1^c2)
5556         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5557           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5558             if (Op1->hasOneUse()) {
5559               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5560               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5561               return new ICmpInst(I.getPredicate(), A,
5562                                   InsertNewInstBefore(Xor, I));
5563             }
5564         
5565         // A^B == A^D -> B == D
5566         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5567         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5568         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5569         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5570       }
5571     }
5572     
5573     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5574         (A == Op0 || B == Op0)) {
5575       // A == (A^B)  ->  B == 0
5576       Value *OtherVal = A == Op0 ? B : A;
5577       return new ICmpInst(I.getPredicate(), OtherVal,
5578                           Constant::getNullValue(A->getType()));
5579     }
5580     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5581       // (A-B) == A  ->  B == 0
5582       return new ICmpInst(I.getPredicate(), B,
5583                           Constant::getNullValue(B->getType()));
5584     }
5585     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5586       // A == (A-B)  ->  B == 0
5587       return new ICmpInst(I.getPredicate(), B,
5588                           Constant::getNullValue(B->getType()));
5589     }
5590     
5591     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5592     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5593         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5594         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5595       Value *X = 0, *Y = 0, *Z = 0;
5596       
5597       if (A == C) {
5598         X = B; Y = D; Z = A;
5599       } else if (A == D) {
5600         X = B; Y = C; Z = A;
5601       } else if (B == C) {
5602         X = A; Y = D; Z = B;
5603       } else if (B == D) {
5604         X = A; Y = C; Z = B;
5605       }
5606       
5607       if (X) {   // Build (X^Y) & Z
5608         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5609         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5610         I.setOperand(0, Op1);
5611         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5612         return &I;
5613       }
5614     }
5615   }
5616   return Changed ? &I : 0;
5617 }
5618
5619
5620 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5621 /// and CmpRHS are both known to be integer constants.
5622 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5623                                           ConstantInt *DivRHS) {
5624   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5625   const APInt &CmpRHSV = CmpRHS->getValue();
5626   
5627   // FIXME: If the operand types don't match the type of the divide 
5628   // then don't attempt this transform. The code below doesn't have the
5629   // logic to deal with a signed divide and an unsigned compare (and
5630   // vice versa). This is because (x /s C1) <s C2  produces different 
5631   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5632   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5633   // work. :(  The if statement below tests that condition and bails 
5634   // if it finds it. 
5635   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5636   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5637     return 0;
5638   if (DivRHS->isZero())
5639     return 0; // The ProdOV computation fails on divide by zero.
5640
5641   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5642   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5643   // C2 (CI). By solving for X we can turn this into a range check 
5644   // instead of computing a divide. 
5645   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5646
5647   // Determine if the product overflows by seeing if the product is
5648   // not equal to the divide. Make sure we do the same kind of divide
5649   // as in the LHS instruction that we're folding. 
5650   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5651                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5652
5653   // Get the ICmp opcode
5654   ICmpInst::Predicate Pred = ICI.getPredicate();
5655
5656   // Figure out the interval that is being checked.  For example, a comparison
5657   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5658   // Compute this interval based on the constants involved and the signedness of
5659   // the compare/divide.  This computes a half-open interval, keeping track of
5660   // whether either value in the interval overflows.  After analysis each
5661   // overflow variable is set to 0 if it's corresponding bound variable is valid
5662   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5663   int LoOverflow = 0, HiOverflow = 0;
5664   ConstantInt *LoBound = 0, *HiBound = 0;
5665   
5666   
5667   if (!DivIsSigned) {  // udiv
5668     // e.g. X/5 op 3  --> [15, 20)
5669     LoBound = Prod;
5670     HiOverflow = LoOverflow = ProdOV;
5671     if (!HiOverflow)
5672       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5673   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5674     if (CmpRHSV == 0) {       // (X / pos) op 0
5675       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5676       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5677       HiBound = DivRHS;
5678     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5679       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5680       HiOverflow = LoOverflow = ProdOV;
5681       if (!HiOverflow)
5682         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5683     } else {                       // (X / pos) op neg
5684       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5685       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5686       LoOverflow = AddWithOverflow(LoBound, Prod,
5687                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5688       HiBound = AddOne(Prod);
5689       HiOverflow = ProdOV ? -1 : 0;
5690     }
5691   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5692     if (CmpRHSV == 0) {       // (X / neg) op 0
5693       // e.g. X/-5 op 0  --> [-4, 5)
5694       LoBound = AddOne(DivRHS);
5695       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5696       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5697         HiOverflow = 1;            // [INTMIN+1, overflow)
5698         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5699       }
5700     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5701       // e.g. X/-5 op 3  --> [-19, -14)
5702       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5703       if (!LoOverflow)
5704         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5705       HiBound = AddOne(Prod);
5706     } else {                       // (X / neg) op neg
5707       // e.g. X/-5 op -3  --> [15, 20)
5708       LoBound = Prod;
5709       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5710       HiBound = Subtract(Prod, DivRHS);
5711     }
5712     
5713     // Dividing by a negative swaps the condition.  LT <-> GT
5714     Pred = ICmpInst::getSwappedPredicate(Pred);
5715   }
5716
5717   Value *X = DivI->getOperand(0);
5718   switch (Pred) {
5719   default: assert(0 && "Unhandled icmp opcode!");
5720   case ICmpInst::ICMP_EQ:
5721     if (LoOverflow && HiOverflow)
5722       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5723     else if (HiOverflow)
5724       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5725                           ICmpInst::ICMP_UGE, X, LoBound);
5726     else if (LoOverflow)
5727       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5728                           ICmpInst::ICMP_ULT, X, HiBound);
5729     else
5730       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5731   case ICmpInst::ICMP_NE:
5732     if (LoOverflow && HiOverflow)
5733       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5734     else if (HiOverflow)
5735       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5736                           ICmpInst::ICMP_ULT, X, LoBound);
5737     else if (LoOverflow)
5738       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5739                           ICmpInst::ICMP_UGE, X, HiBound);
5740     else
5741       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5742   case ICmpInst::ICMP_ULT:
5743   case ICmpInst::ICMP_SLT:
5744     if (LoOverflow == +1)   // Low bound is greater than input range.
5745       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5746     if (LoOverflow == -1)   // Low bound is less than input range.
5747       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5748     return new ICmpInst(Pred, X, LoBound);
5749   case ICmpInst::ICMP_UGT:
5750   case ICmpInst::ICMP_SGT:
5751     if (HiOverflow == +1)       // High bound greater than input range.
5752       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5753     else if (HiOverflow == -1)  // High bound less than input range.
5754       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5755     if (Pred == ICmpInst::ICMP_UGT)
5756       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5757     else
5758       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5759   }
5760 }
5761
5762
5763 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5764 ///
5765 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5766                                                           Instruction *LHSI,
5767                                                           ConstantInt *RHS) {
5768   const APInt &RHSV = RHS->getValue();
5769   
5770   switch (LHSI->getOpcode()) {
5771   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5772     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5773       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5774       // fold the xor.
5775       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5776           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5777         Value *CompareVal = LHSI->getOperand(0);
5778         
5779         // If the sign bit of the XorCST is not set, there is no change to
5780         // the operation, just stop using the Xor.
5781         if (!XorCST->getValue().isNegative()) {
5782           ICI.setOperand(0, CompareVal);
5783           AddToWorkList(LHSI);
5784           return &ICI;
5785         }
5786         
5787         // Was the old condition true if the operand is positive?
5788         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5789         
5790         // If so, the new one isn't.
5791         isTrueIfPositive ^= true;
5792         
5793         if (isTrueIfPositive)
5794           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5795         else
5796           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5797       }
5798     }
5799     break;
5800   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5801     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5802         LHSI->getOperand(0)->hasOneUse()) {
5803       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5804       
5805       // If the LHS is an AND of a truncating cast, we can widen the
5806       // and/compare to be the input width without changing the value
5807       // produced, eliminating a cast.
5808       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5809         // We can do this transformation if either the AND constant does not
5810         // have its sign bit set or if it is an equality comparison. 
5811         // Extending a relational comparison when we're checking the sign
5812         // bit would not work.
5813         if (Cast->hasOneUse() &&
5814             (ICI.isEquality() ||
5815              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5816           uint32_t BitWidth = 
5817             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5818           APInt NewCST = AndCST->getValue();
5819           NewCST.zext(BitWidth);
5820           APInt NewCI = RHSV;
5821           NewCI.zext(BitWidth);
5822           Instruction *NewAnd = 
5823             BinaryOperator::CreateAnd(Cast->getOperand(0),
5824                                       ConstantInt::get(NewCST),LHSI->getName());
5825           InsertNewInstBefore(NewAnd, ICI);
5826           return new ICmpInst(ICI.getPredicate(), NewAnd,
5827                               ConstantInt::get(NewCI));
5828         }
5829       }
5830       
5831       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5832       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5833       // happens a LOT in code produced by the C front-end, for bitfield
5834       // access.
5835       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5836       if (Shift && !Shift->isShift())
5837         Shift = 0;
5838       
5839       ConstantInt *ShAmt;
5840       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5841       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5842       const Type *AndTy = AndCST->getType();          // Type of the and.
5843       
5844       // We can fold this as long as we can't shift unknown bits
5845       // into the mask.  This can only happen with signed shift
5846       // rights, as they sign-extend.
5847       if (ShAmt) {
5848         bool CanFold = Shift->isLogicalShift();
5849         if (!CanFold) {
5850           // To test for the bad case of the signed shr, see if any
5851           // of the bits shifted in could be tested after the mask.
5852           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5853           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5854           
5855           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5856           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5857                AndCST->getValue()) == 0)
5858             CanFold = true;
5859         }
5860         
5861         if (CanFold) {
5862           Constant *NewCst;
5863           if (Shift->getOpcode() == Instruction::Shl)
5864             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5865           else
5866             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5867           
5868           // Check to see if we are shifting out any of the bits being
5869           // compared.
5870           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5871             // If we shifted bits out, the fold is not going to work out.
5872             // As a special case, check to see if this means that the
5873             // result is always true or false now.
5874             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5875               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5876             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5877               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5878           } else {
5879             ICI.setOperand(1, NewCst);
5880             Constant *NewAndCST;
5881             if (Shift->getOpcode() == Instruction::Shl)
5882               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5883             else
5884               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5885             LHSI->setOperand(1, NewAndCST);
5886             LHSI->setOperand(0, Shift->getOperand(0));
5887             AddToWorkList(Shift); // Shift is dead.
5888             AddUsesToWorkList(ICI);
5889             return &ICI;
5890           }
5891         }
5892       }
5893       
5894       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5895       // preferable because it allows the C<<Y expression to be hoisted out
5896       // of a loop if Y is invariant and X is not.
5897       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5898           ICI.isEquality() && !Shift->isArithmeticShift() &&
5899           isa<Instruction>(Shift->getOperand(0))) {
5900         // Compute C << Y.
5901         Value *NS;
5902         if (Shift->getOpcode() == Instruction::LShr) {
5903           NS = BinaryOperator::CreateShl(AndCST, 
5904                                          Shift->getOperand(1), "tmp");
5905         } else {
5906           // Insert a logical shift.
5907           NS = BinaryOperator::CreateLShr(AndCST,
5908                                           Shift->getOperand(1), "tmp");
5909         }
5910         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5911         
5912         // Compute X & (C << Y).
5913         Instruction *NewAnd = 
5914           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5915         InsertNewInstBefore(NewAnd, ICI);
5916         
5917         ICI.setOperand(0, NewAnd);
5918         return &ICI;
5919       }
5920     }
5921     break;
5922     
5923   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5924     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5925     if (!ShAmt) break;
5926     
5927     uint32_t TypeBits = RHSV.getBitWidth();
5928     
5929     // Check that the shift amount is in range.  If not, don't perform
5930     // undefined shifts.  When the shift is visited it will be
5931     // simplified.
5932     if (ShAmt->uge(TypeBits))
5933       break;
5934     
5935     if (ICI.isEquality()) {
5936       // If we are comparing against bits always shifted out, the
5937       // comparison cannot succeed.
5938       Constant *Comp =
5939         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5940       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5941         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5942         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5943         return ReplaceInstUsesWith(ICI, Cst);
5944       }
5945       
5946       if (LHSI->hasOneUse()) {
5947         // Otherwise strength reduce the shift into an and.
5948         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5949         Constant *Mask =
5950           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5951         
5952         Instruction *AndI =
5953           BinaryOperator::CreateAnd(LHSI->getOperand(0),
5954                                     Mask, LHSI->getName()+".mask");
5955         Value *And = InsertNewInstBefore(AndI, ICI);
5956         return new ICmpInst(ICI.getPredicate(), And,
5957                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5958       }
5959     }
5960     
5961     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5962     bool TrueIfSigned = false;
5963     if (LHSI->hasOneUse() &&
5964         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5965       // (X << 31) <s 0  --> (X&1) != 0
5966       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5967                                            (TypeBits-ShAmt->getZExtValue()-1));
5968       Instruction *AndI =
5969         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5970                                   Mask, LHSI->getName()+".mask");
5971       Value *And = InsertNewInstBefore(AndI, ICI);
5972       
5973       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5974                           And, Constant::getNullValue(And->getType()));
5975     }
5976     break;
5977   }
5978     
5979   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5980   case Instruction::AShr: {
5981     // Only handle equality comparisons of shift-by-constant.
5982     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5983     if (!ShAmt || !ICI.isEquality()) break;
5984
5985     // Check that the shift amount is in range.  If not, don't perform
5986     // undefined shifts.  When the shift is visited it will be
5987     // simplified.
5988     uint32_t TypeBits = RHSV.getBitWidth();
5989     if (ShAmt->uge(TypeBits))
5990       break;
5991     
5992     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5993       
5994     // If we are comparing against bits always shifted out, the
5995     // comparison cannot succeed.
5996     APInt Comp = RHSV << ShAmtVal;
5997     if (LHSI->getOpcode() == Instruction::LShr)
5998       Comp = Comp.lshr(ShAmtVal);
5999     else
6000       Comp = Comp.ashr(ShAmtVal);
6001     
6002     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6003       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6004       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6005       return ReplaceInstUsesWith(ICI, Cst);
6006     }
6007     
6008     // Otherwise, check to see if the bits shifted out are known to be zero.
6009     // If so, we can compare against the unshifted value:
6010     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6011     if (LHSI->hasOneUse() &&
6012         MaskedValueIsZero(LHSI->getOperand(0), 
6013                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6014       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6015                           ConstantExpr::getShl(RHS, ShAmt));
6016     }
6017       
6018     if (LHSI->hasOneUse()) {
6019       // Otherwise strength reduce the shift into an and.
6020       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6021       Constant *Mask = ConstantInt::get(Val);
6022       
6023       Instruction *AndI =
6024         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6025                                   Mask, LHSI->getName()+".mask");
6026       Value *And = InsertNewInstBefore(AndI, ICI);
6027       return new ICmpInst(ICI.getPredicate(), And,
6028                           ConstantExpr::getShl(RHS, ShAmt));
6029     }
6030     break;
6031   }
6032     
6033   case Instruction::SDiv:
6034   case Instruction::UDiv:
6035     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6036     // Fold this div into the comparison, producing a range check. 
6037     // Determine, based on the divide type, what the range is being 
6038     // checked.  If there is an overflow on the low or high side, remember 
6039     // it, otherwise compute the range [low, hi) bounding the new value.
6040     // See: InsertRangeTest above for the kinds of replacements possible.
6041     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6042       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6043                                           DivRHS))
6044         return R;
6045     break;
6046
6047   case Instruction::Add:
6048     // Fold: icmp pred (add, X, C1), C2
6049
6050     if (!ICI.isEquality()) {
6051       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6052       if (!LHSC) break;
6053       const APInt &LHSV = LHSC->getValue();
6054
6055       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6056                             .subtract(LHSV);
6057
6058       if (ICI.isSignedPredicate()) {
6059         if (CR.getLower().isSignBit()) {
6060           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6061                               ConstantInt::get(CR.getUpper()));
6062         } else if (CR.getUpper().isSignBit()) {
6063           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6064                               ConstantInt::get(CR.getLower()));
6065         }
6066       } else {
6067         if (CR.getLower().isMinValue()) {
6068           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6069                               ConstantInt::get(CR.getUpper()));
6070         } else if (CR.getUpper().isMinValue()) {
6071           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6072                               ConstantInt::get(CR.getLower()));
6073         }
6074       }
6075     }
6076     break;
6077   }
6078   
6079   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6080   if (ICI.isEquality()) {
6081     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6082     
6083     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6084     // the second operand is a constant, simplify a bit.
6085     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6086       switch (BO->getOpcode()) {
6087       case Instruction::SRem:
6088         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6089         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6090           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6091           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6092             Instruction *NewRem =
6093               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6094                                          BO->getName());
6095             InsertNewInstBefore(NewRem, ICI);
6096             return new ICmpInst(ICI.getPredicate(), NewRem, 
6097                                 Constant::getNullValue(BO->getType()));
6098           }
6099         }
6100         break;
6101       case Instruction::Add:
6102         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6103         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6104           if (BO->hasOneUse())
6105             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6106                                 Subtract(RHS, BOp1C));
6107         } else if (RHSV == 0) {
6108           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6109           // efficiently invertible, or if the add has just this one use.
6110           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6111           
6112           if (Value *NegVal = dyn_castNegVal(BOp1))
6113             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6114           else if (Value *NegVal = dyn_castNegVal(BOp0))
6115             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6116           else if (BO->hasOneUse()) {
6117             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6118             InsertNewInstBefore(Neg, ICI);
6119             Neg->takeName(BO);
6120             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6121           }
6122         }
6123         break;
6124       case Instruction::Xor:
6125         // For the xor case, we can xor two constants together, eliminating
6126         // the explicit xor.
6127         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6128           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6129                               ConstantExpr::getXor(RHS, BOC));
6130         
6131         // FALLTHROUGH
6132       case Instruction::Sub:
6133         // Replace (([sub|xor] A, B) != 0) with (A != B)
6134         if (RHSV == 0)
6135           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6136                               BO->getOperand(1));
6137         break;
6138         
6139       case Instruction::Or:
6140         // If bits are being or'd in that are not present in the constant we
6141         // are comparing against, then the comparison could never succeed!
6142         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6143           Constant *NotCI = ConstantExpr::getNot(RHS);
6144           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6145             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6146                                                              isICMP_NE));
6147         }
6148         break;
6149         
6150       case Instruction::And:
6151         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6152           // If bits are being compared against that are and'd out, then the
6153           // comparison can never succeed!
6154           if ((RHSV & ~BOC->getValue()) != 0)
6155             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6156                                                              isICMP_NE));
6157           
6158           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6159           if (RHS == BOC && RHSV.isPowerOf2())
6160             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6161                                 ICmpInst::ICMP_NE, LHSI,
6162                                 Constant::getNullValue(RHS->getType()));
6163           
6164           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6165           if (BOC->getValue().isSignBit()) {
6166             Value *X = BO->getOperand(0);
6167             Constant *Zero = Constant::getNullValue(X->getType());
6168             ICmpInst::Predicate pred = isICMP_NE ? 
6169               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6170             return new ICmpInst(pred, X, Zero);
6171           }
6172           
6173           // ((X & ~7) == 0) --> X < 8
6174           if (RHSV == 0 && isHighOnes(BOC)) {
6175             Value *X = BO->getOperand(0);
6176             Constant *NegX = ConstantExpr::getNeg(BOC);
6177             ICmpInst::Predicate pred = isICMP_NE ? 
6178               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6179             return new ICmpInst(pred, X, NegX);
6180           }
6181         }
6182       default: break;
6183       }
6184     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6185       // Handle icmp {eq|ne} <intrinsic>, intcst.
6186       if (II->getIntrinsicID() == Intrinsic::bswap) {
6187         AddToWorkList(II);
6188         ICI.setOperand(0, II->getOperand(1));
6189         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6190         return &ICI;
6191       }
6192     }
6193   } else {  // Not a ICMP_EQ/ICMP_NE
6194             // If the LHS is a cast from an integral value of the same size, 
6195             // then since we know the RHS is a constant, try to simlify.
6196     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6197       Value *CastOp = Cast->getOperand(0);
6198       const Type *SrcTy = CastOp->getType();
6199       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6200       if (SrcTy->isInteger() && 
6201           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6202         // If this is an unsigned comparison, try to make the comparison use
6203         // smaller constant values.
6204         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6205           // X u< 128 => X s> -1
6206           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6207                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6208         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6209                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6210           // X u> 127 => X s< 0
6211           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6212                               Constant::getNullValue(SrcTy));
6213         }
6214       }
6215     }
6216   }
6217   return 0;
6218 }
6219
6220 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6221 /// We only handle extending casts so far.
6222 ///
6223 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6224   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6225   Value *LHSCIOp        = LHSCI->getOperand(0);
6226   const Type *SrcTy     = LHSCIOp->getType();
6227   const Type *DestTy    = LHSCI->getType();
6228   Value *RHSCIOp;
6229
6230   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6231   // integer type is the same size as the pointer type.
6232   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6233       getTargetData().getPointerSizeInBits() == 
6234          cast<IntegerType>(DestTy)->getBitWidth()) {
6235     Value *RHSOp = 0;
6236     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6237       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6238     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6239       RHSOp = RHSC->getOperand(0);
6240       // If the pointer types don't match, insert a bitcast.
6241       if (LHSCIOp->getType() != RHSOp->getType())
6242         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6243     }
6244
6245     if (RHSOp)
6246       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6247   }
6248   
6249   // The code below only handles extension cast instructions, so far.
6250   // Enforce this.
6251   if (LHSCI->getOpcode() != Instruction::ZExt &&
6252       LHSCI->getOpcode() != Instruction::SExt)
6253     return 0;
6254
6255   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6256   bool isSignedCmp = ICI.isSignedPredicate();
6257
6258   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6259     // Not an extension from the same type?
6260     RHSCIOp = CI->getOperand(0);
6261     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6262       return 0;
6263     
6264     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6265     // and the other is a zext), then we can't handle this.
6266     if (CI->getOpcode() != LHSCI->getOpcode())
6267       return 0;
6268
6269     // Deal with equality cases early.
6270     if (ICI.isEquality())
6271       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6272
6273     // A signed comparison of sign extended values simplifies into a
6274     // signed comparison.
6275     if (isSignedCmp && isSignedExt)
6276       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6277
6278     // The other three cases all fold into an unsigned comparison.
6279     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6280   }
6281
6282   // If we aren't dealing with a constant on the RHS, exit early
6283   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6284   if (!CI)
6285     return 0;
6286
6287   // Compute the constant that would happen if we truncated to SrcTy then
6288   // reextended to DestTy.
6289   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6290   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6291
6292   // If the re-extended constant didn't change...
6293   if (Res2 == CI) {
6294     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6295     // For example, we might have:
6296     //    %A = sext short %X to uint
6297     //    %B = icmp ugt uint %A, 1330
6298     // It is incorrect to transform this into 
6299     //    %B = icmp ugt short %X, 1330 
6300     // because %A may have negative value. 
6301     //
6302     // However, we allow this when the compare is EQ/NE, because they are
6303     // signless.
6304     if (isSignedExt == isSignedCmp || ICI.isEquality())
6305       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6306     return 0;
6307   }
6308
6309   // The re-extended constant changed so the constant cannot be represented 
6310   // in the shorter type. Consequently, we cannot emit a simple comparison.
6311
6312   // First, handle some easy cases. We know the result cannot be equal at this
6313   // point so handle the ICI.isEquality() cases
6314   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6315     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6316   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6317     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6318
6319   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6320   // should have been folded away previously and not enter in here.
6321   Value *Result;
6322   if (isSignedCmp) {
6323     // We're performing a signed comparison.
6324     if (cast<ConstantInt>(CI)->getValue().isNegative())
6325       Result = ConstantInt::getFalse();          // X < (small) --> false
6326     else
6327       Result = ConstantInt::getTrue();           // X < (large) --> true
6328   } else {
6329     // We're performing an unsigned comparison.
6330     if (isSignedExt) {
6331       // We're performing an unsigned comp with a sign extended value.
6332       // This is true if the input is >= 0. [aka >s -1]
6333       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6334       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6335                                    NegOne, ICI.getName()), ICI);
6336     } else {
6337       // Unsigned extend & unsigned compare -> always true.
6338       Result = ConstantInt::getTrue();
6339     }
6340   }
6341
6342   // Finally, return the value computed.
6343   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6344       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6345     return ReplaceInstUsesWith(ICI, Result);
6346
6347   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6348           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6349          "ICmp should be folded!");
6350   if (Constant *CI = dyn_cast<Constant>(Result))
6351     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6352   return BinaryOperator::CreateNot(Result);
6353 }
6354
6355 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6356   return commonShiftTransforms(I);
6357 }
6358
6359 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6360   return commonShiftTransforms(I);
6361 }
6362
6363 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6364   if (Instruction *R = commonShiftTransforms(I))
6365     return R;
6366   
6367   Value *Op0 = I.getOperand(0);
6368   
6369   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6370   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6371     if (CSI->isAllOnesValue())
6372       return ReplaceInstUsesWith(I, CSI);
6373   
6374   // See if we can turn a signed shr into an unsigned shr.
6375   if (!isa<VectorType>(I.getType()) &&
6376       MaskedValueIsZero(Op0,
6377                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6378     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6379   
6380   return 0;
6381 }
6382
6383 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6384   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6385   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6386
6387   // shl X, 0 == X and shr X, 0 == X
6388   // shl 0, X == 0 and shr 0, X == 0
6389   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6390       Op0 == Constant::getNullValue(Op0->getType()))
6391     return ReplaceInstUsesWith(I, Op0);
6392   
6393   if (isa<UndefValue>(Op0)) {            
6394     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6395       return ReplaceInstUsesWith(I, Op0);
6396     else                                    // undef << X -> 0, undef >>u X -> 0
6397       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6398   }
6399   if (isa<UndefValue>(Op1)) {
6400     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6401       return ReplaceInstUsesWith(I, Op0);          
6402     else                                     // X << undef, X >>u undef -> 0
6403       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6404   }
6405
6406   // Try to fold constant and into select arguments.
6407   if (isa<Constant>(Op0))
6408     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6409       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6410         return R;
6411
6412   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6413     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6414       return Res;
6415   return 0;
6416 }
6417
6418 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6419                                                BinaryOperator &I) {
6420   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6421
6422   // See if we can simplify any instructions used by the instruction whose sole 
6423   // purpose is to compute bits we don't care about.
6424   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6425   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6426   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6427                            KnownZero, KnownOne))
6428     return &I;
6429   
6430   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6431   // of a signed value.
6432   //
6433   if (Op1->uge(TypeBits)) {
6434     if (I.getOpcode() != Instruction::AShr)
6435       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6436     else {
6437       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6438       return &I;
6439     }
6440   }
6441   
6442   // ((X*C1) << C2) == (X * (C1 << C2))
6443   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6444     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6445       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6446         return BinaryOperator::CreateMul(BO->getOperand(0),
6447                                          ConstantExpr::getShl(BOOp, Op1));
6448   
6449   // Try to fold constant and into select arguments.
6450   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6451     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6452       return R;
6453   if (isa<PHINode>(Op0))
6454     if (Instruction *NV = FoldOpIntoPhi(I))
6455       return NV;
6456   
6457   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6458   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6459     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6460     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6461     // place.  Don't try to do this transformation in this case.  Also, we
6462     // require that the input operand is a shift-by-constant so that we have
6463     // confidence that the shifts will get folded together.  We could do this
6464     // xform in more cases, but it is unlikely to be profitable.
6465     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6466         isa<ConstantInt>(TrOp->getOperand(1))) {
6467       // Okay, we'll do this xform.  Make the shift of shift.
6468       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6469       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6470                                                 I.getName());
6471       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6472
6473       // For logical shifts, the truncation has the effect of making the high
6474       // part of the register be zeros.  Emulate this by inserting an AND to
6475       // clear the top bits as needed.  This 'and' will usually be zapped by
6476       // other xforms later if dead.
6477       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6478       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6479       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6480       
6481       // The mask we constructed says what the trunc would do if occurring
6482       // between the shifts.  We want to know the effect *after* the second
6483       // shift.  We know that it is a logical shift by a constant, so adjust the
6484       // mask as appropriate.
6485       if (I.getOpcode() == Instruction::Shl)
6486         MaskV <<= Op1->getZExtValue();
6487       else {
6488         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6489         MaskV = MaskV.lshr(Op1->getZExtValue());
6490       }
6491
6492       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6493                                                    TI->getName());
6494       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6495
6496       // Return the value truncated to the interesting size.
6497       return new TruncInst(And, I.getType());
6498     }
6499   }
6500   
6501   if (Op0->hasOneUse()) {
6502     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6503       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6504       Value *V1, *V2;
6505       ConstantInt *CC;
6506       switch (Op0BO->getOpcode()) {
6507         default: break;
6508         case Instruction::Add:
6509         case Instruction::And:
6510         case Instruction::Or:
6511         case Instruction::Xor: {
6512           // These operators commute.
6513           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6514           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6515               match(Op0BO->getOperand(1),
6516                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6517             Instruction *YS = BinaryOperator::CreateShl(
6518                                             Op0BO->getOperand(0), Op1,
6519                                             Op0BO->getName());
6520             InsertNewInstBefore(YS, I); // (Y << C)
6521             Instruction *X = 
6522               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6523                                      Op0BO->getOperand(1)->getName());
6524             InsertNewInstBefore(X, I);  // (X + (Y << C))
6525             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6526             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6527                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6528           }
6529           
6530           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6531           Value *Op0BOOp1 = Op0BO->getOperand(1);
6532           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6533               match(Op0BOOp1, 
6534                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6535               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6536               V2 == Op1) {
6537             Instruction *YS = BinaryOperator::CreateShl(
6538                                                      Op0BO->getOperand(0), Op1,
6539                                                      Op0BO->getName());
6540             InsertNewInstBefore(YS, I); // (Y << C)
6541             Instruction *XM =
6542               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6543                                         V1->getName()+".mask");
6544             InsertNewInstBefore(XM, I); // X & (CC << C)
6545             
6546             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6547           }
6548         }
6549           
6550         // FALL THROUGH.
6551         case Instruction::Sub: {
6552           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6553           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6554               match(Op0BO->getOperand(0),
6555                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6556             Instruction *YS = BinaryOperator::CreateShl(
6557                                                      Op0BO->getOperand(1), Op1,
6558                                                      Op0BO->getName());
6559             InsertNewInstBefore(YS, I); // (Y << C)
6560             Instruction *X =
6561               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6562                                      Op0BO->getOperand(0)->getName());
6563             InsertNewInstBefore(X, I);  // (X + (Y << C))
6564             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6565             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6566                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6567           }
6568           
6569           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6570           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6571               match(Op0BO->getOperand(0),
6572                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6573                           m_ConstantInt(CC))) && V2 == Op1 &&
6574               cast<BinaryOperator>(Op0BO->getOperand(0))
6575                   ->getOperand(0)->hasOneUse()) {
6576             Instruction *YS = BinaryOperator::CreateShl(
6577                                                      Op0BO->getOperand(1), Op1,
6578                                                      Op0BO->getName());
6579             InsertNewInstBefore(YS, I); // (Y << C)
6580             Instruction *XM =
6581               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6582                                         V1->getName()+".mask");
6583             InsertNewInstBefore(XM, I); // X & (CC << C)
6584             
6585             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6586           }
6587           
6588           break;
6589         }
6590       }
6591       
6592       
6593       // If the operand is an bitwise operator with a constant RHS, and the
6594       // shift is the only use, we can pull it out of the shift.
6595       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6596         bool isValid = true;     // Valid only for And, Or, Xor
6597         bool highBitSet = false; // Transform if high bit of constant set?
6598         
6599         switch (Op0BO->getOpcode()) {
6600           default: isValid = false; break;   // Do not perform transform!
6601           case Instruction::Add:
6602             isValid = isLeftShift;
6603             break;
6604           case Instruction::Or:
6605           case Instruction::Xor:
6606             highBitSet = false;
6607             break;
6608           case Instruction::And:
6609             highBitSet = true;
6610             break;
6611         }
6612         
6613         // If this is a signed shift right, and the high bit is modified
6614         // by the logical operation, do not perform the transformation.
6615         // The highBitSet boolean indicates the value of the high bit of
6616         // the constant which would cause it to be modified for this
6617         // operation.
6618         //
6619         if (isValid && I.getOpcode() == Instruction::AShr)
6620           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6621         
6622         if (isValid) {
6623           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6624           
6625           Instruction *NewShift =
6626             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6627           InsertNewInstBefore(NewShift, I);
6628           NewShift->takeName(Op0BO);
6629           
6630           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6631                                         NewRHS);
6632         }
6633       }
6634     }
6635   }
6636   
6637   // Find out if this is a shift of a shift by a constant.
6638   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6639   if (ShiftOp && !ShiftOp->isShift())
6640     ShiftOp = 0;
6641   
6642   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6643     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6644     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6645     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6646     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6647     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6648     Value *X = ShiftOp->getOperand(0);
6649     
6650     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6651     if (AmtSum > TypeBits)
6652       AmtSum = TypeBits;
6653     
6654     const IntegerType *Ty = cast<IntegerType>(I.getType());
6655     
6656     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6657     if (I.getOpcode() == ShiftOp->getOpcode()) {
6658       return BinaryOperator::Create(I.getOpcode(), X,
6659                                     ConstantInt::get(Ty, AmtSum));
6660     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6661                I.getOpcode() == Instruction::AShr) {
6662       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6663       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6664     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6665                I.getOpcode() == Instruction::LShr) {
6666       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6667       Instruction *Shift =
6668         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6669       InsertNewInstBefore(Shift, I);
6670
6671       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6672       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6673     }
6674     
6675     // Okay, if we get here, one shift must be left, and the other shift must be
6676     // right.  See if the amounts are equal.
6677     if (ShiftAmt1 == ShiftAmt2) {
6678       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6679       if (I.getOpcode() == Instruction::Shl) {
6680         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6681         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6682       }
6683       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6684       if (I.getOpcode() == Instruction::LShr) {
6685         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6686         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6687       }
6688       // We can simplify ((X << C) >>s C) into a trunc + sext.
6689       // NOTE: we could do this for any C, but that would make 'unusual' integer
6690       // types.  For now, just stick to ones well-supported by the code
6691       // generators.
6692       const Type *SExtType = 0;
6693       switch (Ty->getBitWidth() - ShiftAmt1) {
6694       case 1  :
6695       case 8  :
6696       case 16 :
6697       case 32 :
6698       case 64 :
6699       case 128:
6700         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6701         break;
6702       default: break;
6703       }
6704       if (SExtType) {
6705         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6706         InsertNewInstBefore(NewTrunc, I);
6707         return new SExtInst(NewTrunc, Ty);
6708       }
6709       // Otherwise, we can't handle it yet.
6710     } else if (ShiftAmt1 < ShiftAmt2) {
6711       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6712       
6713       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6714       if (I.getOpcode() == Instruction::Shl) {
6715         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6716                ShiftOp->getOpcode() == Instruction::AShr);
6717         Instruction *Shift =
6718           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6719         InsertNewInstBefore(Shift, I);
6720         
6721         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6722         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6723       }
6724       
6725       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6726       if (I.getOpcode() == Instruction::LShr) {
6727         assert(ShiftOp->getOpcode() == Instruction::Shl);
6728         Instruction *Shift =
6729           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6730         InsertNewInstBefore(Shift, I);
6731         
6732         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6733         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6734       }
6735       
6736       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6737     } else {
6738       assert(ShiftAmt2 < ShiftAmt1);
6739       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6740
6741       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6742       if (I.getOpcode() == Instruction::Shl) {
6743         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6744                ShiftOp->getOpcode() == Instruction::AShr);
6745         Instruction *Shift =
6746           BinaryOperator::Create(ShiftOp->getOpcode(), X,
6747                                  ConstantInt::get(Ty, ShiftDiff));
6748         InsertNewInstBefore(Shift, I);
6749         
6750         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6751         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6752       }
6753       
6754       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6755       if (I.getOpcode() == Instruction::LShr) {
6756         assert(ShiftOp->getOpcode() == Instruction::Shl);
6757         Instruction *Shift =
6758           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6759         InsertNewInstBefore(Shift, I);
6760         
6761         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6762         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6763       }
6764       
6765       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6766     }
6767   }
6768   return 0;
6769 }
6770
6771
6772 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6773 /// expression.  If so, decompose it, returning some value X, such that Val is
6774 /// X*Scale+Offset.
6775 ///
6776 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6777                                         int &Offset) {
6778   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6779   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6780     Offset = CI->getZExtValue();
6781     Scale  = 0;
6782     return ConstantInt::get(Type::Int32Ty, 0);
6783   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6784     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6785       if (I->getOpcode() == Instruction::Shl) {
6786         // This is a value scaled by '1 << the shift amt'.
6787         Scale = 1U << RHS->getZExtValue();
6788         Offset = 0;
6789         return I->getOperand(0);
6790       } else if (I->getOpcode() == Instruction::Mul) {
6791         // This value is scaled by 'RHS'.
6792         Scale = RHS->getZExtValue();
6793         Offset = 0;
6794         return I->getOperand(0);
6795       } else if (I->getOpcode() == Instruction::Add) {
6796         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6797         // where C1 is divisible by C2.
6798         unsigned SubScale;
6799         Value *SubVal = 
6800           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6801         Offset += RHS->getZExtValue();
6802         Scale = SubScale;
6803         return SubVal;
6804       }
6805     }
6806   }
6807
6808   // Otherwise, we can't look past this.
6809   Scale = 1;
6810   Offset = 0;
6811   return Val;
6812 }
6813
6814
6815 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6816 /// try to eliminate the cast by moving the type information into the alloc.
6817 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6818                                                    AllocationInst &AI) {
6819   const PointerType *PTy = cast<PointerType>(CI.getType());
6820   
6821   // Remove any uses of AI that are dead.
6822   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6823   
6824   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6825     Instruction *User = cast<Instruction>(*UI++);
6826     if (isInstructionTriviallyDead(User)) {
6827       while (UI != E && *UI == User)
6828         ++UI; // If this instruction uses AI more than once, don't break UI.
6829       
6830       ++NumDeadInst;
6831       DOUT << "IC: DCE: " << *User;
6832       EraseInstFromFunction(*User);
6833     }
6834   }
6835   
6836   // Get the type really allocated and the type casted to.
6837   const Type *AllocElTy = AI.getAllocatedType();
6838   const Type *CastElTy = PTy->getElementType();
6839   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6840
6841   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6842   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6843   if (CastElTyAlign < AllocElTyAlign) return 0;
6844
6845   // If the allocation has multiple uses, only promote it if we are strictly
6846   // increasing the alignment of the resultant allocation.  If we keep it the
6847   // same, we open the door to infinite loops of various kinds.
6848   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6849
6850   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6851   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6852   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6853
6854   // See if we can satisfy the modulus by pulling a scale out of the array
6855   // size argument.
6856   unsigned ArraySizeScale;
6857   int ArrayOffset;
6858   Value *NumElements = // See if the array size is a decomposable linear expr.
6859     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6860  
6861   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6862   // do the xform.
6863   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6864       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6865
6866   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6867   Value *Amt = 0;
6868   if (Scale == 1) {
6869     Amt = NumElements;
6870   } else {
6871     // If the allocation size is constant, form a constant mul expression
6872     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6873     if (isa<ConstantInt>(NumElements))
6874       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6875     // otherwise multiply the amount and the number of elements
6876     else if (Scale != 1) {
6877       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6878       Amt = InsertNewInstBefore(Tmp, AI);
6879     }
6880   }
6881   
6882   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6883     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6884     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6885     Amt = InsertNewInstBefore(Tmp, AI);
6886   }
6887   
6888   AllocationInst *New;
6889   if (isa<MallocInst>(AI))
6890     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6891   else
6892     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6893   InsertNewInstBefore(New, AI);
6894   New->takeName(&AI);
6895   
6896   // If the allocation has multiple uses, insert a cast and change all things
6897   // that used it to use the new cast.  This will also hack on CI, but it will
6898   // die soon.
6899   if (!AI.hasOneUse()) {
6900     AddUsesToWorkList(AI);
6901     // New is the allocation instruction, pointer typed. AI is the original
6902     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6903     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6904     InsertNewInstBefore(NewCast, AI);
6905     AI.replaceAllUsesWith(NewCast);
6906   }
6907   return ReplaceInstUsesWith(CI, New);
6908 }
6909
6910 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6911 /// and return it as type Ty without inserting any new casts and without
6912 /// changing the computed value.  This is used by code that tries to decide
6913 /// whether promoting or shrinking integer operations to wider or smaller types
6914 /// will allow us to eliminate a truncate or extend.
6915 ///
6916 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6917 /// extension operation if Ty is larger.
6918 ///
6919 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
6920 /// should return true if trunc(V) can be computed by computing V in the smaller
6921 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
6922 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6923 /// efficiently truncated.
6924 ///
6925 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6926 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6927 /// the final result.
6928 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6929                                               unsigned CastOpc,
6930                                               int &NumCastsRemoved) {
6931   // We can always evaluate constants in another type.
6932   if (isa<ConstantInt>(V))
6933     return true;
6934   
6935   Instruction *I = dyn_cast<Instruction>(V);
6936   if (!I) return false;
6937   
6938   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6939   
6940   // If this is an extension or truncate, we can often eliminate it.
6941   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6942     // If this is a cast from the destination type, we can trivially eliminate
6943     // it, and this will remove a cast overall.
6944     if (I->getOperand(0)->getType() == Ty) {
6945       // If the first operand is itself a cast, and is eliminable, do not count
6946       // this as an eliminable cast.  We would prefer to eliminate those two
6947       // casts first.
6948       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
6949         ++NumCastsRemoved;
6950       return true;
6951     }
6952   }
6953
6954   // We can't extend or shrink something that has multiple uses: doing so would
6955   // require duplicating the instruction in general, which isn't profitable.
6956   if (!I->hasOneUse()) return false;
6957
6958   switch (I->getOpcode()) {
6959   case Instruction::Add:
6960   case Instruction::Sub:
6961   case Instruction::Mul:
6962   case Instruction::And:
6963   case Instruction::Or:
6964   case Instruction::Xor:
6965     // These operators can all arbitrarily be extended or truncated.
6966     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6967                                       NumCastsRemoved) &&
6968            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6969                                       NumCastsRemoved);
6970
6971   case Instruction::Shl:
6972     // If we are truncating the result of this SHL, and if it's a shift of a
6973     // constant amount, we can always perform a SHL in a smaller type.
6974     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6975       uint32_t BitWidth = Ty->getBitWidth();
6976       if (BitWidth < OrigTy->getBitWidth() && 
6977           CI->getLimitedValue(BitWidth) < BitWidth)
6978         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6979                                           NumCastsRemoved);
6980     }
6981     break;
6982   case Instruction::LShr:
6983     // If this is a truncate of a logical shr, we can truncate it to a smaller
6984     // lshr iff we know that the bits we would otherwise be shifting in are
6985     // already zeros.
6986     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6987       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6988       uint32_t BitWidth = Ty->getBitWidth();
6989       if (BitWidth < OrigBitWidth &&
6990           MaskedValueIsZero(I->getOperand(0),
6991             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6992           CI->getLimitedValue(BitWidth) < BitWidth) {
6993         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6994                                           NumCastsRemoved);
6995       }
6996     }
6997     break;
6998   case Instruction::ZExt:
6999   case Instruction::SExt:
7000   case Instruction::Trunc:
7001     // If this is the same kind of case as our original (e.g. zext+zext), we
7002     // can safely replace it.  Note that replacing it does not reduce the number
7003     // of casts in the input.
7004     if (I->getOpcode() == CastOpc)
7005       return true;
7006     break;
7007   case Instruction::Select: {
7008     SelectInst *SI = cast<SelectInst>(I);
7009     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7010                                       NumCastsRemoved) &&
7011            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7012                                       NumCastsRemoved);
7013   }
7014   case Instruction::PHI: {
7015     // We can change a phi if we can change all operands.
7016     PHINode *PN = cast<PHINode>(I);
7017     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7018       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7019                                       NumCastsRemoved))
7020         return false;
7021     return true;
7022   }
7023   default:
7024     // TODO: Can handle more cases here.
7025     break;
7026   }
7027   
7028   return false;
7029 }
7030
7031 /// EvaluateInDifferentType - Given an expression that 
7032 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7033 /// evaluate the expression.
7034 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7035                                              bool isSigned) {
7036   if (Constant *C = dyn_cast<Constant>(V))
7037     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7038
7039   // Otherwise, it must be an instruction.
7040   Instruction *I = cast<Instruction>(V);
7041   Instruction *Res = 0;
7042   switch (I->getOpcode()) {
7043   case Instruction::Add:
7044   case Instruction::Sub:
7045   case Instruction::Mul:
7046   case Instruction::And:
7047   case Instruction::Or:
7048   case Instruction::Xor:
7049   case Instruction::AShr:
7050   case Instruction::LShr:
7051   case Instruction::Shl: {
7052     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7053     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7054     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7055                                  LHS, RHS);
7056     break;
7057   }    
7058   case Instruction::Trunc:
7059   case Instruction::ZExt:
7060   case Instruction::SExt:
7061     // If the source type of the cast is the type we're trying for then we can
7062     // just return the source.  There's no need to insert it because it is not
7063     // new.
7064     if (I->getOperand(0)->getType() == Ty)
7065       return I->getOperand(0);
7066     
7067     // Otherwise, must be the same type of cast, so just reinsert a new one.
7068     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7069                            Ty);
7070     break;
7071   case Instruction::Select: {
7072     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7073     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7074     Res = SelectInst::Create(I->getOperand(0), True, False);
7075     break;
7076   }
7077   case Instruction::PHI: {
7078     PHINode *OPN = cast<PHINode>(I);
7079     PHINode *NPN = PHINode::Create(Ty);
7080     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7081       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7082       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7083     }
7084     Res = NPN;
7085     break;
7086   }
7087   default: 
7088     // TODO: Can handle more cases here.
7089     assert(0 && "Unreachable!");
7090     break;
7091   }
7092   
7093   Res->takeName(I);
7094   return InsertNewInstBefore(Res, *I);
7095 }
7096
7097 /// @brief Implement the transforms common to all CastInst visitors.
7098 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7099   Value *Src = CI.getOperand(0);
7100
7101   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7102   // eliminate it now.
7103   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7104     if (Instruction::CastOps opc = 
7105         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7106       // The first cast (CSrc) is eliminable so we need to fix up or replace
7107       // the second cast (CI). CSrc will then have a good chance of being dead.
7108       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7109     }
7110   }
7111
7112   // If we are casting a select then fold the cast into the select
7113   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7114     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7115       return NV;
7116
7117   // If we are casting a PHI then fold the cast into the PHI
7118   if (isa<PHINode>(Src))
7119     if (Instruction *NV = FoldOpIntoPhi(CI))
7120       return NV;
7121   
7122   return 0;
7123 }
7124
7125 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7126 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7127   Value *Src = CI.getOperand(0);
7128   
7129   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7130     // If casting the result of a getelementptr instruction with no offset, turn
7131     // this into a cast of the original pointer!
7132     if (GEP->hasAllZeroIndices()) {
7133       // Changing the cast operand is usually not a good idea but it is safe
7134       // here because the pointer operand is being replaced with another 
7135       // pointer operand so the opcode doesn't need to change.
7136       AddToWorkList(GEP);
7137       CI.setOperand(0, GEP->getOperand(0));
7138       return &CI;
7139     }
7140     
7141     // If the GEP has a single use, and the base pointer is a bitcast, and the
7142     // GEP computes a constant offset, see if we can convert these three
7143     // instructions into fewer.  This typically happens with unions and other
7144     // non-type-safe code.
7145     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7146       if (GEP->hasAllConstantIndices()) {
7147         // We are guaranteed to get a constant from EmitGEPOffset.
7148         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7149         int64_t Offset = OffsetV->getSExtValue();
7150         
7151         // Get the base pointer input of the bitcast, and the type it points to.
7152         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7153         const Type *GEPIdxTy =
7154           cast<PointerType>(OrigBase->getType())->getElementType();
7155         if (GEPIdxTy->isSized()) {
7156           SmallVector<Value*, 8> NewIndices;
7157           
7158           // Start with the index over the outer type.  Note that the type size
7159           // might be zero (even if the offset isn't zero) if the indexed type
7160           // is something like [0 x {int, int}]
7161           const Type *IntPtrTy = TD->getIntPtrType();
7162           int64_t FirstIdx = 0;
7163           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7164             FirstIdx = Offset/TySize;
7165             Offset %= TySize;
7166           
7167             // Handle silly modulus not returning values values [0..TySize).
7168             if (Offset < 0) {
7169               --FirstIdx;
7170               Offset += TySize;
7171               assert(Offset >= 0);
7172             }
7173             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7174           }
7175           
7176           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7177
7178           // Index into the types.  If we fail, set OrigBase to null.
7179           while (Offset) {
7180             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7181               const StructLayout *SL = TD->getStructLayout(STy);
7182               if (Offset < (int64_t)SL->getSizeInBytes()) {
7183                 unsigned Elt = SL->getElementContainingOffset(Offset);
7184                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7185               
7186                 Offset -= SL->getElementOffset(Elt);
7187                 GEPIdxTy = STy->getElementType(Elt);
7188               } else {
7189                 // Otherwise, we can't index into this, bail out.
7190                 Offset = 0;
7191                 OrigBase = 0;
7192               }
7193             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7194               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7195               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7196                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7197                 Offset %= EltSize;
7198               } else {
7199                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7200               }
7201               GEPIdxTy = STy->getElementType();
7202             } else {
7203               // Otherwise, we can't index into this, bail out.
7204               Offset = 0;
7205               OrigBase = 0;
7206             }
7207           }
7208           if (OrigBase) {
7209             // If we were able to index down into an element, create the GEP
7210             // and bitcast the result.  This eliminates one bitcast, potentially
7211             // two.
7212             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7213                                                           NewIndices.begin(),
7214                                                           NewIndices.end(), "");
7215             InsertNewInstBefore(NGEP, CI);
7216             NGEP->takeName(GEP);
7217             
7218             if (isa<BitCastInst>(CI))
7219               return new BitCastInst(NGEP, CI.getType());
7220             assert(isa<PtrToIntInst>(CI));
7221             return new PtrToIntInst(NGEP, CI.getType());
7222           }
7223         }
7224       }      
7225     }
7226   }
7227     
7228   return commonCastTransforms(CI);
7229 }
7230
7231
7232
7233 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7234 /// integer types. This function implements the common transforms for all those
7235 /// cases.
7236 /// @brief Implement the transforms common to CastInst with integer operands
7237 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7238   if (Instruction *Result = commonCastTransforms(CI))
7239     return Result;
7240
7241   Value *Src = CI.getOperand(0);
7242   const Type *SrcTy = Src->getType();
7243   const Type *DestTy = CI.getType();
7244   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7245   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7246
7247   // See if we can simplify any instructions used by the LHS whose sole 
7248   // purpose is to compute bits we don't care about.
7249   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7250   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7251                            KnownZero, KnownOne))
7252     return &CI;
7253
7254   // If the source isn't an instruction or has more than one use then we
7255   // can't do anything more. 
7256   Instruction *SrcI = dyn_cast<Instruction>(Src);
7257   if (!SrcI || !Src->hasOneUse())
7258     return 0;
7259
7260   // Attempt to propagate the cast into the instruction for int->int casts.
7261   int NumCastsRemoved = 0;
7262   if (!isa<BitCastInst>(CI) &&
7263       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7264                                  CI.getOpcode(), NumCastsRemoved)) {
7265     // If this cast is a truncate, evaluting in a different type always
7266     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7267     // we need to do an AND to maintain the clear top-part of the computation,
7268     // so we require that the input have eliminated at least one cast.  If this
7269     // is a sign extension, we insert two new casts (to do the extension) so we
7270     // require that two casts have been eliminated.
7271     bool DoXForm;
7272     switch (CI.getOpcode()) {
7273     default:
7274       // All the others use floating point so we shouldn't actually 
7275       // get here because of the check above.
7276       assert(0 && "Unknown cast type");
7277     case Instruction::Trunc:
7278       DoXForm = true;
7279       break;
7280     case Instruction::ZExt:
7281       DoXForm = NumCastsRemoved >= 1;
7282       break;
7283     case Instruction::SExt:
7284       DoXForm = NumCastsRemoved >= 2;
7285       break;
7286     }
7287     
7288     if (DoXForm) {
7289       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7290                                            CI.getOpcode() == Instruction::SExt);
7291       assert(Res->getType() == DestTy);
7292       switch (CI.getOpcode()) {
7293       default: assert(0 && "Unknown cast type!");
7294       case Instruction::Trunc:
7295       case Instruction::BitCast:
7296         // Just replace this cast with the result.
7297         return ReplaceInstUsesWith(CI, Res);
7298       case Instruction::ZExt: {
7299         // We need to emit an AND to clear the high bits.
7300         assert(SrcBitSize < DestBitSize && "Not a zext?");
7301         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7302                                                             SrcBitSize));
7303         return BinaryOperator::CreateAnd(Res, C);
7304       }
7305       case Instruction::SExt:
7306         // We need to emit a cast to truncate, then a cast to sext.
7307         return CastInst::Create(Instruction::SExt,
7308             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7309                              CI), DestTy);
7310       }
7311     }
7312   }
7313   
7314   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7315   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7316
7317   switch (SrcI->getOpcode()) {
7318   case Instruction::Add:
7319   case Instruction::Mul:
7320   case Instruction::And:
7321   case Instruction::Or:
7322   case Instruction::Xor:
7323     // If we are discarding information, rewrite.
7324     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7325       // Don't insert two casts if they cannot be eliminated.  We allow 
7326       // two casts to be inserted if the sizes are the same.  This could 
7327       // only be converting signedness, which is a noop.
7328       if (DestBitSize == SrcBitSize || 
7329           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7330           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7331         Instruction::CastOps opcode = CI.getOpcode();
7332         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7333         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7334         return BinaryOperator::Create(
7335             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7336       }
7337     }
7338
7339     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7340     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7341         SrcI->getOpcode() == Instruction::Xor &&
7342         Op1 == ConstantInt::getTrue() &&
7343         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7344       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7345       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7346     }
7347     break;
7348   case Instruction::SDiv:
7349   case Instruction::UDiv:
7350   case Instruction::SRem:
7351   case Instruction::URem:
7352     // If we are just changing the sign, rewrite.
7353     if (DestBitSize == SrcBitSize) {
7354       // Don't insert two casts if they cannot be eliminated.  We allow 
7355       // two casts to be inserted if the sizes are the same.  This could 
7356       // only be converting signedness, which is a noop.
7357       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7358           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7359         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7360                                               Op0, DestTy, SrcI);
7361         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7362                                               Op1, DestTy, SrcI);
7363         return BinaryOperator::Create(
7364           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7365       }
7366     }
7367     break;
7368
7369   case Instruction::Shl:
7370     // Allow changing the sign of the source operand.  Do not allow 
7371     // changing the size of the shift, UNLESS the shift amount is a 
7372     // constant.  We must not change variable sized shifts to a smaller 
7373     // size, because it is undefined to shift more bits out than exist 
7374     // in the value.
7375     if (DestBitSize == SrcBitSize ||
7376         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7377       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7378           Instruction::BitCast : Instruction::Trunc);
7379       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7380       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7381       return BinaryOperator::CreateShl(Op0c, Op1c);
7382     }
7383     break;
7384   case Instruction::AShr:
7385     // If this is a signed shr, and if all bits shifted in are about to be
7386     // truncated off, turn it into an unsigned shr to allow greater
7387     // simplifications.
7388     if (DestBitSize < SrcBitSize &&
7389         isa<ConstantInt>(Op1)) {
7390       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7391       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7392         // Insert the new logical shift right.
7393         return BinaryOperator::CreateLShr(Op0, Op1);
7394       }
7395     }
7396     break;
7397   }
7398   return 0;
7399 }
7400
7401 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7402   if (Instruction *Result = commonIntCastTransforms(CI))
7403     return Result;
7404   
7405   Value *Src = CI.getOperand(0);
7406   const Type *Ty = CI.getType();
7407   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7408   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7409   
7410   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7411     switch (SrcI->getOpcode()) {
7412     default: break;
7413     case Instruction::LShr:
7414       // We can shrink lshr to something smaller if we know the bits shifted in
7415       // are already zeros.
7416       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7417         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7418         
7419         // Get a mask for the bits shifting in.
7420         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7421         Value* SrcIOp0 = SrcI->getOperand(0);
7422         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7423           if (ShAmt >= DestBitWidth)        // All zeros.
7424             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7425
7426           // Okay, we can shrink this.  Truncate the input, then return a new
7427           // shift.
7428           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7429           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7430                                        Ty, CI);
7431           return BinaryOperator::CreateLShr(V1, V2);
7432         }
7433       } else {     // This is a variable shr.
7434         
7435         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7436         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7437         // loop-invariant and CSE'd.
7438         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7439           Value *One = ConstantInt::get(SrcI->getType(), 1);
7440
7441           Value *V = InsertNewInstBefore(
7442               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7443                                      "tmp"), CI);
7444           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7445                                                             SrcI->getOperand(0),
7446                                                             "tmp"), CI);
7447           Value *Zero = Constant::getNullValue(V->getType());
7448           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7449         }
7450       }
7451       break;
7452     }
7453   }
7454   
7455   return 0;
7456 }
7457
7458 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7459 /// in order to eliminate the icmp.
7460 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7461                                              bool DoXform) {
7462   // If we are just checking for a icmp eq of a single bit and zext'ing it
7463   // to an integer, then shift the bit to the appropriate place and then
7464   // cast to integer to avoid the comparison.
7465   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7466     const APInt &Op1CV = Op1C->getValue();
7467       
7468     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7469     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7470     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7471         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7472       if (!DoXform) return ICI;
7473
7474       Value *In = ICI->getOperand(0);
7475       Value *Sh = ConstantInt::get(In->getType(),
7476                                    In->getType()->getPrimitiveSizeInBits()-1);
7477       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7478                                                         In->getName()+".lobit"),
7479                                CI);
7480       if (In->getType() != CI.getType())
7481         In = CastInst::CreateIntegerCast(In, CI.getType(),
7482                                          false/*ZExt*/, "tmp", &CI);
7483
7484       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7485         Constant *One = ConstantInt::get(In->getType(), 1);
7486         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7487                                                          In->getName()+".not"),
7488                                  CI);
7489       }
7490
7491       return ReplaceInstUsesWith(CI, In);
7492     }
7493       
7494       
7495       
7496     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7497     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7498     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7499     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7500     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7501     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7502     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7503     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7504     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7505         // This only works for EQ and NE
7506         ICI->isEquality()) {
7507       // If Op1C some other power of two, convert:
7508       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7509       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7510       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7511       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7512         
7513       APInt KnownZeroMask(~KnownZero);
7514       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7515         if (!DoXform) return ICI;
7516
7517         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7518         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7519           // (X&4) == 2 --> false
7520           // (X&4) != 2 --> true
7521           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7522           Res = ConstantExpr::getZExt(Res, CI.getType());
7523           return ReplaceInstUsesWith(CI, Res);
7524         }
7525           
7526         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7527         Value *In = ICI->getOperand(0);
7528         if (ShiftAmt) {
7529           // Perform a logical shr by shiftamt.
7530           // Insert the shift to put the result in the low bit.
7531           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7532                                   ConstantInt::get(In->getType(), ShiftAmt),
7533                                                    In->getName()+".lobit"), CI);
7534         }
7535           
7536         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7537           Constant *One = ConstantInt::get(In->getType(), 1);
7538           In = BinaryOperator::CreateXor(In, One, "tmp");
7539           InsertNewInstBefore(cast<Instruction>(In), CI);
7540         }
7541           
7542         if (CI.getType() == In->getType())
7543           return ReplaceInstUsesWith(CI, In);
7544         else
7545           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7546       }
7547     }
7548   }
7549
7550   return 0;
7551 }
7552
7553 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7554   // If one of the common conversion will work ..
7555   if (Instruction *Result = commonIntCastTransforms(CI))
7556     return Result;
7557
7558   Value *Src = CI.getOperand(0);
7559
7560   // If this is a cast of a cast
7561   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7562     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7563     // types and if the sizes are just right we can convert this into a logical
7564     // 'and' which will be much cheaper than the pair of casts.
7565     if (isa<TruncInst>(CSrc)) {
7566       // Get the sizes of the types involved
7567       Value *A = CSrc->getOperand(0);
7568       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7569       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7570       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7571       // If we're actually extending zero bits and the trunc is a no-op
7572       if (MidSize < DstSize && SrcSize == DstSize) {
7573         // Replace both of the casts with an And of the type mask.
7574         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7575         Constant *AndConst = ConstantInt::get(AndValue);
7576         Instruction *And = 
7577           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7578         // Unfortunately, if the type changed, we need to cast it back.
7579         if (And->getType() != CI.getType()) {
7580           And->setName(CSrc->getName()+".mask");
7581           InsertNewInstBefore(And, CI);
7582           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7583         }
7584         return And;
7585       }
7586     }
7587   }
7588
7589   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7590     return transformZExtICmp(ICI, CI);
7591
7592   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7593   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7594     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7595     // of the (zext icmp) will be transformed.
7596     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7597     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7598     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7599         (transformZExtICmp(LHS, CI, false) ||
7600          transformZExtICmp(RHS, CI, false))) {
7601       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7602       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7603       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7604     }
7605   }
7606
7607   return 0;
7608 }
7609
7610 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7611   if (Instruction *I = commonIntCastTransforms(CI))
7612     return I;
7613   
7614   Value *Src = CI.getOperand(0);
7615   
7616   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7617   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7618   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7619     // If we are just checking for a icmp eq of a single bit and zext'ing it
7620     // to an integer, then shift the bit to the appropriate place and then
7621     // cast to integer to avoid the comparison.
7622     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7623       const APInt &Op1CV = Op1C->getValue();
7624       
7625       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7626       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7627       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7628           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7629         Value *In = ICI->getOperand(0);
7630         Value *Sh = ConstantInt::get(In->getType(),
7631                                      In->getType()->getPrimitiveSizeInBits()-1);
7632         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7633                                                         In->getName()+".lobit"),
7634                                  CI);
7635         if (In->getType() != CI.getType())
7636           In = CastInst::CreateIntegerCast(In, CI.getType(),
7637                                            true/*SExt*/, "tmp", &CI);
7638         
7639         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7640           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7641                                      In->getName()+".not"), CI);
7642         
7643         return ReplaceInstUsesWith(CI, In);
7644       }
7645     }
7646   }
7647
7648   // See if the value being truncated is already sign extended.  If so, just
7649   // eliminate the trunc/sext pair.
7650   if (getOpcode(Src) == Instruction::Trunc) {
7651     Value *Op = cast<User>(Src)->getOperand(0);
7652     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
7653     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
7654     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7655     unsigned NumSignBits = ComputeNumSignBits(Op);
7656
7657     if (OpBits == DestBits) {
7658       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7659       // bits, it is already ready.
7660       if (NumSignBits > DestBits-MidBits)
7661         return ReplaceInstUsesWith(CI, Op);
7662     } else if (OpBits < DestBits) {
7663       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7664       // bits, just sext from i32.
7665       if (NumSignBits > OpBits-MidBits)
7666         return new SExtInst(Op, CI.getType(), "tmp");
7667     } else {
7668       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7669       // bits, just truncate to i32.
7670       if (NumSignBits > OpBits-MidBits)
7671         return new TruncInst(Op, CI.getType(), "tmp");
7672     }
7673   }
7674
7675   // If the input is a shl/ashr pair of a same constant, then this is a sign
7676   // extension from a smaller value.  If we could trust arbitrary bitwidth
7677   // integers, we could turn this into a truncate to the smaller bit and then
7678   // use a sext for the whole extension.  Since we don't, look deeper and check
7679   // for a truncate.  If the source and dest are the same type, eliminate the
7680   // trunc and extend and just do shifts.  For example, turn:
7681   //   %a = trunc i32 %i to i8
7682   //   %b = shl i8 %a, 6
7683   //   %c = ashr i8 %b, 6
7684   //   %d = sext i8 %c to i32
7685   // into:
7686   //   %a = shl i32 %i, 30
7687   //   %d = ashr i32 %a, 30
7688   Value *A = 0;
7689   ConstantInt *BA = 0, *CA = 0;
7690   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
7691                         m_ConstantInt(CA))) &&
7692       BA == CA && isa<TruncInst>(A)) {
7693     Value *I = cast<TruncInst>(A)->getOperand(0);
7694     if (I->getType() == CI.getType()) {
7695       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
7696       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
7697       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
7698       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
7699       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
7700                                                         CI.getName()), CI);
7701       return BinaryOperator::CreateAShr(I, ShAmtV);
7702     }
7703   }
7704   
7705   return 0;
7706 }
7707
7708 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7709 /// in the specified FP type without changing its value.
7710 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7711   APFloat F = CFP->getValueAPF();
7712   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7713     return ConstantFP::get(F);
7714   return 0;
7715 }
7716
7717 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7718 /// through it until we get the source value.
7719 static Value *LookThroughFPExtensions(Value *V) {
7720   if (Instruction *I = dyn_cast<Instruction>(V))
7721     if (I->getOpcode() == Instruction::FPExt)
7722       return LookThroughFPExtensions(I->getOperand(0));
7723   
7724   // If this value is a constant, return the constant in the smallest FP type
7725   // that can accurately represent it.  This allows us to turn
7726   // (float)((double)X+2.0) into x+2.0f.
7727   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7728     if (CFP->getType() == Type::PPC_FP128Ty)
7729       return V;  // No constant folding of this.
7730     // See if the value can be truncated to float and then reextended.
7731     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7732       return V;
7733     if (CFP->getType() == Type::DoubleTy)
7734       return V;  // Won't shrink.
7735     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7736       return V;
7737     // Don't try to shrink to various long double types.
7738   }
7739   
7740   return V;
7741 }
7742
7743 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7744   if (Instruction *I = commonCastTransforms(CI))
7745     return I;
7746   
7747   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7748   // smaller than the destination type, we can eliminate the truncate by doing
7749   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7750   // many builtins (sqrt, etc).
7751   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7752   if (OpI && OpI->hasOneUse()) {
7753     switch (OpI->getOpcode()) {
7754     default: break;
7755     case Instruction::Add:
7756     case Instruction::Sub:
7757     case Instruction::Mul:
7758     case Instruction::FDiv:
7759     case Instruction::FRem:
7760       const Type *SrcTy = OpI->getType();
7761       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7762       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7763       if (LHSTrunc->getType() != SrcTy && 
7764           RHSTrunc->getType() != SrcTy) {
7765         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7766         // If the source types were both smaller than the destination type of
7767         // the cast, do this xform.
7768         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7769             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7770           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7771                                       CI.getType(), CI);
7772           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7773                                       CI.getType(), CI);
7774           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7775         }
7776       }
7777       break;  
7778     }
7779   }
7780   return 0;
7781 }
7782
7783 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7784   return commonCastTransforms(CI);
7785 }
7786
7787 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7788   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7789   if (OpI == 0)
7790     return commonCastTransforms(FI);
7791
7792   // fptoui(uitofp(X)) --> X
7793   // fptoui(sitofp(X)) --> X
7794   // This is safe if the intermediate type has enough bits in its mantissa to
7795   // accurately represent all values of X.  For example, do not do this with
7796   // i64->float->i64.  This is also safe for sitofp case, because any negative
7797   // 'X' value would cause an undefined result for the fptoui. 
7798   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7799       OpI->getOperand(0)->getType() == FI.getType() &&
7800       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7801                     OpI->getType()->getFPMantissaWidth())
7802     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
7803
7804   return commonCastTransforms(FI);
7805 }
7806
7807 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7808   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7809   if (OpI == 0)
7810     return commonCastTransforms(FI);
7811   
7812   // fptosi(sitofp(X)) --> X
7813   // fptosi(uitofp(X)) --> X
7814   // This is safe if the intermediate type has enough bits in its mantissa to
7815   // accurately represent all values of X.  For example, do not do this with
7816   // i64->float->i64.  This is also safe for sitofp case, because any negative
7817   // 'X' value would cause an undefined result for the fptoui. 
7818   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7819       OpI->getOperand(0)->getType() == FI.getType() &&
7820       (int)FI.getType()->getPrimitiveSizeInBits() <= 
7821                     OpI->getType()->getFPMantissaWidth())
7822     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
7823   
7824   return commonCastTransforms(FI);
7825 }
7826
7827 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7828   return commonCastTransforms(CI);
7829 }
7830
7831 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7832   return commonCastTransforms(CI);
7833 }
7834
7835 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7836   return commonPointerCastTransforms(CI);
7837 }
7838
7839 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7840   if (Instruction *I = commonCastTransforms(CI))
7841     return I;
7842   
7843   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7844   if (!DestPointee->isSized()) return 0;
7845
7846   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7847   ConstantInt *Cst;
7848   Value *X;
7849   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7850                                     m_ConstantInt(Cst)))) {
7851     // If the source and destination operands have the same type, see if this
7852     // is a single-index GEP.
7853     if (X->getType() == CI.getType()) {
7854       // Get the size of the pointee type.
7855       uint64_t Size = TD->getABITypeSize(DestPointee);
7856
7857       // Convert the constant to intptr type.
7858       APInt Offset = Cst->getValue();
7859       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7860
7861       // If Offset is evenly divisible by Size, we can do this xform.
7862       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7863         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7864         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7865       }
7866     }
7867     // TODO: Could handle other cases, e.g. where add is indexing into field of
7868     // struct etc.
7869   } else if (CI.getOperand(0)->hasOneUse() &&
7870              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7871     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7872     // "inttoptr+GEP" instead of "add+intptr".
7873     
7874     // Get the size of the pointee type.
7875     uint64_t Size = TD->getABITypeSize(DestPointee);
7876     
7877     // Convert the constant to intptr type.
7878     APInt Offset = Cst->getValue();
7879     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7880     
7881     // If Offset is evenly divisible by Size, we can do this xform.
7882     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7883       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7884       
7885       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7886                                                             "tmp"), CI);
7887       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7888     }
7889   }
7890   return 0;
7891 }
7892
7893 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7894   // If the operands are integer typed then apply the integer transforms,
7895   // otherwise just apply the common ones.
7896   Value *Src = CI.getOperand(0);
7897   const Type *SrcTy = Src->getType();
7898   const Type *DestTy = CI.getType();
7899
7900   if (SrcTy->isInteger() && DestTy->isInteger()) {
7901     if (Instruction *Result = commonIntCastTransforms(CI))
7902       return Result;
7903   } else if (isa<PointerType>(SrcTy)) {
7904     if (Instruction *I = commonPointerCastTransforms(CI))
7905       return I;
7906   } else {
7907     if (Instruction *Result = commonCastTransforms(CI))
7908       return Result;
7909   }
7910
7911
7912   // Get rid of casts from one type to the same type. These are useless and can
7913   // be replaced by the operand.
7914   if (DestTy == Src->getType())
7915     return ReplaceInstUsesWith(CI, Src);
7916
7917   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7918     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7919     const Type *DstElTy = DstPTy->getElementType();
7920     const Type *SrcElTy = SrcPTy->getElementType();
7921     
7922     // If the address spaces don't match, don't eliminate the bitcast, which is
7923     // required for changing types.
7924     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7925       return 0;
7926     
7927     // If we are casting a malloc or alloca to a pointer to a type of the same
7928     // size, rewrite the allocation instruction to allocate the "right" type.
7929     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7930       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7931         return V;
7932     
7933     // If the source and destination are pointers, and this cast is equivalent
7934     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7935     // This can enhance SROA and other transforms that want type-safe pointers.
7936     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7937     unsigned NumZeros = 0;
7938     while (SrcElTy != DstElTy && 
7939            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7940            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7941       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7942       ++NumZeros;
7943     }
7944
7945     // If we found a path from the src to dest, create the getelementptr now.
7946     if (SrcElTy == DstElTy) {
7947       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7948       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
7949                                        ((Instruction*) NULL));
7950     }
7951   }
7952
7953   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7954     if (SVI->hasOneUse()) {
7955       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7956       // a bitconvert to a vector with the same # elts.
7957       if (isa<VectorType>(DestTy) && 
7958           cast<VectorType>(DestTy)->getNumElements() == 
7959                 SVI->getType()->getNumElements()) {
7960         CastInst *Tmp;
7961         // If either of the operands is a cast from CI.getType(), then
7962         // evaluating the shuffle in the casted destination's type will allow
7963         // us to eliminate at least one cast.
7964         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7965              Tmp->getOperand(0)->getType() == DestTy) ||
7966             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7967              Tmp->getOperand(0)->getType() == DestTy)) {
7968           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7969                                                SVI->getOperand(0), DestTy, &CI);
7970           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7971                                                SVI->getOperand(1), DestTy, &CI);
7972           // Return a new shuffle vector.  Use the same element ID's, as we
7973           // know the vector types match #elts.
7974           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7975         }
7976       }
7977     }
7978   }
7979   return 0;
7980 }
7981
7982 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7983 ///   %C = or %A, %B
7984 ///   %D = select %cond, %C, %A
7985 /// into:
7986 ///   %C = select %cond, %B, 0
7987 ///   %D = or %A, %C
7988 ///
7989 /// Assuming that the specified instruction is an operand to the select, return
7990 /// a bitmask indicating which operands of this instruction are foldable if they
7991 /// equal the other incoming value of the select.
7992 ///
7993 static unsigned GetSelectFoldableOperands(Instruction *I) {
7994   switch (I->getOpcode()) {
7995   case Instruction::Add:
7996   case Instruction::Mul:
7997   case Instruction::And:
7998   case Instruction::Or:
7999   case Instruction::Xor:
8000     return 3;              // Can fold through either operand.
8001   case Instruction::Sub:   // Can only fold on the amount subtracted.
8002   case Instruction::Shl:   // Can only fold on the shift amount.
8003   case Instruction::LShr:
8004   case Instruction::AShr:
8005     return 1;
8006   default:
8007     return 0;              // Cannot fold
8008   }
8009 }
8010
8011 /// GetSelectFoldableConstant - For the same transformation as the previous
8012 /// function, return the identity constant that goes into the select.
8013 static Constant *GetSelectFoldableConstant(Instruction *I) {
8014   switch (I->getOpcode()) {
8015   default: assert(0 && "This cannot happen!"); abort();
8016   case Instruction::Add:
8017   case Instruction::Sub:
8018   case Instruction::Or:
8019   case Instruction::Xor:
8020   case Instruction::Shl:
8021   case Instruction::LShr:
8022   case Instruction::AShr:
8023     return Constant::getNullValue(I->getType());
8024   case Instruction::And:
8025     return Constant::getAllOnesValue(I->getType());
8026   case Instruction::Mul:
8027     return ConstantInt::get(I->getType(), 1);
8028   }
8029 }
8030
8031 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8032 /// have the same opcode and only one use each.  Try to simplify this.
8033 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8034                                           Instruction *FI) {
8035   if (TI->getNumOperands() == 1) {
8036     // If this is a non-volatile load or a cast from the same type,
8037     // merge.
8038     if (TI->isCast()) {
8039       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8040         return 0;
8041     } else {
8042       return 0;  // unknown unary op.
8043     }
8044
8045     // Fold this by inserting a select from the input values.
8046     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8047                                            FI->getOperand(0), SI.getName()+".v");
8048     InsertNewInstBefore(NewSI, SI);
8049     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8050                             TI->getType());
8051   }
8052
8053   // Only handle binary operators here.
8054   if (!isa<BinaryOperator>(TI))
8055     return 0;
8056
8057   // Figure out if the operations have any operands in common.
8058   Value *MatchOp, *OtherOpT, *OtherOpF;
8059   bool MatchIsOpZero;
8060   if (TI->getOperand(0) == FI->getOperand(0)) {
8061     MatchOp  = TI->getOperand(0);
8062     OtherOpT = TI->getOperand(1);
8063     OtherOpF = FI->getOperand(1);
8064     MatchIsOpZero = true;
8065   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8066     MatchOp  = TI->getOperand(1);
8067     OtherOpT = TI->getOperand(0);
8068     OtherOpF = FI->getOperand(0);
8069     MatchIsOpZero = false;
8070   } else if (!TI->isCommutative()) {
8071     return 0;
8072   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8073     MatchOp  = TI->getOperand(0);
8074     OtherOpT = TI->getOperand(1);
8075     OtherOpF = FI->getOperand(0);
8076     MatchIsOpZero = true;
8077   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8078     MatchOp  = TI->getOperand(1);
8079     OtherOpT = TI->getOperand(0);
8080     OtherOpF = FI->getOperand(1);
8081     MatchIsOpZero = true;
8082   } else {
8083     return 0;
8084   }
8085
8086   // If we reach here, they do have operations in common.
8087   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8088                                          OtherOpF, SI.getName()+".v");
8089   InsertNewInstBefore(NewSI, SI);
8090
8091   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8092     if (MatchIsOpZero)
8093       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8094     else
8095       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8096   }
8097   assert(0 && "Shouldn't get here");
8098   return 0;
8099 }
8100
8101 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8102   Value *CondVal = SI.getCondition();
8103   Value *TrueVal = SI.getTrueValue();
8104   Value *FalseVal = SI.getFalseValue();
8105
8106   // select true, X, Y  -> X
8107   // select false, X, Y -> Y
8108   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8109     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8110
8111   // select C, X, X -> X
8112   if (TrueVal == FalseVal)
8113     return ReplaceInstUsesWith(SI, TrueVal);
8114
8115   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8116     return ReplaceInstUsesWith(SI, FalseVal);
8117   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8118     return ReplaceInstUsesWith(SI, TrueVal);
8119   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8120     if (isa<Constant>(TrueVal))
8121       return ReplaceInstUsesWith(SI, TrueVal);
8122     else
8123       return ReplaceInstUsesWith(SI, FalseVal);
8124   }
8125
8126   if (SI.getType() == Type::Int1Ty) {
8127     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8128       if (C->getZExtValue()) {
8129         // Change: A = select B, true, C --> A = or B, C
8130         return BinaryOperator::CreateOr(CondVal, FalseVal);
8131       } else {
8132         // Change: A = select B, false, C --> A = and !B, C
8133         Value *NotCond =
8134           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8135                                              "not."+CondVal->getName()), SI);
8136         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8137       }
8138     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8139       if (C->getZExtValue() == false) {
8140         // Change: A = select B, C, false --> A = and B, C
8141         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8142       } else {
8143         // Change: A = select B, C, true --> A = or !B, C
8144         Value *NotCond =
8145           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8146                                              "not."+CondVal->getName()), SI);
8147         return BinaryOperator::CreateOr(NotCond, TrueVal);
8148       }
8149     }
8150     
8151     // select a, b, a  -> a&b
8152     // select a, a, b  -> a|b
8153     if (CondVal == TrueVal)
8154       return BinaryOperator::CreateOr(CondVal, FalseVal);
8155     else if (CondVal == FalseVal)
8156       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8157   }
8158
8159   // Selecting between two integer constants?
8160   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8161     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8162       // select C, 1, 0 -> zext C to int
8163       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8164         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8165       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8166         // select C, 0, 1 -> zext !C to int
8167         Value *NotCond =
8168           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8169                                                "not."+CondVal->getName()), SI);
8170         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8171       }
8172       
8173       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8174
8175       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8176
8177         // (x <s 0) ? -1 : 0 -> ashr x, 31
8178         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8179           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8180             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8181               // The comparison constant and the result are not neccessarily the
8182               // same width. Make an all-ones value by inserting a AShr.
8183               Value *X = IC->getOperand(0);
8184               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8185               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8186               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8187                                                         ShAmt, "ones");
8188               InsertNewInstBefore(SRA, SI);
8189               
8190               // Finally, convert to the type of the select RHS.  We figure out
8191               // if this requires a SExt, Trunc or BitCast based on the sizes.
8192               Instruction::CastOps opc = Instruction::BitCast;
8193               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8194               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8195               if (SRASize < SISize)
8196                 opc = Instruction::SExt;
8197               else if (SRASize > SISize)
8198                 opc = Instruction::Trunc;
8199               return CastInst::Create(opc, SRA, SI.getType());
8200             }
8201           }
8202
8203
8204         // If one of the constants is zero (we know they can't both be) and we
8205         // have an icmp instruction with zero, and we have an 'and' with the
8206         // non-constant value, eliminate this whole mess.  This corresponds to
8207         // cases like this: ((X & 27) ? 27 : 0)
8208         if (TrueValC->isZero() || FalseValC->isZero())
8209           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8210               cast<Constant>(IC->getOperand(1))->isNullValue())
8211             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8212               if (ICA->getOpcode() == Instruction::And &&
8213                   isa<ConstantInt>(ICA->getOperand(1)) &&
8214                   (ICA->getOperand(1) == TrueValC ||
8215                    ICA->getOperand(1) == FalseValC) &&
8216                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8217                 // Okay, now we know that everything is set up, we just don't
8218                 // know whether we have a icmp_ne or icmp_eq and whether the 
8219                 // true or false val is the zero.
8220                 bool ShouldNotVal = !TrueValC->isZero();
8221                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8222                 Value *V = ICA;
8223                 if (ShouldNotVal)
8224                   V = InsertNewInstBefore(BinaryOperator::Create(
8225                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8226                 return ReplaceInstUsesWith(SI, V);
8227               }
8228       }
8229     }
8230
8231   // See if we are selecting two values based on a comparison of the two values.
8232   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8233     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8234       // Transform (X == Y) ? X : Y  -> Y
8235       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8236         // This is not safe in general for floating point:  
8237         // consider X== -0, Y== +0.
8238         // It becomes safe if either operand is a nonzero constant.
8239         ConstantFP *CFPt, *CFPf;
8240         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8241               !CFPt->getValueAPF().isZero()) ||
8242             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8243              !CFPf->getValueAPF().isZero()))
8244         return ReplaceInstUsesWith(SI, FalseVal);
8245       }
8246       // Transform (X != Y) ? X : Y  -> X
8247       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8248         return ReplaceInstUsesWith(SI, TrueVal);
8249       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8250
8251     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8252       // Transform (X == Y) ? Y : X  -> X
8253       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8254         // This is not safe in general for floating point:  
8255         // consider X== -0, Y== +0.
8256         // It becomes safe if either operand is a nonzero constant.
8257         ConstantFP *CFPt, *CFPf;
8258         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8259               !CFPt->getValueAPF().isZero()) ||
8260             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8261              !CFPf->getValueAPF().isZero()))
8262           return ReplaceInstUsesWith(SI, FalseVal);
8263       }
8264       // Transform (X != Y) ? Y : X  -> Y
8265       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8266         return ReplaceInstUsesWith(SI, TrueVal);
8267       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8268     }
8269   }
8270
8271   // See if we are selecting two values based on a comparison of the two values.
8272   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8273     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8274       // Transform (X == Y) ? X : Y  -> Y
8275       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8276         return ReplaceInstUsesWith(SI, FalseVal);
8277       // Transform (X != Y) ? X : Y  -> X
8278       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8279         return ReplaceInstUsesWith(SI, TrueVal);
8280       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8281
8282     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8283       // Transform (X == Y) ? Y : X  -> X
8284       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8285         return ReplaceInstUsesWith(SI, FalseVal);
8286       // Transform (X != Y) ? Y : X  -> Y
8287       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8288         return ReplaceInstUsesWith(SI, TrueVal);
8289       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8290     }
8291   }
8292
8293   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8294     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8295       if (TI->hasOneUse() && FI->hasOneUse()) {
8296         Instruction *AddOp = 0, *SubOp = 0;
8297
8298         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8299         if (TI->getOpcode() == FI->getOpcode())
8300           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8301             return IV;
8302
8303         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8304         // even legal for FP.
8305         if (TI->getOpcode() == Instruction::Sub &&
8306             FI->getOpcode() == Instruction::Add) {
8307           AddOp = FI; SubOp = TI;
8308         } else if (FI->getOpcode() == Instruction::Sub &&
8309                    TI->getOpcode() == Instruction::Add) {
8310           AddOp = TI; SubOp = FI;
8311         }
8312
8313         if (AddOp) {
8314           Value *OtherAddOp = 0;
8315           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8316             OtherAddOp = AddOp->getOperand(1);
8317           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8318             OtherAddOp = AddOp->getOperand(0);
8319           }
8320
8321           if (OtherAddOp) {
8322             // So at this point we know we have (Y -> OtherAddOp):
8323             //        select C, (add X, Y), (sub X, Z)
8324             Value *NegVal;  // Compute -Z
8325             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8326               NegVal = ConstantExpr::getNeg(C);
8327             } else {
8328               NegVal = InsertNewInstBefore(
8329                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8330             }
8331
8332             Value *NewTrueOp = OtherAddOp;
8333             Value *NewFalseOp = NegVal;
8334             if (AddOp != TI)
8335               std::swap(NewTrueOp, NewFalseOp);
8336             Instruction *NewSel =
8337               SelectInst::Create(CondVal, NewTrueOp,
8338                                  NewFalseOp, SI.getName() + ".p");
8339
8340             NewSel = InsertNewInstBefore(NewSel, SI);
8341             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8342           }
8343         }
8344       }
8345
8346   // See if we can fold the select into one of our operands.
8347   if (SI.getType()->isInteger()) {
8348     // See the comment above GetSelectFoldableOperands for a description of the
8349     // transformation we are doing here.
8350     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8351       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8352           !isa<Constant>(FalseVal))
8353         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8354           unsigned OpToFold = 0;
8355           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8356             OpToFold = 1;
8357           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8358             OpToFold = 2;
8359           }
8360
8361           if (OpToFold) {
8362             Constant *C = GetSelectFoldableConstant(TVI);
8363             Instruction *NewSel =
8364               SelectInst::Create(SI.getCondition(),
8365                                  TVI->getOperand(2-OpToFold), C);
8366             InsertNewInstBefore(NewSel, SI);
8367             NewSel->takeName(TVI);
8368             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8369               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8370             else {
8371               assert(0 && "Unknown instruction!!");
8372             }
8373           }
8374         }
8375
8376     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8377       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8378           !isa<Constant>(TrueVal))
8379         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8380           unsigned OpToFold = 0;
8381           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8382             OpToFold = 1;
8383           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8384             OpToFold = 2;
8385           }
8386
8387           if (OpToFold) {
8388             Constant *C = GetSelectFoldableConstant(FVI);
8389             Instruction *NewSel =
8390               SelectInst::Create(SI.getCondition(), C,
8391                                  FVI->getOperand(2-OpToFold));
8392             InsertNewInstBefore(NewSel, SI);
8393             NewSel->takeName(FVI);
8394             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8395               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8396             else
8397               assert(0 && "Unknown instruction!!");
8398           }
8399         }
8400   }
8401
8402   if (BinaryOperator::isNot(CondVal)) {
8403     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8404     SI.setOperand(1, FalseVal);
8405     SI.setOperand(2, TrueVal);
8406     return &SI;
8407   }
8408
8409   return 0;
8410 }
8411
8412 /// EnforceKnownAlignment - If the specified pointer points to an object that
8413 /// we control, modify the object's alignment to PrefAlign. This isn't
8414 /// often possible though. If alignment is important, a more reliable approach
8415 /// is to simply align all global variables and allocation instructions to
8416 /// their preferred alignment from the beginning.
8417 ///
8418 static unsigned EnforceKnownAlignment(Value *V,
8419                                       unsigned Align, unsigned PrefAlign) {
8420
8421   User *U = dyn_cast<User>(V);
8422   if (!U) return Align;
8423
8424   switch (getOpcode(U)) {
8425   default: break;
8426   case Instruction::BitCast:
8427     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8428   case Instruction::GetElementPtr: {
8429     // If all indexes are zero, it is just the alignment of the base pointer.
8430     bool AllZeroOperands = true;
8431     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8432       if (!isa<Constant>(*i) ||
8433           !cast<Constant>(*i)->isNullValue()) {
8434         AllZeroOperands = false;
8435         break;
8436       }
8437
8438     if (AllZeroOperands) {
8439       // Treat this like a bitcast.
8440       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8441     }
8442     break;
8443   }
8444   }
8445
8446   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8447     // If there is a large requested alignment and we can, bump up the alignment
8448     // of the global.
8449     if (!GV->isDeclaration()) {
8450       GV->setAlignment(PrefAlign);
8451       Align = PrefAlign;
8452     }
8453   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8454     // If there is a requested alignment and if this is an alloca, round up.  We
8455     // don't do this for malloc, because some systems can't respect the request.
8456     if (isa<AllocaInst>(AI)) {
8457       AI->setAlignment(PrefAlign);
8458       Align = PrefAlign;
8459     }
8460   }
8461
8462   return Align;
8463 }
8464
8465 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8466 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8467 /// and it is more than the alignment of the ultimate object, see if we can
8468 /// increase the alignment of the ultimate object, making this check succeed.
8469 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8470                                                   unsigned PrefAlign) {
8471   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8472                       sizeof(PrefAlign) * CHAR_BIT;
8473   APInt Mask = APInt::getAllOnesValue(BitWidth);
8474   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8475   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8476   unsigned TrailZ = KnownZero.countTrailingOnes();
8477   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8478
8479   if (PrefAlign > Align)
8480     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8481   
8482     // We don't need to make any adjustment.
8483   return Align;
8484 }
8485
8486 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8487   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8488   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8489   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8490   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8491
8492   if (CopyAlign < MinAlign) {
8493     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8494     return MI;
8495   }
8496   
8497   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8498   // load/store.
8499   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8500   if (MemOpLength == 0) return 0;
8501   
8502   // Source and destination pointer types are always "i8*" for intrinsic.  See
8503   // if the size is something we can handle with a single primitive load/store.
8504   // A single load+store correctly handles overlapping memory in the memmove
8505   // case.
8506   unsigned Size = MemOpLength->getZExtValue();
8507   if (Size == 0) return MI;  // Delete this mem transfer.
8508   
8509   if (Size > 8 || (Size&(Size-1)))
8510     return 0;  // If not 1/2/4/8 bytes, exit.
8511   
8512   // Use an integer load+store unless we can find something better.
8513   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8514   
8515   // Memcpy forces the use of i8* for the source and destination.  That means
8516   // that if you're using memcpy to move one double around, you'll get a cast
8517   // from double* to i8*.  We'd much rather use a double load+store rather than
8518   // an i64 load+store, here because this improves the odds that the source or
8519   // dest address will be promotable.  See if we can find a better type than the
8520   // integer datatype.
8521   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8522     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8523     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8524       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8525       // down through these levels if so.
8526       while (!SrcETy->isSingleValueType()) {
8527         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8528           if (STy->getNumElements() == 1)
8529             SrcETy = STy->getElementType(0);
8530           else
8531             break;
8532         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8533           if (ATy->getNumElements() == 1)
8534             SrcETy = ATy->getElementType();
8535           else
8536             break;
8537         } else
8538           break;
8539       }
8540       
8541       if (SrcETy->isSingleValueType())
8542         NewPtrTy = PointerType::getUnqual(SrcETy);
8543     }
8544   }
8545   
8546   
8547   // If the memcpy/memmove provides better alignment info than we can
8548   // infer, use it.
8549   SrcAlign = std::max(SrcAlign, CopyAlign);
8550   DstAlign = std::max(DstAlign, CopyAlign);
8551   
8552   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8553   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8554   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8555   InsertNewInstBefore(L, *MI);
8556   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8557
8558   // Set the size of the copy to 0, it will be deleted on the next iteration.
8559   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8560   return MI;
8561 }
8562
8563 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8564   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8565   if (MI->getAlignment()->getZExtValue() < Alignment) {
8566     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8567     return MI;
8568   }
8569   
8570   // Extract the length and alignment and fill if they are constant.
8571   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8572   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8573   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8574     return 0;
8575   uint64_t Len = LenC->getZExtValue();
8576   Alignment = MI->getAlignment()->getZExtValue();
8577   
8578   // If the length is zero, this is a no-op
8579   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8580   
8581   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8582   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8583     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
8584     
8585     Value *Dest = MI->getDest();
8586     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8587
8588     // Alignment 0 is identity for alignment 1 for memset, but not store.
8589     if (Alignment == 0) Alignment = 1;
8590     
8591     // Extract the fill value and store.
8592     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8593     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8594                                       Alignment), *MI);
8595     
8596     // Set the size of the copy to 0, it will be deleted on the next iteration.
8597     MI->setLength(Constant::getNullValue(LenC->getType()));
8598     return MI;
8599   }
8600
8601   return 0;
8602 }
8603
8604
8605 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8606 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8607 /// the heavy lifting.
8608 ///
8609 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8610   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8611   if (!II) return visitCallSite(&CI);
8612   
8613   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8614   // visitCallSite.
8615   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8616     bool Changed = false;
8617
8618     // memmove/cpy/set of zero bytes is a noop.
8619     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8620       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8621
8622       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8623         if (CI->getZExtValue() == 1) {
8624           // Replace the instruction with just byte operations.  We would
8625           // transform other cases to loads/stores, but we don't know if
8626           // alignment is sufficient.
8627         }
8628     }
8629
8630     // If we have a memmove and the source operation is a constant global,
8631     // then the source and dest pointers can't alias, so we can change this
8632     // into a call to memcpy.
8633     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8634       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8635         if (GVSrc->isConstant()) {
8636           Module *M = CI.getParent()->getParent()->getParent();
8637           Intrinsic::ID MemCpyID;
8638           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8639             MemCpyID = Intrinsic::memcpy_i32;
8640           else
8641             MemCpyID = Intrinsic::memcpy_i64;
8642           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8643           Changed = true;
8644         }
8645
8646       // memmove(x,x,size) -> noop.
8647       if (MMI->getSource() == MMI->getDest())
8648         return EraseInstFromFunction(CI);
8649     }
8650
8651     // If we can determine a pointer alignment that is bigger than currently
8652     // set, update the alignment.
8653     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8654       if (Instruction *I = SimplifyMemTransfer(MI))
8655         return I;
8656     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8657       if (Instruction *I = SimplifyMemSet(MSI))
8658         return I;
8659     }
8660           
8661     if (Changed) return II;
8662   }
8663   
8664   switch (II->getIntrinsicID()) {
8665   default: break;
8666   case Intrinsic::bswap:
8667     // bswap(bswap(x)) -> x
8668     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8669       if (Operand->getIntrinsicID() == Intrinsic::bswap)
8670         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8671     break;
8672   case Intrinsic::ppc_altivec_lvx:
8673   case Intrinsic::ppc_altivec_lvxl:
8674   case Intrinsic::x86_sse_loadu_ps:
8675   case Intrinsic::x86_sse2_loadu_pd:
8676   case Intrinsic::x86_sse2_loadu_dq:
8677     // Turn PPC lvx     -> load if the pointer is known aligned.
8678     // Turn X86 loadups -> load if the pointer is known aligned.
8679     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8680       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8681                                        PointerType::getUnqual(II->getType()),
8682                                        CI);
8683       return new LoadInst(Ptr);
8684     }
8685     break;
8686   case Intrinsic::ppc_altivec_stvx:
8687   case Intrinsic::ppc_altivec_stvxl:
8688     // Turn stvx -> store if the pointer is known aligned.
8689     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8690       const Type *OpPtrTy = 
8691         PointerType::getUnqual(II->getOperand(1)->getType());
8692       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8693       return new StoreInst(II->getOperand(1), Ptr);
8694     }
8695     break;
8696   case Intrinsic::x86_sse_storeu_ps:
8697   case Intrinsic::x86_sse2_storeu_pd:
8698   case Intrinsic::x86_sse2_storeu_dq:
8699     // Turn X86 storeu -> store if the pointer is known aligned.
8700     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8701       const Type *OpPtrTy = 
8702         PointerType::getUnqual(II->getOperand(2)->getType());
8703       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8704       return new StoreInst(II->getOperand(2), Ptr);
8705     }
8706     break;
8707     
8708   case Intrinsic::x86_sse_cvttss2si: {
8709     // These intrinsics only demands the 0th element of its input vector.  If
8710     // we can simplify the input based on that, do so now.
8711     uint64_t UndefElts;
8712     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8713                                               UndefElts)) {
8714       II->setOperand(1, V);
8715       return II;
8716     }
8717     break;
8718   }
8719     
8720   case Intrinsic::ppc_altivec_vperm:
8721     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8722     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8723       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8724       
8725       // Check that all of the elements are integer constants or undefs.
8726       bool AllEltsOk = true;
8727       for (unsigned i = 0; i != 16; ++i) {
8728         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8729             !isa<UndefValue>(Mask->getOperand(i))) {
8730           AllEltsOk = false;
8731           break;
8732         }
8733       }
8734       
8735       if (AllEltsOk) {
8736         // Cast the input vectors to byte vectors.
8737         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8738         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8739         Value *Result = UndefValue::get(Op0->getType());
8740         
8741         // Only extract each element once.
8742         Value *ExtractedElts[32];
8743         memset(ExtractedElts, 0, sizeof(ExtractedElts));
8744         
8745         for (unsigned i = 0; i != 16; ++i) {
8746           if (isa<UndefValue>(Mask->getOperand(i)))
8747             continue;
8748           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8749           Idx &= 31;  // Match the hardware behavior.
8750           
8751           if (ExtractedElts[Idx] == 0) {
8752             Instruction *Elt = 
8753               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8754             InsertNewInstBefore(Elt, CI);
8755             ExtractedElts[Idx] = Elt;
8756           }
8757         
8758           // Insert this value into the result vector.
8759           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8760                                              i, "tmp");
8761           InsertNewInstBefore(cast<Instruction>(Result), CI);
8762         }
8763         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8764       }
8765     }
8766     break;
8767
8768   case Intrinsic::stackrestore: {
8769     // If the save is right next to the restore, remove the restore.  This can
8770     // happen when variable allocas are DCE'd.
8771     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8772       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8773         BasicBlock::iterator BI = SS;
8774         if (&*++BI == II)
8775           return EraseInstFromFunction(CI);
8776       }
8777     }
8778     
8779     // Scan down this block to see if there is another stack restore in the
8780     // same block without an intervening call/alloca.
8781     BasicBlock::iterator BI = II;
8782     TerminatorInst *TI = II->getParent()->getTerminator();
8783     bool CannotRemove = false;
8784     for (++BI; &*BI != TI; ++BI) {
8785       if (isa<AllocaInst>(BI)) {
8786         CannotRemove = true;
8787         break;
8788       }
8789       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8790         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8791           // If there is a stackrestore below this one, remove this one.
8792           if (II->getIntrinsicID() == Intrinsic::stackrestore)
8793             return EraseInstFromFunction(CI);
8794           // Otherwise, ignore the intrinsic.
8795         } else {
8796           // If we found a non-intrinsic call, we can't remove the stack
8797           // restore.
8798           CannotRemove = true;
8799           break;
8800         }
8801       }
8802     }
8803     
8804     // If the stack restore is in a return/unwind block and if there are no
8805     // allocas or calls between the restore and the return, nuke the restore.
8806     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8807       return EraseInstFromFunction(CI);
8808     break;
8809   }
8810   }
8811
8812   return visitCallSite(II);
8813 }
8814
8815 // InvokeInst simplification
8816 //
8817 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8818   return visitCallSite(&II);
8819 }
8820
8821 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
8822 /// passed through the varargs area, we can eliminate the use of the cast.
8823 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8824                                          const CastInst * const CI,
8825                                          const TargetData * const TD,
8826                                          const int ix) {
8827   if (!CI->isLosslessCast())
8828     return false;
8829
8830   // The size of ByVal arguments is derived from the type, so we
8831   // can't change to a type with a different size.  If the size were
8832   // passed explicitly we could avoid this check.
8833   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8834     return true;
8835
8836   const Type* SrcTy = 
8837             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8838   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8839   if (!SrcTy->isSized() || !DstTy->isSized())
8840     return false;
8841   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8842     return false;
8843   return true;
8844 }
8845
8846 // visitCallSite - Improvements for call and invoke instructions.
8847 //
8848 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8849   bool Changed = false;
8850
8851   // If the callee is a constexpr cast of a function, attempt to move the cast
8852   // to the arguments of the call/invoke.
8853   if (transformConstExprCastCall(CS)) return 0;
8854
8855   Value *Callee = CS.getCalledValue();
8856
8857   if (Function *CalleeF = dyn_cast<Function>(Callee))
8858     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8859       Instruction *OldCall = CS.getInstruction();
8860       // If the call and callee calling conventions don't match, this call must
8861       // be unreachable, as the call is undefined.
8862       new StoreInst(ConstantInt::getTrue(),
8863                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8864                                     OldCall);
8865       if (!OldCall->use_empty())
8866         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8867       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8868         return EraseInstFromFunction(*OldCall);
8869       return 0;
8870     }
8871
8872   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8873     // This instruction is not reachable, just remove it.  We insert a store to
8874     // undef so that we know that this code is not reachable, despite the fact
8875     // that we can't modify the CFG here.
8876     new StoreInst(ConstantInt::getTrue(),
8877                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8878                   CS.getInstruction());
8879
8880     if (!CS.getInstruction()->use_empty())
8881       CS.getInstruction()->
8882         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8883
8884     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8885       // Don't break the CFG, insert a dummy cond branch.
8886       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8887                          ConstantInt::getTrue(), II);
8888     }
8889     return EraseInstFromFunction(*CS.getInstruction());
8890   }
8891
8892   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8893     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8894       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8895         return transformCallThroughTrampoline(CS);
8896
8897   const PointerType *PTy = cast<PointerType>(Callee->getType());
8898   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8899   if (FTy->isVarArg()) {
8900     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8901     // See if we can optimize any arguments passed through the varargs area of
8902     // the call.
8903     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8904            E = CS.arg_end(); I != E; ++I, ++ix) {
8905       CastInst *CI = dyn_cast<CastInst>(*I);
8906       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8907         *I = CI->getOperand(0);
8908         Changed = true;
8909       }
8910     }
8911   }
8912
8913   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8914     // Inline asm calls cannot throw - mark them 'nounwind'.
8915     CS.setDoesNotThrow();
8916     Changed = true;
8917   }
8918
8919   return Changed ? CS.getInstruction() : 0;
8920 }
8921
8922 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8923 // attempt to move the cast to the arguments of the call/invoke.
8924 //
8925 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8926   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8927   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8928   if (CE->getOpcode() != Instruction::BitCast || 
8929       !isa<Function>(CE->getOperand(0)))
8930     return false;
8931   Function *Callee = cast<Function>(CE->getOperand(0));
8932   Instruction *Caller = CS.getInstruction();
8933   const PAListPtr &CallerPAL = CS.getParamAttrs();
8934
8935   // Okay, this is a cast from a function to a different type.  Unless doing so
8936   // would cause a type conversion of one of our arguments, change this call to
8937   // be a direct call with arguments casted to the appropriate types.
8938   //
8939   const FunctionType *FT = Callee->getFunctionType();
8940   const Type *OldRetTy = Caller->getType();
8941   const Type *NewRetTy = FT->getReturnType();
8942
8943   if (isa<StructType>(NewRetTy))
8944     return false; // TODO: Handle multiple return values.
8945
8946   // Check to see if we are changing the return type...
8947   if (OldRetTy != NewRetTy) {
8948     if (Callee->isDeclaration() &&
8949         // Conversion is ok if changing from one pointer type to another or from
8950         // a pointer to an integer of the same size.
8951         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8952           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
8953       return false;   // Cannot transform this return value.
8954
8955     if (!Caller->use_empty() &&
8956         // void -> non-void is handled specially
8957         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8958       return false;   // Cannot transform this return value.
8959
8960     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8961       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8962       if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8963         return false;   // Attribute not compatible with transformed value.
8964     }
8965
8966     // If the callsite is an invoke instruction, and the return value is used by
8967     // a PHI node in a successor, we cannot change the return type of the call
8968     // because there is no place to put the cast instruction (without breaking
8969     // the critical edge).  Bail out in this case.
8970     if (!Caller->use_empty())
8971       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8972         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8973              UI != E; ++UI)
8974           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8975             if (PN->getParent() == II->getNormalDest() ||
8976                 PN->getParent() == II->getUnwindDest())
8977               return false;
8978   }
8979
8980   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8981   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8982
8983   CallSite::arg_iterator AI = CS.arg_begin();
8984   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8985     const Type *ParamTy = FT->getParamType(i);
8986     const Type *ActTy = (*AI)->getType();
8987
8988     if (!CastInst::isCastable(ActTy, ParamTy))
8989       return false;   // Cannot transform this parameter value.
8990
8991     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8992       return false;   // Attribute not compatible with transformed value.
8993
8994     // Converting from one pointer type to another or between a pointer and an
8995     // integer of the same size is safe even if we do not have a body.
8996     bool isConvertible = ActTy == ParamTy ||
8997       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8998        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8999     if (Callee->isDeclaration() && !isConvertible) return false;
9000   }
9001
9002   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9003       Callee->isDeclaration())
9004     return false;   // Do not delete arguments unless we have a function body.
9005
9006   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9007       !CallerPAL.isEmpty())
9008     // In this case we have more arguments than the new function type, but we
9009     // won't be dropping them.  Check that these extra arguments have attributes
9010     // that are compatible with being a vararg call argument.
9011     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9012       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9013         break;
9014       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9015       if (PAttrs & ParamAttr::VarArgsIncompatible)
9016         return false;
9017     }
9018
9019   // Okay, we decided that this is a safe thing to do: go ahead and start
9020   // inserting cast instructions as necessary...
9021   std::vector<Value*> Args;
9022   Args.reserve(NumActualArgs);
9023   SmallVector<ParamAttrsWithIndex, 8> attrVec;
9024   attrVec.reserve(NumCommonArgs);
9025
9026   // Get any return attributes.
9027   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9028
9029   // If the return value is not being used, the type may not be compatible
9030   // with the existing attributes.  Wipe out any problematic attributes.
9031   RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
9032
9033   // Add the new return attributes.
9034   if (RAttrs)
9035     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
9036
9037   AI = CS.arg_begin();
9038   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9039     const Type *ParamTy = FT->getParamType(i);
9040     if ((*AI)->getType() == ParamTy) {
9041       Args.push_back(*AI);
9042     } else {
9043       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9044           false, ParamTy, false);
9045       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9046       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9047     }
9048
9049     // Add any parameter attributes.
9050     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9051       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9052   }
9053
9054   // If the function takes more arguments than the call was taking, add them
9055   // now...
9056   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9057     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9058
9059   // If we are removing arguments to the function, emit an obnoxious warning...
9060   if (FT->getNumParams() < NumActualArgs) {
9061     if (!FT->isVarArg()) {
9062       cerr << "WARNING: While resolving call to function '"
9063            << Callee->getName() << "' arguments were dropped!\n";
9064     } else {
9065       // Add all of the arguments in their promoted form to the arg list...
9066       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9067         const Type *PTy = getPromotedType((*AI)->getType());
9068         if (PTy != (*AI)->getType()) {
9069           // Must promote to pass through va_arg area!
9070           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9071                                                                 PTy, false);
9072           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9073           InsertNewInstBefore(Cast, *Caller);
9074           Args.push_back(Cast);
9075         } else {
9076           Args.push_back(*AI);
9077         }
9078
9079         // Add any parameter attributes.
9080         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9081           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9082       }
9083     }
9084   }
9085
9086   if (NewRetTy == Type::VoidTy)
9087     Caller->setName("");   // Void type should not have a name.
9088
9089   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9090
9091   Instruction *NC;
9092   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9093     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9094                             Args.begin(), Args.end(),
9095                             Caller->getName(), Caller);
9096     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9097     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9098   } else {
9099     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9100                           Caller->getName(), Caller);
9101     CallInst *CI = cast<CallInst>(Caller);
9102     if (CI->isTailCall())
9103       cast<CallInst>(NC)->setTailCall();
9104     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9105     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9106   }
9107
9108   // Insert a cast of the return type as necessary.
9109   Value *NV = NC;
9110   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9111     if (NV->getType() != Type::VoidTy) {
9112       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9113                                                             OldRetTy, false);
9114       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9115
9116       // If this is an invoke instruction, we should insert it after the first
9117       // non-phi, instruction in the normal successor block.
9118       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9119         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9120         InsertNewInstBefore(NC, *I);
9121       } else {
9122         // Otherwise, it's a call, just insert cast right after the call instr
9123         InsertNewInstBefore(NC, *Caller);
9124       }
9125       AddUsersToWorkList(*Caller);
9126     } else {
9127       NV = UndefValue::get(Caller->getType());
9128     }
9129   }
9130
9131   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9132     Caller->replaceAllUsesWith(NV);
9133   Caller->eraseFromParent();
9134   RemoveFromWorkList(Caller);
9135   return true;
9136 }
9137
9138 // transformCallThroughTrampoline - Turn a call to a function created by the
9139 // init_trampoline intrinsic into a direct call to the underlying function.
9140 //
9141 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9142   Value *Callee = CS.getCalledValue();
9143   const PointerType *PTy = cast<PointerType>(Callee->getType());
9144   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9145   const PAListPtr &Attrs = CS.getParamAttrs();
9146
9147   // If the call already has the 'nest' attribute somewhere then give up -
9148   // otherwise 'nest' would occur twice after splicing in the chain.
9149   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9150     return 0;
9151
9152   IntrinsicInst *Tramp =
9153     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9154
9155   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9156   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9157   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9158
9159   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9160   if (!NestAttrs.isEmpty()) {
9161     unsigned NestIdx = 1;
9162     const Type *NestTy = 0;
9163     ParameterAttributes NestAttr = ParamAttr::None;
9164
9165     // Look for a parameter marked with the 'nest' attribute.
9166     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9167          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9168       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9169         // Record the parameter type and any other attributes.
9170         NestTy = *I;
9171         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9172         break;
9173       }
9174
9175     if (NestTy) {
9176       Instruction *Caller = CS.getInstruction();
9177       std::vector<Value*> NewArgs;
9178       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9179
9180       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9181       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9182
9183       // Insert the nest argument into the call argument list, which may
9184       // mean appending it.  Likewise for attributes.
9185
9186       // Add any function result attributes.
9187       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9188         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9189
9190       {
9191         unsigned Idx = 1;
9192         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9193         do {
9194           if (Idx == NestIdx) {
9195             // Add the chain argument and attributes.
9196             Value *NestVal = Tramp->getOperand(3);
9197             if (NestVal->getType() != NestTy)
9198               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9199             NewArgs.push_back(NestVal);
9200             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9201           }
9202
9203           if (I == E)
9204             break;
9205
9206           // Add the original argument and attributes.
9207           NewArgs.push_back(*I);
9208           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9209             NewAttrs.push_back
9210               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9211
9212           ++Idx, ++I;
9213         } while (1);
9214       }
9215
9216       // The trampoline may have been bitcast to a bogus type (FTy).
9217       // Handle this by synthesizing a new function type, equal to FTy
9218       // with the chain parameter inserted.
9219
9220       std::vector<const Type*> NewTypes;
9221       NewTypes.reserve(FTy->getNumParams()+1);
9222
9223       // Insert the chain's type into the list of parameter types, which may
9224       // mean appending it.
9225       {
9226         unsigned Idx = 1;
9227         FunctionType::param_iterator I = FTy->param_begin(),
9228           E = FTy->param_end();
9229
9230         do {
9231           if (Idx == NestIdx)
9232             // Add the chain's type.
9233             NewTypes.push_back(NestTy);
9234
9235           if (I == E)
9236             break;
9237
9238           // Add the original type.
9239           NewTypes.push_back(*I);
9240
9241           ++Idx, ++I;
9242         } while (1);
9243       }
9244
9245       // Replace the trampoline call with a direct call.  Let the generic
9246       // code sort out any function type mismatches.
9247       FunctionType *NewFTy =
9248         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9249       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9250         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9251       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9252
9253       Instruction *NewCaller;
9254       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9255         NewCaller = InvokeInst::Create(NewCallee,
9256                                        II->getNormalDest(), II->getUnwindDest(),
9257                                        NewArgs.begin(), NewArgs.end(),
9258                                        Caller->getName(), Caller);
9259         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9260         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9261       } else {
9262         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9263                                      Caller->getName(), Caller);
9264         if (cast<CallInst>(Caller)->isTailCall())
9265           cast<CallInst>(NewCaller)->setTailCall();
9266         cast<CallInst>(NewCaller)->
9267           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9268         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9269       }
9270       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9271         Caller->replaceAllUsesWith(NewCaller);
9272       Caller->eraseFromParent();
9273       RemoveFromWorkList(Caller);
9274       return 0;
9275     }
9276   }
9277
9278   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9279   // parameter, there is no need to adjust the argument list.  Let the generic
9280   // code sort out any function type mismatches.
9281   Constant *NewCallee =
9282     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9283   CS.setCalledFunction(NewCallee);
9284   return CS.getInstruction();
9285 }
9286
9287 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9288 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9289 /// and a single binop.
9290 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9291   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9292   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9293          isa<CmpInst>(FirstInst));
9294   unsigned Opc = FirstInst->getOpcode();
9295   Value *LHSVal = FirstInst->getOperand(0);
9296   Value *RHSVal = FirstInst->getOperand(1);
9297     
9298   const Type *LHSType = LHSVal->getType();
9299   const Type *RHSType = RHSVal->getType();
9300   
9301   // Scan to see if all operands are the same opcode, all have one use, and all
9302   // kill their operands (i.e. the operands have one use).
9303   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9304     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9305     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9306         // Verify type of the LHS matches so we don't fold cmp's of different
9307         // types or GEP's with different index types.
9308         I->getOperand(0)->getType() != LHSType ||
9309         I->getOperand(1)->getType() != RHSType)
9310       return 0;
9311
9312     // If they are CmpInst instructions, check their predicates
9313     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9314       if (cast<CmpInst>(I)->getPredicate() !=
9315           cast<CmpInst>(FirstInst)->getPredicate())
9316         return 0;
9317     
9318     // Keep track of which operand needs a phi node.
9319     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9320     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9321   }
9322   
9323   // Otherwise, this is safe to transform, determine if it is profitable.
9324
9325   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9326   // Indexes are often folded into load/store instructions, so we don't want to
9327   // hide them behind a phi.
9328   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9329     return 0;
9330   
9331   Value *InLHS = FirstInst->getOperand(0);
9332   Value *InRHS = FirstInst->getOperand(1);
9333   PHINode *NewLHS = 0, *NewRHS = 0;
9334   if (LHSVal == 0) {
9335     NewLHS = PHINode::Create(LHSType,
9336                              FirstInst->getOperand(0)->getName() + ".pn");
9337     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9338     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9339     InsertNewInstBefore(NewLHS, PN);
9340     LHSVal = NewLHS;
9341   }
9342   
9343   if (RHSVal == 0) {
9344     NewRHS = PHINode::Create(RHSType,
9345                              FirstInst->getOperand(1)->getName() + ".pn");
9346     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9347     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9348     InsertNewInstBefore(NewRHS, PN);
9349     RHSVal = NewRHS;
9350   }
9351   
9352   // Add all operands to the new PHIs.
9353   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9354     if (NewLHS) {
9355       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9356       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9357     }
9358     if (NewRHS) {
9359       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9360       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9361     }
9362   }
9363     
9364   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9365     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9366   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9367     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9368                            RHSVal);
9369   else {
9370     assert(isa<GetElementPtrInst>(FirstInst));
9371     return GetElementPtrInst::Create(LHSVal, RHSVal);
9372   }
9373 }
9374
9375 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9376 /// of the block that defines it.  This means that it must be obvious the value
9377 /// of the load is not changed from the point of the load to the end of the
9378 /// block it is in.
9379 ///
9380 /// Finally, it is safe, but not profitable, to sink a load targetting a
9381 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9382 /// to a register.
9383 static bool isSafeToSinkLoad(LoadInst *L) {
9384   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9385   
9386   for (++BBI; BBI != E; ++BBI)
9387     if (BBI->mayWriteToMemory())
9388       return false;
9389   
9390   // Check for non-address taken alloca.  If not address-taken already, it isn't
9391   // profitable to do this xform.
9392   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9393     bool isAddressTaken = false;
9394     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9395          UI != E; ++UI) {
9396       if (isa<LoadInst>(UI)) continue;
9397       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9398         // If storing TO the alloca, then the address isn't taken.
9399         if (SI->getOperand(1) == AI) continue;
9400       }
9401       isAddressTaken = true;
9402       break;
9403     }
9404     
9405     if (!isAddressTaken)
9406       return false;
9407   }
9408   
9409   return true;
9410 }
9411
9412
9413 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9414 // operator and they all are only used by the PHI, PHI together their
9415 // inputs, and do the operation once, to the result of the PHI.
9416 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9417   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9418
9419   // Scan the instruction, looking for input operations that can be folded away.
9420   // If all input operands to the phi are the same instruction (e.g. a cast from
9421   // the same type or "+42") we can pull the operation through the PHI, reducing
9422   // code size and simplifying code.
9423   Constant *ConstantOp = 0;
9424   const Type *CastSrcTy = 0;
9425   bool isVolatile = false;
9426   if (isa<CastInst>(FirstInst)) {
9427     CastSrcTy = FirstInst->getOperand(0)->getType();
9428   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9429     // Can fold binop, compare or shift here if the RHS is a constant, 
9430     // otherwise call FoldPHIArgBinOpIntoPHI.
9431     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9432     if (ConstantOp == 0)
9433       return FoldPHIArgBinOpIntoPHI(PN);
9434   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9435     isVolatile = LI->isVolatile();
9436     // We can't sink the load if the loaded value could be modified between the
9437     // load and the PHI.
9438     if (LI->getParent() != PN.getIncomingBlock(0) ||
9439         !isSafeToSinkLoad(LI))
9440       return 0;
9441     
9442     // If the PHI is of volatile loads and the load block has multiple
9443     // successors, sinking it would remove a load of the volatile value from
9444     // the path through the other successor.
9445     if (isVolatile &&
9446         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9447       return 0;
9448     
9449   } else if (isa<GetElementPtrInst>(FirstInst)) {
9450     if (FirstInst->getNumOperands() == 2)
9451       return FoldPHIArgBinOpIntoPHI(PN);
9452     // Can't handle general GEPs yet.
9453     return 0;
9454   } else {
9455     return 0;  // Cannot fold this operation.
9456   }
9457
9458   // Check to see if all arguments are the same operation.
9459   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9460     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9461     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9462     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9463       return 0;
9464     if (CastSrcTy) {
9465       if (I->getOperand(0)->getType() != CastSrcTy)
9466         return 0;  // Cast operation must match.
9467     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9468       // We can't sink the load if the loaded value could be modified between 
9469       // the load and the PHI.
9470       if (LI->isVolatile() != isVolatile ||
9471           LI->getParent() != PN.getIncomingBlock(i) ||
9472           !isSafeToSinkLoad(LI))
9473         return 0;
9474       
9475       // If the PHI is of volatile loads and the load block has multiple
9476       // successors, sinking it would remove a load of the volatile value from
9477       // the path through the other successor.
9478       if (isVolatile &&
9479           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9480         return 0;
9481
9482       
9483     } else if (I->getOperand(1) != ConstantOp) {
9484       return 0;
9485     }
9486   }
9487
9488   // Okay, they are all the same operation.  Create a new PHI node of the
9489   // correct type, and PHI together all of the LHS's of the instructions.
9490   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9491                                    PN.getName()+".in");
9492   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9493
9494   Value *InVal = FirstInst->getOperand(0);
9495   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9496
9497   // Add all operands to the new PHI.
9498   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9499     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9500     if (NewInVal != InVal)
9501       InVal = 0;
9502     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9503   }
9504
9505   Value *PhiVal;
9506   if (InVal) {
9507     // The new PHI unions all of the same values together.  This is really
9508     // common, so we handle it intelligently here for compile-time speed.
9509     PhiVal = InVal;
9510     delete NewPN;
9511   } else {
9512     InsertNewInstBefore(NewPN, PN);
9513     PhiVal = NewPN;
9514   }
9515
9516   // Insert and return the new operation.
9517   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9518     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9519   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9520     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9521   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9522     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9523                            PhiVal, ConstantOp);
9524   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9525   
9526   // If this was a volatile load that we are merging, make sure to loop through
9527   // and mark all the input loads as non-volatile.  If we don't do this, we will
9528   // insert a new volatile load and the old ones will not be deletable.
9529   if (isVolatile)
9530     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9531       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9532   
9533   return new LoadInst(PhiVal, "", isVolatile);
9534 }
9535
9536 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9537 /// that is dead.
9538 static bool DeadPHICycle(PHINode *PN,
9539                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9540   if (PN->use_empty()) return true;
9541   if (!PN->hasOneUse()) return false;
9542
9543   // Remember this node, and if we find the cycle, return.
9544   if (!PotentiallyDeadPHIs.insert(PN))
9545     return true;
9546   
9547   // Don't scan crazily complex things.
9548   if (PotentiallyDeadPHIs.size() == 16)
9549     return false;
9550
9551   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9552     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9553
9554   return false;
9555 }
9556
9557 /// PHIsEqualValue - Return true if this phi node is always equal to
9558 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9559 ///   z = some value; x = phi (y, z); y = phi (x, z)
9560 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9561                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9562   // See if we already saw this PHI node.
9563   if (!ValueEqualPHIs.insert(PN))
9564     return true;
9565   
9566   // Don't scan crazily complex things.
9567   if (ValueEqualPHIs.size() == 16)
9568     return false;
9569  
9570   // Scan the operands to see if they are either phi nodes or are equal to
9571   // the value.
9572   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9573     Value *Op = PN->getIncomingValue(i);
9574     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9575       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9576         return false;
9577     } else if (Op != NonPhiInVal)
9578       return false;
9579   }
9580   
9581   return true;
9582 }
9583
9584
9585 // PHINode simplification
9586 //
9587 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9588   // If LCSSA is around, don't mess with Phi nodes
9589   if (MustPreserveLCSSA) return 0;
9590   
9591   if (Value *V = PN.hasConstantValue())
9592     return ReplaceInstUsesWith(PN, V);
9593
9594   // If all PHI operands are the same operation, pull them through the PHI,
9595   // reducing code size.
9596   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9597       PN.getIncomingValue(0)->hasOneUse())
9598     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9599       return Result;
9600
9601   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9602   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9603   // PHI)... break the cycle.
9604   if (PN.hasOneUse()) {
9605     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9606     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9607       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9608       PotentiallyDeadPHIs.insert(&PN);
9609       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9610         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9611     }
9612    
9613     // If this phi has a single use, and if that use just computes a value for
9614     // the next iteration of a loop, delete the phi.  This occurs with unused
9615     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9616     // common case here is good because the only other things that catch this
9617     // are induction variable analysis (sometimes) and ADCE, which is only run
9618     // late.
9619     if (PHIUser->hasOneUse() &&
9620         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9621         PHIUser->use_back() == &PN) {
9622       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9623     }
9624   }
9625
9626   // We sometimes end up with phi cycles that non-obviously end up being the
9627   // same value, for example:
9628   //   z = some value; x = phi (y, z); y = phi (x, z)
9629   // where the phi nodes don't necessarily need to be in the same block.  Do a
9630   // quick check to see if the PHI node only contains a single non-phi value, if
9631   // so, scan to see if the phi cycle is actually equal to that value.
9632   {
9633     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9634     // Scan for the first non-phi operand.
9635     while (InValNo != NumOperandVals && 
9636            isa<PHINode>(PN.getIncomingValue(InValNo)))
9637       ++InValNo;
9638
9639     if (InValNo != NumOperandVals) {
9640       Value *NonPhiInVal = PN.getOperand(InValNo);
9641       
9642       // Scan the rest of the operands to see if there are any conflicts, if so
9643       // there is no need to recursively scan other phis.
9644       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9645         Value *OpVal = PN.getIncomingValue(InValNo);
9646         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9647           break;
9648       }
9649       
9650       // If we scanned over all operands, then we have one unique value plus
9651       // phi values.  Scan PHI nodes to see if they all merge in each other or
9652       // the value.
9653       if (InValNo == NumOperandVals) {
9654         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9655         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9656           return ReplaceInstUsesWith(PN, NonPhiInVal);
9657       }
9658     }
9659   }
9660   return 0;
9661 }
9662
9663 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9664                                    Instruction *InsertPoint,
9665                                    InstCombiner *IC) {
9666   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9667   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9668   // We must cast correctly to the pointer type. Ensure that we
9669   // sign extend the integer value if it is smaller as this is
9670   // used for address computation.
9671   Instruction::CastOps opcode = 
9672      (VTySize < PtrSize ? Instruction::SExt :
9673       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9674   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9675 }
9676
9677
9678 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9679   Value *PtrOp = GEP.getOperand(0);
9680   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9681   // If so, eliminate the noop.
9682   if (GEP.getNumOperands() == 1)
9683     return ReplaceInstUsesWith(GEP, PtrOp);
9684
9685   if (isa<UndefValue>(GEP.getOperand(0)))
9686     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9687
9688   bool HasZeroPointerIndex = false;
9689   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9690     HasZeroPointerIndex = C->isNullValue();
9691
9692   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9693     return ReplaceInstUsesWith(GEP, PtrOp);
9694
9695   // Eliminate unneeded casts for indices.
9696   bool MadeChange = false;
9697   
9698   gep_type_iterator GTI = gep_type_begin(GEP);
9699   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9700        i != e; ++i, ++GTI) {
9701     if (isa<SequentialType>(*GTI)) {
9702       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9703         if (CI->getOpcode() == Instruction::ZExt ||
9704             CI->getOpcode() == Instruction::SExt) {
9705           const Type *SrcTy = CI->getOperand(0)->getType();
9706           // We can eliminate a cast from i32 to i64 iff the target 
9707           // is a 32-bit pointer target.
9708           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9709             MadeChange = true;
9710             *i = CI->getOperand(0);
9711           }
9712         }
9713       }
9714       // If we are using a wider index than needed for this platform, shrink it
9715       // to what we need.  If the incoming value needs a cast instruction,
9716       // insert it.  This explicit cast can make subsequent optimizations more
9717       // obvious.
9718       Value *Op = *i;
9719       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9720         if (Constant *C = dyn_cast<Constant>(Op)) {
9721           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9722           MadeChange = true;
9723         } else {
9724           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9725                                 GEP);
9726           *i = Op;
9727           MadeChange = true;
9728         }
9729       }
9730     }
9731   }
9732   if (MadeChange) return &GEP;
9733
9734   // If this GEP instruction doesn't move the pointer, and if the input operand
9735   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9736   // real input to the dest type.
9737   if (GEP.hasAllZeroIndices()) {
9738     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9739       // If the bitcast is of an allocation, and the allocation will be
9740       // converted to match the type of the cast, don't touch this.
9741       if (isa<AllocationInst>(BCI->getOperand(0))) {
9742         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9743         if (Instruction *I = visitBitCast(*BCI)) {
9744           if (I != BCI) {
9745             I->takeName(BCI);
9746             BCI->getParent()->getInstList().insert(BCI, I);
9747             ReplaceInstUsesWith(*BCI, I);
9748           }
9749           return &GEP;
9750         }
9751       }
9752       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9753     }
9754   }
9755   
9756   // Combine Indices - If the source pointer to this getelementptr instruction
9757   // is a getelementptr instruction, combine the indices of the two
9758   // getelementptr instructions into a single instruction.
9759   //
9760   SmallVector<Value*, 8> SrcGEPOperands;
9761   if (User *Src = dyn_castGetElementPtr(PtrOp))
9762     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9763
9764   if (!SrcGEPOperands.empty()) {
9765     // Note that if our source is a gep chain itself that we wait for that
9766     // chain to be resolved before we perform this transformation.  This
9767     // avoids us creating a TON of code in some cases.
9768     //
9769     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9770         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9771       return 0;   // Wait until our source is folded to completion.
9772
9773     SmallVector<Value*, 8> Indices;
9774
9775     // Find out whether the last index in the source GEP is a sequential idx.
9776     bool EndsWithSequential = false;
9777     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9778            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9779       EndsWithSequential = !isa<StructType>(*I);
9780
9781     // Can we combine the two pointer arithmetics offsets?
9782     if (EndsWithSequential) {
9783       // Replace: gep (gep %P, long B), long A, ...
9784       // With:    T = long A+B; gep %P, T, ...
9785       //
9786       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9787       if (SO1 == Constant::getNullValue(SO1->getType())) {
9788         Sum = GO1;
9789       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9790         Sum = SO1;
9791       } else {
9792         // If they aren't the same type, convert both to an integer of the
9793         // target's pointer size.
9794         if (SO1->getType() != GO1->getType()) {
9795           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9796             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9797           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9798             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9799           } else {
9800             unsigned PS = TD->getPointerSizeInBits();
9801             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9802               // Convert GO1 to SO1's type.
9803               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9804
9805             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9806               // Convert SO1 to GO1's type.
9807               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9808             } else {
9809               const Type *PT = TD->getIntPtrType();
9810               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9811               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9812             }
9813           }
9814         }
9815         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9816           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9817         else {
9818           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9819           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9820         }
9821       }
9822
9823       // Recycle the GEP we already have if possible.
9824       if (SrcGEPOperands.size() == 2) {
9825         GEP.setOperand(0, SrcGEPOperands[0]);
9826         GEP.setOperand(1, Sum);
9827         return &GEP;
9828       } else {
9829         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9830                        SrcGEPOperands.end()-1);
9831         Indices.push_back(Sum);
9832         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9833       }
9834     } else if (isa<Constant>(*GEP.idx_begin()) &&
9835                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9836                SrcGEPOperands.size() != 1) {
9837       // Otherwise we can do the fold if the first index of the GEP is a zero
9838       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9839                      SrcGEPOperands.end());
9840       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9841     }
9842
9843     if (!Indices.empty())
9844       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9845                                        Indices.end(), GEP.getName());
9846
9847   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9848     // GEP of global variable.  If all of the indices for this GEP are
9849     // constants, we can promote this to a constexpr instead of an instruction.
9850
9851     // Scan for nonconstants...
9852     SmallVector<Constant*, 8> Indices;
9853     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9854     for (; I != E && isa<Constant>(*I); ++I)
9855       Indices.push_back(cast<Constant>(*I));
9856
9857     if (I == E) {  // If they are all constants...
9858       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9859                                                     &Indices[0],Indices.size());
9860
9861       // Replace all uses of the GEP with the new constexpr...
9862       return ReplaceInstUsesWith(GEP, CE);
9863     }
9864   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9865     if (!isa<PointerType>(X->getType())) {
9866       // Not interesting.  Source pointer must be a cast from pointer.
9867     } else if (HasZeroPointerIndex) {
9868       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9869       // into     : GEP [10 x i8]* X, i32 0, ...
9870       //
9871       // This occurs when the program declares an array extern like "int X[];"
9872       //
9873       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9874       const PointerType *XTy = cast<PointerType>(X->getType());
9875       if (const ArrayType *XATy =
9876           dyn_cast<ArrayType>(XTy->getElementType()))
9877         if (const ArrayType *CATy =
9878             dyn_cast<ArrayType>(CPTy->getElementType()))
9879           if (CATy->getElementType() == XATy->getElementType()) {
9880             // At this point, we know that the cast source type is a pointer
9881             // to an array of the same type as the destination pointer
9882             // array.  Because the array type is never stepped over (there
9883             // is a leading zero) we can fold the cast into this GEP.
9884             GEP.setOperand(0, X);
9885             return &GEP;
9886           }
9887     } else if (GEP.getNumOperands() == 2) {
9888       // Transform things like:
9889       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9890       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9891       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9892       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9893       if (isa<ArrayType>(SrcElTy) &&
9894           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9895           TD->getABITypeSize(ResElTy)) {
9896         Value *Idx[2];
9897         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9898         Idx[1] = GEP.getOperand(1);
9899         Value *V = InsertNewInstBefore(
9900                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9901         // V and GEP are both pointer types --> BitCast
9902         return new BitCastInst(V, GEP.getType());
9903       }
9904       
9905       // Transform things like:
9906       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9907       //   (where tmp = 8*tmp2) into:
9908       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9909       
9910       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9911         uint64_t ArrayEltSize =
9912             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9913         
9914         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9915         // allow either a mul, shift, or constant here.
9916         Value *NewIdx = 0;
9917         ConstantInt *Scale = 0;
9918         if (ArrayEltSize == 1) {
9919           NewIdx = GEP.getOperand(1);
9920           Scale = ConstantInt::get(NewIdx->getType(), 1);
9921         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9922           NewIdx = ConstantInt::get(CI->getType(), 1);
9923           Scale = CI;
9924         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9925           if (Inst->getOpcode() == Instruction::Shl &&
9926               isa<ConstantInt>(Inst->getOperand(1))) {
9927             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9928             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9929             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9930             NewIdx = Inst->getOperand(0);
9931           } else if (Inst->getOpcode() == Instruction::Mul &&
9932                      isa<ConstantInt>(Inst->getOperand(1))) {
9933             Scale = cast<ConstantInt>(Inst->getOperand(1));
9934             NewIdx = Inst->getOperand(0);
9935           }
9936         }
9937         
9938         // If the index will be to exactly the right offset with the scale taken
9939         // out, perform the transformation. Note, we don't know whether Scale is
9940         // signed or not. We'll use unsigned version of division/modulo
9941         // operation after making sure Scale doesn't have the sign bit set.
9942         if (Scale && Scale->getSExtValue() >= 0LL &&
9943             Scale->getZExtValue() % ArrayEltSize == 0) {
9944           Scale = ConstantInt::get(Scale->getType(),
9945                                    Scale->getZExtValue() / ArrayEltSize);
9946           if (Scale->getZExtValue() != 1) {
9947             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9948                                                        false /*ZExt*/);
9949             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9950             NewIdx = InsertNewInstBefore(Sc, GEP);
9951           }
9952
9953           // Insert the new GEP instruction.
9954           Value *Idx[2];
9955           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9956           Idx[1] = NewIdx;
9957           Instruction *NewGEP =
9958             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9959           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9960           // The NewGEP must be pointer typed, so must the old one -> BitCast
9961           return new BitCastInst(NewGEP, GEP.getType());
9962         }
9963       }
9964     }
9965   }
9966
9967   return 0;
9968 }
9969
9970 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9971   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9972   if (AI.isArrayAllocation()) {  // Check C != 1
9973     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9974       const Type *NewTy = 
9975         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9976       AllocationInst *New = 0;
9977
9978       // Create and insert the replacement instruction...
9979       if (isa<MallocInst>(AI))
9980         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9981       else {
9982         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9983         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9984       }
9985
9986       InsertNewInstBefore(New, AI);
9987
9988       // Scan to the end of the allocation instructions, to skip over a block of
9989       // allocas if possible...
9990       //
9991       BasicBlock::iterator It = New;
9992       while (isa<AllocationInst>(*It)) ++It;
9993
9994       // Now that I is pointing to the first non-allocation-inst in the block,
9995       // insert our getelementptr instruction...
9996       //
9997       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9998       Value *Idx[2];
9999       Idx[0] = NullIdx;
10000       Idx[1] = NullIdx;
10001       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10002                                            New->getName()+".sub", It);
10003
10004       // Now make everything use the getelementptr instead of the original
10005       // allocation.
10006       return ReplaceInstUsesWith(AI, V);
10007     } else if (isa<UndefValue>(AI.getArraySize())) {
10008       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10009     }
10010   }
10011
10012   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10013   // Note that we only do this for alloca's, because malloc should allocate and
10014   // return a unique pointer, even for a zero byte allocation.
10015   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10016       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10017     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10018
10019   return 0;
10020 }
10021
10022 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10023   Value *Op = FI.getOperand(0);
10024
10025   // free undef -> unreachable.
10026   if (isa<UndefValue>(Op)) {
10027     // Insert a new store to null because we cannot modify the CFG here.
10028     new StoreInst(ConstantInt::getTrue(),
10029                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10030     return EraseInstFromFunction(FI);
10031   }
10032   
10033   // If we have 'free null' delete the instruction.  This can happen in stl code
10034   // when lots of inlining happens.
10035   if (isa<ConstantPointerNull>(Op))
10036     return EraseInstFromFunction(FI);
10037   
10038   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10039   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10040     FI.setOperand(0, CI->getOperand(0));
10041     return &FI;
10042   }
10043   
10044   // Change free (gep X, 0,0,0,0) into free(X)
10045   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10046     if (GEPI->hasAllZeroIndices()) {
10047       AddToWorkList(GEPI);
10048       FI.setOperand(0, GEPI->getOperand(0));
10049       return &FI;
10050     }
10051   }
10052   
10053   // Change free(malloc) into nothing, if the malloc has a single use.
10054   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10055     if (MI->hasOneUse()) {
10056       EraseInstFromFunction(FI);
10057       return EraseInstFromFunction(*MI);
10058     }
10059
10060   return 0;
10061 }
10062
10063
10064 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10065 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10066                                         const TargetData *TD) {
10067   User *CI = cast<User>(LI.getOperand(0));
10068   Value *CastOp = CI->getOperand(0);
10069
10070   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10071     // Instead of loading constant c string, use corresponding integer value
10072     // directly if string length is small enough.
10073     std::string Str;
10074     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10075       unsigned len = Str.length();
10076       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10077       unsigned numBits = Ty->getPrimitiveSizeInBits();
10078       // Replace LI with immediate integer store.
10079       if ((numBits >> 3) == len + 1) {
10080         APInt StrVal(numBits, 0);
10081         APInt SingleChar(numBits, 0);
10082         if (TD->isLittleEndian()) {
10083           for (signed i = len-1; i >= 0; i--) {
10084             SingleChar = (uint64_t) Str[i];
10085             StrVal = (StrVal << 8) | SingleChar;
10086           }
10087         } else {
10088           for (unsigned i = 0; i < len; i++) {
10089             SingleChar = (uint64_t) Str[i];
10090             StrVal = (StrVal << 8) | SingleChar;
10091           }
10092           // Append NULL at the end.
10093           SingleChar = 0;
10094           StrVal = (StrVal << 8) | SingleChar;
10095         }
10096         Value *NL = ConstantInt::get(StrVal);
10097         return IC.ReplaceInstUsesWith(LI, NL);
10098       }
10099     }
10100   }
10101
10102   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10103   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10104     const Type *SrcPTy = SrcTy->getElementType();
10105
10106     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10107          isa<VectorType>(DestPTy)) {
10108       // If the source is an array, the code below will not succeed.  Check to
10109       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10110       // constants.
10111       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10112         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10113           if (ASrcTy->getNumElements() != 0) {
10114             Value *Idxs[2];
10115             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10116             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10117             SrcTy = cast<PointerType>(CastOp->getType());
10118             SrcPTy = SrcTy->getElementType();
10119           }
10120
10121       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10122             isa<VectorType>(SrcPTy)) &&
10123           // Do not allow turning this into a load of an integer, which is then
10124           // casted to a pointer, this pessimizes pointer analysis a lot.
10125           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10126           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10127                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10128
10129         // Okay, we are casting from one integer or pointer type to another of
10130         // the same size.  Instead of casting the pointer before the load, cast
10131         // the result of the loaded value.
10132         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10133                                                              CI->getName(),
10134                                                          LI.isVolatile()),LI);
10135         // Now cast the result of the load.
10136         return new BitCastInst(NewLoad, LI.getType());
10137       }
10138     }
10139   }
10140   return 0;
10141 }
10142
10143 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10144 /// from this value cannot trap.  If it is not obviously safe to load from the
10145 /// specified pointer, we do a quick local scan of the basic block containing
10146 /// ScanFrom, to determine if the address is already accessed.
10147 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10148   // If it is an alloca it is always safe to load from.
10149   if (isa<AllocaInst>(V)) return true;
10150
10151   // If it is a global variable it is mostly safe to load from.
10152   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10153     // Don't try to evaluate aliases.  External weak GV can be null.
10154     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10155
10156   // Otherwise, be a little bit agressive by scanning the local block where we
10157   // want to check to see if the pointer is already being loaded or stored
10158   // from/to.  If so, the previous load or store would have already trapped,
10159   // so there is no harm doing an extra load (also, CSE will later eliminate
10160   // the load entirely).
10161   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10162
10163   while (BBI != E) {
10164     --BBI;
10165
10166     // If we see a free or a call (which might do a free) the pointer could be
10167     // marked invalid.
10168     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10169       return false;
10170     
10171     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10172       if (LI->getOperand(0) == V) return true;
10173     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10174       if (SI->getOperand(1) == V) return true;
10175     }
10176
10177   }
10178   return false;
10179 }
10180
10181 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10182 /// until we find the underlying object a pointer is referring to or something
10183 /// we don't understand.  Note that the returned pointer may be offset from the
10184 /// input, because we ignore GEP indices.
10185 static Value *GetUnderlyingObject(Value *Ptr) {
10186   while (1) {
10187     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10188       if (CE->getOpcode() == Instruction::BitCast ||
10189           CE->getOpcode() == Instruction::GetElementPtr)
10190         Ptr = CE->getOperand(0);
10191       else
10192         return Ptr;
10193     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10194       Ptr = BCI->getOperand(0);
10195     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10196       Ptr = GEP->getOperand(0);
10197     } else {
10198       return Ptr;
10199     }
10200   }
10201 }
10202
10203 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10204   Value *Op = LI.getOperand(0);
10205
10206   // Attempt to improve the alignment.
10207   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10208   if (KnownAlign >
10209       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10210                                 LI.getAlignment()))
10211     LI.setAlignment(KnownAlign);
10212
10213   // load (cast X) --> cast (load X) iff safe
10214   if (isa<CastInst>(Op))
10215     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10216       return Res;
10217
10218   // None of the following transforms are legal for volatile loads.
10219   if (LI.isVolatile()) return 0;
10220   
10221   if (&LI.getParent()->front() != &LI) {
10222     BasicBlock::iterator BBI = &LI; --BBI;
10223     // If the instruction immediately before this is a store to the same
10224     // address, do a simple form of store->load forwarding.
10225     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10226       if (SI->getOperand(1) == LI.getOperand(0))
10227         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10228     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10229       if (LIB->getOperand(0) == LI.getOperand(0))
10230         return ReplaceInstUsesWith(LI, LIB);
10231   }
10232
10233   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10234     const Value *GEPI0 = GEPI->getOperand(0);
10235     // TODO: Consider a target hook for valid address spaces for this xform.
10236     if (isa<ConstantPointerNull>(GEPI0) &&
10237         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10238       // Insert a new store to null instruction before the load to indicate
10239       // that this code is not reachable.  We do this instead of inserting
10240       // an unreachable instruction directly because we cannot modify the
10241       // CFG.
10242       new StoreInst(UndefValue::get(LI.getType()),
10243                     Constant::getNullValue(Op->getType()), &LI);
10244       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10245     }
10246   } 
10247
10248   if (Constant *C = dyn_cast<Constant>(Op)) {
10249     // load null/undef -> undef
10250     // TODO: Consider a target hook for valid address spaces for this xform.
10251     if (isa<UndefValue>(C) || (C->isNullValue() && 
10252         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10253       // Insert a new store to null instruction before the load to indicate that
10254       // this code is not reachable.  We do this instead of inserting an
10255       // unreachable instruction directly because we cannot modify the CFG.
10256       new StoreInst(UndefValue::get(LI.getType()),
10257                     Constant::getNullValue(Op->getType()), &LI);
10258       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10259     }
10260
10261     // Instcombine load (constant global) into the value loaded.
10262     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10263       if (GV->isConstant() && !GV->isDeclaration())
10264         return ReplaceInstUsesWith(LI, GV->getInitializer());
10265
10266     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10267     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10268       if (CE->getOpcode() == Instruction::GetElementPtr) {
10269         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10270           if (GV->isConstant() && !GV->isDeclaration())
10271             if (Constant *V = 
10272                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10273               return ReplaceInstUsesWith(LI, V);
10274         if (CE->getOperand(0)->isNullValue()) {
10275           // Insert a new store to null instruction before the load to indicate
10276           // that this code is not reachable.  We do this instead of inserting
10277           // an unreachable instruction directly because we cannot modify the
10278           // CFG.
10279           new StoreInst(UndefValue::get(LI.getType()),
10280                         Constant::getNullValue(Op->getType()), &LI);
10281           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10282         }
10283
10284       } else if (CE->isCast()) {
10285         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10286           return Res;
10287       }
10288     }
10289   }
10290     
10291   // If this load comes from anywhere in a constant global, and if the global
10292   // is all undef or zero, we know what it loads.
10293   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10294     if (GV->isConstant() && GV->hasInitializer()) {
10295       if (GV->getInitializer()->isNullValue())
10296         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10297       else if (isa<UndefValue>(GV->getInitializer()))
10298         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10299     }
10300   }
10301
10302   if (Op->hasOneUse()) {
10303     // Change select and PHI nodes to select values instead of addresses: this
10304     // helps alias analysis out a lot, allows many others simplifications, and
10305     // exposes redundancy in the code.
10306     //
10307     // Note that we cannot do the transformation unless we know that the
10308     // introduced loads cannot trap!  Something like this is valid as long as
10309     // the condition is always false: load (select bool %C, int* null, int* %G),
10310     // but it would not be valid if we transformed it to load from null
10311     // unconditionally.
10312     //
10313     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10314       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10315       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10316           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10317         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10318                                      SI->getOperand(1)->getName()+".val"), LI);
10319         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10320                                      SI->getOperand(2)->getName()+".val"), LI);
10321         return SelectInst::Create(SI->getCondition(), V1, V2);
10322       }
10323
10324       // load (select (cond, null, P)) -> load P
10325       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10326         if (C->isNullValue()) {
10327           LI.setOperand(0, SI->getOperand(2));
10328           return &LI;
10329         }
10330
10331       // load (select (cond, P, null)) -> load P
10332       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10333         if (C->isNullValue()) {
10334           LI.setOperand(0, SI->getOperand(1));
10335           return &LI;
10336         }
10337     }
10338   }
10339   return 0;
10340 }
10341
10342 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10343 /// when possible.
10344 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10345   User *CI = cast<User>(SI.getOperand(1));
10346   Value *CastOp = CI->getOperand(0);
10347
10348   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10349   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10350     const Type *SrcPTy = SrcTy->getElementType();
10351
10352     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10353       // If the source is an array, the code below will not succeed.  Check to
10354       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10355       // constants.
10356       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10357         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10358           if (ASrcTy->getNumElements() != 0) {
10359             Value* Idxs[2];
10360             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10361             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10362             SrcTy = cast<PointerType>(CastOp->getType());
10363             SrcPTy = SrcTy->getElementType();
10364           }
10365
10366       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10367           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10368                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10369
10370         // Okay, we are casting from one integer or pointer type to another of
10371         // the same size.  Instead of casting the pointer before 
10372         // the store, cast the value to be stored.
10373         Value *NewCast;
10374         Value *SIOp0 = SI.getOperand(0);
10375         Instruction::CastOps opcode = Instruction::BitCast;
10376         const Type* CastSrcTy = SIOp0->getType();
10377         const Type* CastDstTy = SrcPTy;
10378         if (isa<PointerType>(CastDstTy)) {
10379           if (CastSrcTy->isInteger())
10380             opcode = Instruction::IntToPtr;
10381         } else if (isa<IntegerType>(CastDstTy)) {
10382           if (isa<PointerType>(SIOp0->getType()))
10383             opcode = Instruction::PtrToInt;
10384         }
10385         if (Constant *C = dyn_cast<Constant>(SIOp0))
10386           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10387         else
10388           NewCast = IC.InsertNewInstBefore(
10389             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10390             SI);
10391         return new StoreInst(NewCast, CastOp);
10392       }
10393     }
10394   }
10395   return 0;
10396 }
10397
10398 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10399   Value *Val = SI.getOperand(0);
10400   Value *Ptr = SI.getOperand(1);
10401
10402   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10403     EraseInstFromFunction(SI);
10404     ++NumCombined;
10405     return 0;
10406   }
10407   
10408   // If the RHS is an alloca with a single use, zapify the store, making the
10409   // alloca dead.
10410   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10411     if (isa<AllocaInst>(Ptr)) {
10412       EraseInstFromFunction(SI);
10413       ++NumCombined;
10414       return 0;
10415     }
10416     
10417     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10418       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10419           GEP->getOperand(0)->hasOneUse()) {
10420         EraseInstFromFunction(SI);
10421         ++NumCombined;
10422         return 0;
10423       }
10424   }
10425
10426   // Attempt to improve the alignment.
10427   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10428   if (KnownAlign >
10429       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10430                                 SI.getAlignment()))
10431     SI.setAlignment(KnownAlign);
10432
10433   // Do really simple DSE, to catch cases where there are several consequtive
10434   // stores to the same location, separated by a few arithmetic operations. This
10435   // situation often occurs with bitfield accesses.
10436   BasicBlock::iterator BBI = &SI;
10437   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10438        --ScanInsts) {
10439     --BBI;
10440     
10441     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10442       // Prev store isn't volatile, and stores to the same location?
10443       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10444         ++NumDeadStore;
10445         ++BBI;
10446         EraseInstFromFunction(*PrevSI);
10447         continue;
10448       }
10449       break;
10450     }
10451     
10452     // If this is a load, we have to stop.  However, if the loaded value is from
10453     // the pointer we're loading and is producing the pointer we're storing,
10454     // then *this* store is dead (X = load P; store X -> P).
10455     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10456       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10457         EraseInstFromFunction(SI);
10458         ++NumCombined;
10459         return 0;
10460       }
10461       // Otherwise, this is a load from some other location.  Stores before it
10462       // may not be dead.
10463       break;
10464     }
10465     
10466     // Don't skip over loads or things that can modify memory.
10467     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10468       break;
10469   }
10470   
10471   
10472   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10473
10474   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10475   if (isa<ConstantPointerNull>(Ptr)) {
10476     if (!isa<UndefValue>(Val)) {
10477       SI.setOperand(0, UndefValue::get(Val->getType()));
10478       if (Instruction *U = dyn_cast<Instruction>(Val))
10479         AddToWorkList(U);  // Dropped a use.
10480       ++NumCombined;
10481     }
10482     return 0;  // Do not modify these!
10483   }
10484
10485   // store undef, Ptr -> noop
10486   if (isa<UndefValue>(Val)) {
10487     EraseInstFromFunction(SI);
10488     ++NumCombined;
10489     return 0;
10490   }
10491
10492   // If the pointer destination is a cast, see if we can fold the cast into the
10493   // source instead.
10494   if (isa<CastInst>(Ptr))
10495     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10496       return Res;
10497   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10498     if (CE->isCast())
10499       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10500         return Res;
10501
10502   
10503   // If this store is the last instruction in the basic block, and if the block
10504   // ends with an unconditional branch, try to move it to the successor block.
10505   BBI = &SI; ++BBI;
10506   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10507     if (BI->isUnconditional())
10508       if (SimplifyStoreAtEndOfBlock(SI))
10509         return 0;  // xform done!
10510   
10511   return 0;
10512 }
10513
10514 /// SimplifyStoreAtEndOfBlock - Turn things like:
10515 ///   if () { *P = v1; } else { *P = v2 }
10516 /// into a phi node with a store in the successor.
10517 ///
10518 /// Simplify things like:
10519 ///   *P = v1; if () { *P = v2; }
10520 /// into a phi node with a store in the successor.
10521 ///
10522 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10523   BasicBlock *StoreBB = SI.getParent();
10524   
10525   // Check to see if the successor block has exactly two incoming edges.  If
10526   // so, see if the other predecessor contains a store to the same location.
10527   // if so, insert a PHI node (if needed) and move the stores down.
10528   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10529   
10530   // Determine whether Dest has exactly two predecessors and, if so, compute
10531   // the other predecessor.
10532   pred_iterator PI = pred_begin(DestBB);
10533   BasicBlock *OtherBB = 0;
10534   if (*PI != StoreBB)
10535     OtherBB = *PI;
10536   ++PI;
10537   if (PI == pred_end(DestBB))
10538     return false;
10539   
10540   if (*PI != StoreBB) {
10541     if (OtherBB)
10542       return false;
10543     OtherBB = *PI;
10544   }
10545   if (++PI != pred_end(DestBB))
10546     return false;
10547
10548   // Bail out if all the relevant blocks aren't distinct (this can happen,
10549   // for example, if SI is in an infinite loop)
10550   if (StoreBB == DestBB || OtherBB == DestBB)
10551     return false;
10552
10553   // Verify that the other block ends in a branch and is not otherwise empty.
10554   BasicBlock::iterator BBI = OtherBB->getTerminator();
10555   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10556   if (!OtherBr || BBI == OtherBB->begin())
10557     return false;
10558   
10559   // If the other block ends in an unconditional branch, check for the 'if then
10560   // else' case.  there is an instruction before the branch.
10561   StoreInst *OtherStore = 0;
10562   if (OtherBr->isUnconditional()) {
10563     // If this isn't a store, or isn't a store to the same location, bail out.
10564     --BBI;
10565     OtherStore = dyn_cast<StoreInst>(BBI);
10566     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10567       return false;
10568   } else {
10569     // Otherwise, the other block ended with a conditional branch. If one of the
10570     // destinations is StoreBB, then we have the if/then case.
10571     if (OtherBr->getSuccessor(0) != StoreBB && 
10572         OtherBr->getSuccessor(1) != StoreBB)
10573       return false;
10574     
10575     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10576     // if/then triangle.  See if there is a store to the same ptr as SI that
10577     // lives in OtherBB.
10578     for (;; --BBI) {
10579       // Check to see if we find the matching store.
10580       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10581         if (OtherStore->getOperand(1) != SI.getOperand(1))
10582           return false;
10583         break;
10584       }
10585       // If we find something that may be using or overwriting the stored
10586       // value, or if we run out of instructions, we can't do the xform.
10587       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10588           BBI == OtherBB->begin())
10589         return false;
10590     }
10591     
10592     // In order to eliminate the store in OtherBr, we have to
10593     // make sure nothing reads or overwrites the stored value in
10594     // StoreBB.
10595     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10596       // FIXME: This should really be AA driven.
10597       if (I->mayReadFromMemory() || I->mayWriteToMemory())
10598         return false;
10599     }
10600   }
10601   
10602   // Insert a PHI node now if we need it.
10603   Value *MergedVal = OtherStore->getOperand(0);
10604   if (MergedVal != SI.getOperand(0)) {
10605     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10606     PN->reserveOperandSpace(2);
10607     PN->addIncoming(SI.getOperand(0), SI.getParent());
10608     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10609     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10610   }
10611   
10612   // Advance to a place where it is safe to insert the new store and
10613   // insert it.
10614   BBI = DestBB->getFirstNonPHI();
10615   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10616                                     OtherStore->isVolatile()), *BBI);
10617   
10618   // Nuke the old stores.
10619   EraseInstFromFunction(SI);
10620   EraseInstFromFunction(*OtherStore);
10621   ++NumCombined;
10622   return true;
10623 }
10624
10625
10626 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10627   // Change br (not X), label True, label False to: br X, label False, True
10628   Value *X = 0;
10629   BasicBlock *TrueDest;
10630   BasicBlock *FalseDest;
10631   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10632       !isa<Constant>(X)) {
10633     // Swap Destinations and condition...
10634     BI.setCondition(X);
10635     BI.setSuccessor(0, FalseDest);
10636     BI.setSuccessor(1, TrueDest);
10637     return &BI;
10638   }
10639
10640   // Cannonicalize fcmp_one -> fcmp_oeq
10641   FCmpInst::Predicate FPred; Value *Y;
10642   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10643                              TrueDest, FalseDest)))
10644     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10645          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10646       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10647       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10648       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10649       NewSCC->takeName(I);
10650       // Swap Destinations and condition...
10651       BI.setCondition(NewSCC);
10652       BI.setSuccessor(0, FalseDest);
10653       BI.setSuccessor(1, TrueDest);
10654       RemoveFromWorkList(I);
10655       I->eraseFromParent();
10656       AddToWorkList(NewSCC);
10657       return &BI;
10658     }
10659
10660   // Cannonicalize icmp_ne -> icmp_eq
10661   ICmpInst::Predicate IPred;
10662   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10663                       TrueDest, FalseDest)))
10664     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10665          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10666          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10667       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10668       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10669       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10670       NewSCC->takeName(I);
10671       // Swap Destinations and condition...
10672       BI.setCondition(NewSCC);
10673       BI.setSuccessor(0, FalseDest);
10674       BI.setSuccessor(1, TrueDest);
10675       RemoveFromWorkList(I);
10676       I->eraseFromParent();;
10677       AddToWorkList(NewSCC);
10678       return &BI;
10679     }
10680
10681   return 0;
10682 }
10683
10684 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10685   Value *Cond = SI.getCondition();
10686   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10687     if (I->getOpcode() == Instruction::Add)
10688       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10689         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10690         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10691           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10692                                                 AddRHS));
10693         SI.setOperand(0, I->getOperand(0));
10694         AddToWorkList(I);
10695         return &SI;
10696       }
10697   }
10698   return 0;
10699 }
10700
10701 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10702   Value *Agg = EV.getAggregateOperand();
10703
10704   if (!EV.hasIndices())
10705     return ReplaceInstUsesWith(EV, Agg);
10706
10707   if (Constant *C = dyn_cast<Constant>(Agg)) {
10708     if (isa<UndefValue>(C))
10709       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
10710       
10711     if (isa<ConstantAggregateZero>(C))
10712       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
10713
10714     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
10715       // Extract the element indexed by the first index out of the constant
10716       Value *V = C->getOperand(*EV.idx_begin());
10717       if (EV.getNumIndices() > 1)
10718         // Extract the remaining indices out of the constant indexed by the
10719         // first index
10720         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
10721       else
10722         return ReplaceInstUsesWith(EV, V);
10723     }
10724     return 0; // Can't handle other constants
10725   } 
10726   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
10727     // We're extracting from an insertvalue instruction, compare the indices
10728     const unsigned *exti, *exte, *insi, *inse;
10729     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
10730          exte = EV.idx_end(), inse = IV->idx_end();
10731          exti != exte && insi != inse;
10732          ++exti, ++insi) {
10733       if (*insi != *exti)
10734         // The insert and extract both reference distinctly different elements.
10735         // This means the extract is not influenced by the insert, and we can
10736         // replace the aggregate operand of the extract with the aggregate
10737         // operand of the insert. i.e., replace
10738         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10739         // %E = extractvalue { i32, { i32 } } %I, 0
10740         // with
10741         // %E = extractvalue { i32, { i32 } } %A, 0
10742         return ExtractValueInst::Create(IV->getAggregateOperand(),
10743                                         EV.idx_begin(), EV.idx_end());
10744     }
10745     if (exti == exte && insi == inse)
10746       // Both iterators are at the end: Index lists are identical. Replace
10747       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10748       // %C = extractvalue { i32, { i32 } } %B, 1, 0
10749       // with "i32 42"
10750       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
10751     if (exti == exte) {
10752       // The extract list is a prefix of the insert list. i.e. replace
10753       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10754       // %E = extractvalue { i32, { i32 } } %I, 1
10755       // with
10756       // %X = extractvalue { i32, { i32 } } %A, 1
10757       // %E = insertvalue { i32 } %X, i32 42, 0
10758       // by switching the order of the insert and extract (though the
10759       // insertvalue should be left in, since it may have other uses).
10760       Value *NewEV = InsertNewInstBefore(
10761         ExtractValueInst::Create(IV->getAggregateOperand(),
10762                                  EV.idx_begin(), EV.idx_end()),
10763         EV);
10764       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
10765                                      insi, inse);
10766     }
10767     if (insi == inse)
10768       // The insert list is a prefix of the extract list
10769       // We can simply remove the common indices from the extract and make it
10770       // operate on the inserted value instead of the insertvalue result.
10771       // i.e., replace
10772       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10773       // %E = extractvalue { i32, { i32 } } %I, 1, 0
10774       // with
10775       // %E extractvalue { i32 } { i32 42 }, 0
10776       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
10777                                       exti, exte);
10778   }
10779   // Can't simplify extracts from other values. Note that nested extracts are
10780   // already simplified implicitely by the above (extract ( extract (insert) )
10781   // will be translated into extract ( insert ( extract ) ) first and then just
10782   // the value inserted, if appropriate).
10783   return 0;
10784 }
10785
10786 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10787 /// is to leave as a vector operation.
10788 static bool CheapToScalarize(Value *V, bool isConstant) {
10789   if (isa<ConstantAggregateZero>(V)) 
10790     return true;
10791   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10792     if (isConstant) return true;
10793     // If all elts are the same, we can extract.
10794     Constant *Op0 = C->getOperand(0);
10795     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10796       if (C->getOperand(i) != Op0)
10797         return false;
10798     return true;
10799   }
10800   Instruction *I = dyn_cast<Instruction>(V);
10801   if (!I) return false;
10802   
10803   // Insert element gets simplified to the inserted element or is deleted if
10804   // this is constant idx extract element and its a constant idx insertelt.
10805   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10806       isa<ConstantInt>(I->getOperand(2)))
10807     return true;
10808   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10809     return true;
10810   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10811     if (BO->hasOneUse() &&
10812         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10813          CheapToScalarize(BO->getOperand(1), isConstant)))
10814       return true;
10815   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10816     if (CI->hasOneUse() &&
10817         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10818          CheapToScalarize(CI->getOperand(1), isConstant)))
10819       return true;
10820   
10821   return false;
10822 }
10823
10824 /// Read and decode a shufflevector mask.
10825 ///
10826 /// It turns undef elements into values that are larger than the number of
10827 /// elements in the input.
10828 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10829   unsigned NElts = SVI->getType()->getNumElements();
10830   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10831     return std::vector<unsigned>(NElts, 0);
10832   if (isa<UndefValue>(SVI->getOperand(2)))
10833     return std::vector<unsigned>(NElts, 2*NElts);
10834
10835   std::vector<unsigned> Result;
10836   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10837   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10838     if (isa<UndefValue>(*i))
10839       Result.push_back(NElts*2);  // undef -> 8
10840     else
10841       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10842   return Result;
10843 }
10844
10845 /// FindScalarElement - Given a vector and an element number, see if the scalar
10846 /// value is already around as a register, for example if it were inserted then
10847 /// extracted from the vector.
10848 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10849   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10850   const VectorType *PTy = cast<VectorType>(V->getType());
10851   unsigned Width = PTy->getNumElements();
10852   if (EltNo >= Width)  // Out of range access.
10853     return UndefValue::get(PTy->getElementType());
10854   
10855   if (isa<UndefValue>(V))
10856     return UndefValue::get(PTy->getElementType());
10857   else if (isa<ConstantAggregateZero>(V))
10858     return Constant::getNullValue(PTy->getElementType());
10859   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10860     return CP->getOperand(EltNo);
10861   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10862     // If this is an insert to a variable element, we don't know what it is.
10863     if (!isa<ConstantInt>(III->getOperand(2))) 
10864       return 0;
10865     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10866     
10867     // If this is an insert to the element we are looking for, return the
10868     // inserted value.
10869     if (EltNo == IIElt) 
10870       return III->getOperand(1);
10871     
10872     // Otherwise, the insertelement doesn't modify the value, recurse on its
10873     // vector input.
10874     return FindScalarElement(III->getOperand(0), EltNo);
10875   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10876     unsigned InEl = getShuffleMask(SVI)[EltNo];
10877     if (InEl < Width)
10878       return FindScalarElement(SVI->getOperand(0), InEl);
10879     else if (InEl < Width*2)
10880       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10881     else
10882       return UndefValue::get(PTy->getElementType());
10883   }
10884   
10885   // Otherwise, we don't know.
10886   return 0;
10887 }
10888
10889 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10890   // If vector val is undef, replace extract with scalar undef.
10891   if (isa<UndefValue>(EI.getOperand(0)))
10892     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10893
10894   // If vector val is constant 0, replace extract with scalar 0.
10895   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10896     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10897   
10898   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10899     // If vector val is constant with all elements the same, replace EI with
10900     // that element. When the elements are not identical, we cannot replace yet
10901     // (we do that below, but only when the index is constant).
10902     Constant *op0 = C->getOperand(0);
10903     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10904       if (C->getOperand(i) != op0) {
10905         op0 = 0; 
10906         break;
10907       }
10908     if (op0)
10909       return ReplaceInstUsesWith(EI, op0);
10910   }
10911   
10912   // If extracting a specified index from the vector, see if we can recursively
10913   // find a previously computed scalar that was inserted into the vector.
10914   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10915     unsigned IndexVal = IdxC->getZExtValue();
10916     unsigned VectorWidth = 
10917       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10918       
10919     // If this is extracting an invalid index, turn this into undef, to avoid
10920     // crashing the code below.
10921     if (IndexVal >= VectorWidth)
10922       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10923     
10924     // This instruction only demands the single element from the input vector.
10925     // If the input vector has a single use, simplify it based on this use
10926     // property.
10927     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10928       uint64_t UndefElts;
10929       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10930                                                 1 << IndexVal,
10931                                                 UndefElts)) {
10932         EI.setOperand(0, V);
10933         return &EI;
10934       }
10935     }
10936     
10937     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10938       return ReplaceInstUsesWith(EI, Elt);
10939     
10940     // If the this extractelement is directly using a bitcast from a vector of
10941     // the same number of elements, see if we can find the source element from
10942     // it.  In this case, we will end up needing to bitcast the scalars.
10943     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10944       if (const VectorType *VT = 
10945               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10946         if (VT->getNumElements() == VectorWidth)
10947           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10948             return new BitCastInst(Elt, EI.getType());
10949     }
10950   }
10951   
10952   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10953     if (I->hasOneUse()) {
10954       // Push extractelement into predecessor operation if legal and
10955       // profitable to do so
10956       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10957         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10958         if (CheapToScalarize(BO, isConstantElt)) {
10959           ExtractElementInst *newEI0 = 
10960             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10961                                    EI.getName()+".lhs");
10962           ExtractElementInst *newEI1 =
10963             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10964                                    EI.getName()+".rhs");
10965           InsertNewInstBefore(newEI0, EI);
10966           InsertNewInstBefore(newEI1, EI);
10967           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10968         }
10969       } else if (isa<LoadInst>(I)) {
10970         unsigned AS = 
10971           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10972         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10973                                          PointerType::get(EI.getType(), AS),EI);
10974         GetElementPtrInst *GEP =
10975           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10976         InsertNewInstBefore(GEP, EI);
10977         return new LoadInst(GEP);
10978       }
10979     }
10980     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10981       // Extracting the inserted element?
10982       if (IE->getOperand(2) == EI.getOperand(1))
10983         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10984       // If the inserted and extracted elements are constants, they must not
10985       // be the same value, extract from the pre-inserted value instead.
10986       if (isa<Constant>(IE->getOperand(2)) &&
10987           isa<Constant>(EI.getOperand(1))) {
10988         AddUsesToWorkList(EI);
10989         EI.setOperand(0, IE->getOperand(0));
10990         return &EI;
10991       }
10992     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10993       // If this is extracting an element from a shufflevector, figure out where
10994       // it came from and extract from the appropriate input element instead.
10995       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10996         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10997         Value *Src;
10998         if (SrcIdx < SVI->getType()->getNumElements())
10999           Src = SVI->getOperand(0);
11000         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11001           SrcIdx -= SVI->getType()->getNumElements();
11002           Src = SVI->getOperand(1);
11003         } else {
11004           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11005         }
11006         return new ExtractElementInst(Src, SrcIdx);
11007       }
11008     }
11009   }
11010   return 0;
11011 }
11012
11013 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11014 /// elements from either LHS or RHS, return the shuffle mask and true. 
11015 /// Otherwise, return false.
11016 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11017                                          std::vector<Constant*> &Mask) {
11018   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11019          "Invalid CollectSingleShuffleElements");
11020   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11021
11022   if (isa<UndefValue>(V)) {
11023     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11024     return true;
11025   } else if (V == LHS) {
11026     for (unsigned i = 0; i != NumElts; ++i)
11027       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11028     return true;
11029   } else if (V == RHS) {
11030     for (unsigned i = 0; i != NumElts; ++i)
11031       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11032     return true;
11033   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11034     // If this is an insert of an extract from some other vector, include it.
11035     Value *VecOp    = IEI->getOperand(0);
11036     Value *ScalarOp = IEI->getOperand(1);
11037     Value *IdxOp    = IEI->getOperand(2);
11038     
11039     if (!isa<ConstantInt>(IdxOp))
11040       return false;
11041     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11042     
11043     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11044       // Okay, we can handle this if the vector we are insertinting into is
11045       // transitively ok.
11046       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11047         // If so, update the mask to reflect the inserted undef.
11048         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11049         return true;
11050       }      
11051     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11052       if (isa<ConstantInt>(EI->getOperand(1)) &&
11053           EI->getOperand(0)->getType() == V->getType()) {
11054         unsigned ExtractedIdx =
11055           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11056         
11057         // This must be extracting from either LHS or RHS.
11058         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11059           // Okay, we can handle this if the vector we are insertinting into is
11060           // transitively ok.
11061           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11062             // If so, update the mask to reflect the inserted value.
11063             if (EI->getOperand(0) == LHS) {
11064               Mask[InsertedIdx % NumElts] = 
11065                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11066             } else {
11067               assert(EI->getOperand(0) == RHS);
11068               Mask[InsertedIdx % NumElts] = 
11069                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11070               
11071             }
11072             return true;
11073           }
11074         }
11075       }
11076     }
11077   }
11078   // TODO: Handle shufflevector here!
11079   
11080   return false;
11081 }
11082
11083 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11084 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11085 /// that computes V and the LHS value of the shuffle.
11086 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11087                                      Value *&RHS) {
11088   assert(isa<VectorType>(V->getType()) && 
11089          (RHS == 0 || V->getType() == RHS->getType()) &&
11090          "Invalid shuffle!");
11091   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11092
11093   if (isa<UndefValue>(V)) {
11094     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11095     return V;
11096   } else if (isa<ConstantAggregateZero>(V)) {
11097     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11098     return V;
11099   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11100     // If this is an insert of an extract from some other vector, include it.
11101     Value *VecOp    = IEI->getOperand(0);
11102     Value *ScalarOp = IEI->getOperand(1);
11103     Value *IdxOp    = IEI->getOperand(2);
11104     
11105     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11106       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11107           EI->getOperand(0)->getType() == V->getType()) {
11108         unsigned ExtractedIdx =
11109           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11110         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11111         
11112         // Either the extracted from or inserted into vector must be RHSVec,
11113         // otherwise we'd end up with a shuffle of three inputs.
11114         if (EI->getOperand(0) == RHS || RHS == 0) {
11115           RHS = EI->getOperand(0);
11116           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11117           Mask[InsertedIdx % NumElts] = 
11118             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11119           return V;
11120         }
11121         
11122         if (VecOp == RHS) {
11123           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11124           // Everything but the extracted element is replaced with the RHS.
11125           for (unsigned i = 0; i != NumElts; ++i) {
11126             if (i != InsertedIdx)
11127               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11128           }
11129           return V;
11130         }
11131         
11132         // If this insertelement is a chain that comes from exactly these two
11133         // vectors, return the vector and the effective shuffle.
11134         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11135           return EI->getOperand(0);
11136         
11137       }
11138     }
11139   }
11140   // TODO: Handle shufflevector here!
11141   
11142   // Otherwise, can't do anything fancy.  Return an identity vector.
11143   for (unsigned i = 0; i != NumElts; ++i)
11144     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11145   return V;
11146 }
11147
11148 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11149   Value *VecOp    = IE.getOperand(0);
11150   Value *ScalarOp = IE.getOperand(1);
11151   Value *IdxOp    = IE.getOperand(2);
11152   
11153   // Inserting an undef or into an undefined place, remove this.
11154   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11155     ReplaceInstUsesWith(IE, VecOp);
11156   
11157   // If the inserted element was extracted from some other vector, and if the 
11158   // indexes are constant, try to turn this into a shufflevector operation.
11159   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11160     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11161         EI->getOperand(0)->getType() == IE.getType()) {
11162       unsigned NumVectorElts = IE.getType()->getNumElements();
11163       unsigned ExtractedIdx =
11164         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11165       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11166       
11167       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11168         return ReplaceInstUsesWith(IE, VecOp);
11169       
11170       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11171         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11172       
11173       // If we are extracting a value from a vector, then inserting it right
11174       // back into the same place, just use the input vector.
11175       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11176         return ReplaceInstUsesWith(IE, VecOp);      
11177       
11178       // We could theoretically do this for ANY input.  However, doing so could
11179       // turn chains of insertelement instructions into a chain of shufflevector
11180       // instructions, and right now we do not merge shufflevectors.  As such,
11181       // only do this in a situation where it is clear that there is benefit.
11182       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11183         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11184         // the values of VecOp, except then one read from EIOp0.
11185         // Build a new shuffle mask.
11186         std::vector<Constant*> Mask;
11187         if (isa<UndefValue>(VecOp))
11188           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11189         else {
11190           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11191           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11192                                                        NumVectorElts));
11193         } 
11194         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11195         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11196                                      ConstantVector::get(Mask));
11197       }
11198       
11199       // If this insertelement isn't used by some other insertelement, turn it
11200       // (and any insertelements it points to), into one big shuffle.
11201       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11202         std::vector<Constant*> Mask;
11203         Value *RHS = 0;
11204         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11205         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11206         // We now have a shuffle of LHS, RHS, Mask.
11207         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11208       }
11209     }
11210   }
11211
11212   return 0;
11213 }
11214
11215
11216 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11217   Value *LHS = SVI.getOperand(0);
11218   Value *RHS = SVI.getOperand(1);
11219   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11220
11221   bool MadeChange = false;
11222   
11223   // Undefined shuffle mask -> undefined value.
11224   if (isa<UndefValue>(SVI.getOperand(2)))
11225     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11226   
11227   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11228   // the undef, change them to undefs.
11229   if (isa<UndefValue>(SVI.getOperand(1))) {
11230     // Scan to see if there are any references to the RHS.  If so, replace them
11231     // with undef element refs and set MadeChange to true.
11232     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11233       if (Mask[i] >= e && Mask[i] != 2*e) {
11234         Mask[i] = 2*e;
11235         MadeChange = true;
11236       }
11237     }
11238     
11239     if (MadeChange) {
11240       // Remap any references to RHS to use LHS.
11241       std::vector<Constant*> Elts;
11242       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11243         if (Mask[i] == 2*e)
11244           Elts.push_back(UndefValue::get(Type::Int32Ty));
11245         else
11246           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11247       }
11248       SVI.setOperand(2, ConstantVector::get(Elts));
11249     }
11250   }
11251   
11252   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11253   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11254   if (LHS == RHS || isa<UndefValue>(LHS)) {
11255     if (isa<UndefValue>(LHS) && LHS == RHS) {
11256       // shuffle(undef,undef,mask) -> undef.
11257       return ReplaceInstUsesWith(SVI, LHS);
11258     }
11259     
11260     // Remap any references to RHS to use LHS.
11261     std::vector<Constant*> Elts;
11262     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11263       if (Mask[i] >= 2*e)
11264         Elts.push_back(UndefValue::get(Type::Int32Ty));
11265       else {
11266         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11267             (Mask[i] <  e && isa<UndefValue>(LHS))) {
11268           Mask[i] = 2*e;     // Turn into undef.
11269           Elts.push_back(UndefValue::get(Type::Int32Ty));
11270         } else {
11271           Mask[i] = Mask[i] % e;  // Force to LHS.
11272           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11273         }
11274       }
11275     }
11276     SVI.setOperand(0, SVI.getOperand(1));
11277     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11278     SVI.setOperand(2, ConstantVector::get(Elts));
11279     LHS = SVI.getOperand(0);
11280     RHS = SVI.getOperand(1);
11281     MadeChange = true;
11282   }
11283   
11284   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11285   bool isLHSID = true, isRHSID = true;
11286     
11287   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11288     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11289     // Is this an identity shuffle of the LHS value?
11290     isLHSID &= (Mask[i] == i);
11291       
11292     // Is this an identity shuffle of the RHS value?
11293     isRHSID &= (Mask[i]-e == i);
11294   }
11295
11296   // Eliminate identity shuffles.
11297   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11298   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11299   
11300   // If the LHS is a shufflevector itself, see if we can combine it with this
11301   // one without producing an unusual shuffle.  Here we are really conservative:
11302   // we are absolutely afraid of producing a shuffle mask not in the input
11303   // program, because the code gen may not be smart enough to turn a merged
11304   // shuffle into two specific shuffles: it may produce worse code.  As such,
11305   // we only merge two shuffles if the result is one of the two input shuffle
11306   // masks.  In this case, merging the shuffles just removes one instruction,
11307   // which we know is safe.  This is good for things like turning:
11308   // (splat(splat)) -> splat.
11309   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11310     if (isa<UndefValue>(RHS)) {
11311       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11312
11313       std::vector<unsigned> NewMask;
11314       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11315         if (Mask[i] >= 2*e)
11316           NewMask.push_back(2*e);
11317         else
11318           NewMask.push_back(LHSMask[Mask[i]]);
11319       
11320       // If the result mask is equal to the src shuffle or this shuffle mask, do
11321       // the replacement.
11322       if (NewMask == LHSMask || NewMask == Mask) {
11323         std::vector<Constant*> Elts;
11324         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11325           if (NewMask[i] >= e*2) {
11326             Elts.push_back(UndefValue::get(Type::Int32Ty));
11327           } else {
11328             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11329           }
11330         }
11331         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11332                                      LHSSVI->getOperand(1),
11333                                      ConstantVector::get(Elts));
11334       }
11335     }
11336   }
11337
11338   return MadeChange ? &SVI : 0;
11339 }
11340
11341
11342
11343
11344 /// TryToSinkInstruction - Try to move the specified instruction from its
11345 /// current block into the beginning of DestBlock, which can only happen if it's
11346 /// safe to move the instruction past all of the instructions between it and the
11347 /// end of its block.
11348 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11349   assert(I->hasOneUse() && "Invariants didn't hold!");
11350
11351   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11352   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11353     return false;
11354
11355   // Do not sink alloca instructions out of the entry block.
11356   if (isa<AllocaInst>(I) && I->getParent() ==
11357         &DestBlock->getParent()->getEntryBlock())
11358     return false;
11359
11360   // We can only sink load instructions if there is nothing between the load and
11361   // the end of block that could change the value.
11362   if (I->mayReadFromMemory()) {
11363     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11364          Scan != E; ++Scan)
11365       if (Scan->mayWriteToMemory())
11366         return false;
11367   }
11368
11369   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11370
11371   I->moveBefore(InsertPos);
11372   ++NumSunkInst;
11373   return true;
11374 }
11375
11376
11377 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11378 /// all reachable code to the worklist.
11379 ///
11380 /// This has a couple of tricks to make the code faster and more powerful.  In
11381 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11382 /// them to the worklist (this significantly speeds up instcombine on code where
11383 /// many instructions are dead or constant).  Additionally, if we find a branch
11384 /// whose condition is a known constant, we only visit the reachable successors.
11385 ///
11386 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11387                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11388                                        InstCombiner &IC,
11389                                        const TargetData *TD) {
11390   SmallVector<BasicBlock*, 256> Worklist;
11391   Worklist.push_back(BB);
11392
11393   while (!Worklist.empty()) {
11394     BB = Worklist.back();
11395     Worklist.pop_back();
11396     
11397     // We have now visited this block!  If we've already been here, ignore it.
11398     if (!Visited.insert(BB)) continue;
11399     
11400     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11401       Instruction *Inst = BBI++;
11402       
11403       // DCE instruction if trivially dead.
11404       if (isInstructionTriviallyDead(Inst)) {
11405         ++NumDeadInst;
11406         DOUT << "IC: DCE: " << *Inst;
11407         Inst->eraseFromParent();
11408         continue;
11409       }
11410       
11411       // ConstantProp instruction if trivially constant.
11412       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11413         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11414         Inst->replaceAllUsesWith(C);
11415         ++NumConstProp;
11416         Inst->eraseFromParent();
11417         continue;
11418       }
11419      
11420       IC.AddToWorkList(Inst);
11421     }
11422
11423     // Recursively visit successors.  If this is a branch or switch on a
11424     // constant, only visit the reachable successor.
11425     TerminatorInst *TI = BB->getTerminator();
11426     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11427       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11428         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11429         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11430         Worklist.push_back(ReachableBB);
11431         continue;
11432       }
11433     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11434       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11435         // See if this is an explicit destination.
11436         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11437           if (SI->getCaseValue(i) == Cond) {
11438             BasicBlock *ReachableBB = SI->getSuccessor(i);
11439             Worklist.push_back(ReachableBB);
11440             continue;
11441           }
11442         
11443         // Otherwise it is the default destination.
11444         Worklist.push_back(SI->getSuccessor(0));
11445         continue;
11446       }
11447     }
11448     
11449     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11450       Worklist.push_back(TI->getSuccessor(i));
11451   }
11452 }
11453
11454 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11455   bool Changed = false;
11456   TD = &getAnalysis<TargetData>();
11457   
11458   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11459              << F.getNameStr() << "\n");
11460
11461   {
11462     // Do a depth-first traversal of the function, populate the worklist with
11463     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11464     // track of which blocks we visit.
11465     SmallPtrSet<BasicBlock*, 64> Visited;
11466     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11467
11468     // Do a quick scan over the function.  If we find any blocks that are
11469     // unreachable, remove any instructions inside of them.  This prevents
11470     // the instcombine code from having to deal with some bad special cases.
11471     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11472       if (!Visited.count(BB)) {
11473         Instruction *Term = BB->getTerminator();
11474         while (Term != BB->begin()) {   // Remove instrs bottom-up
11475           BasicBlock::iterator I = Term; --I;
11476
11477           DOUT << "IC: DCE: " << *I;
11478           ++NumDeadInst;
11479
11480           if (!I->use_empty())
11481             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11482           I->eraseFromParent();
11483         }
11484       }
11485   }
11486
11487   while (!Worklist.empty()) {
11488     Instruction *I = RemoveOneFromWorkList();
11489     if (I == 0) continue;  // skip null values.
11490
11491     // Check to see if we can DCE the instruction.
11492     if (isInstructionTriviallyDead(I)) {
11493       // Add operands to the worklist.
11494       if (I->getNumOperands() < 4)
11495         AddUsesToWorkList(*I);
11496       ++NumDeadInst;
11497
11498       DOUT << "IC: DCE: " << *I;
11499
11500       I->eraseFromParent();
11501       RemoveFromWorkList(I);
11502       continue;
11503     }
11504
11505     // Instruction isn't dead, see if we can constant propagate it.
11506     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11507       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11508
11509       // Add operands to the worklist.
11510       AddUsesToWorkList(*I);
11511       ReplaceInstUsesWith(*I, C);
11512
11513       ++NumConstProp;
11514       I->eraseFromParent();
11515       RemoveFromWorkList(I);
11516       continue;
11517     }
11518
11519     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11520       // See if we can constant fold its operands.
11521       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11522         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11523           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11524             i->set(NewC);
11525         }
11526       }
11527     }
11528
11529     // See if we can trivially sink this instruction to a successor basic block.
11530     if (I->hasOneUse()) {
11531       BasicBlock *BB = I->getParent();
11532       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11533       if (UserParent != BB) {
11534         bool UserIsSuccessor = false;
11535         // See if the user is one of our successors.
11536         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11537           if (*SI == UserParent) {
11538             UserIsSuccessor = true;
11539             break;
11540           }
11541
11542         // If the user is one of our immediate successors, and if that successor
11543         // only has us as a predecessors (we'd have to split the critical edge
11544         // otherwise), we can keep going.
11545         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11546             next(pred_begin(UserParent)) == pred_end(UserParent))
11547           // Okay, the CFG is simple enough, try to sink this instruction.
11548           Changed |= TryToSinkInstruction(I, UserParent);
11549       }
11550     }
11551
11552     // Now that we have an instruction, try combining it to simplify it...
11553 #ifndef NDEBUG
11554     std::string OrigI;
11555 #endif
11556     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11557     if (Instruction *Result = visit(*I)) {
11558       ++NumCombined;
11559       // Should we replace the old instruction with a new one?
11560       if (Result != I) {
11561         DOUT << "IC: Old = " << *I
11562              << "    New = " << *Result;
11563
11564         // Everything uses the new instruction now.
11565         I->replaceAllUsesWith(Result);
11566
11567         // Push the new instruction and any users onto the worklist.
11568         AddToWorkList(Result);
11569         AddUsersToWorkList(*Result);
11570
11571         // Move the name to the new instruction first.
11572         Result->takeName(I);
11573
11574         // Insert the new instruction into the basic block...
11575         BasicBlock *InstParent = I->getParent();
11576         BasicBlock::iterator InsertPos = I;
11577
11578         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11579           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11580             ++InsertPos;
11581
11582         InstParent->getInstList().insert(InsertPos, Result);
11583
11584         // Make sure that we reprocess all operands now that we reduced their
11585         // use counts.
11586         AddUsesToWorkList(*I);
11587
11588         // Instructions can end up on the worklist more than once.  Make sure
11589         // we do not process an instruction that has been deleted.
11590         RemoveFromWorkList(I);
11591
11592         // Erase the old instruction.
11593         InstParent->getInstList().erase(I);
11594       } else {
11595 #ifndef NDEBUG
11596         DOUT << "IC: Mod = " << OrigI
11597              << "    New = " << *I;
11598 #endif
11599
11600         // If the instruction was modified, it's possible that it is now dead.
11601         // if so, remove it.
11602         if (isInstructionTriviallyDead(I)) {
11603           // Make sure we process all operands now that we are reducing their
11604           // use counts.
11605           AddUsesToWorkList(*I);
11606
11607           // Instructions may end up in the worklist more than once.  Erase all
11608           // occurrences of this instruction.
11609           RemoveFromWorkList(I);
11610           I->eraseFromParent();
11611         } else {
11612           AddToWorkList(I);
11613           AddUsersToWorkList(*I);
11614         }
11615       }
11616       Changed = true;
11617     }
11618   }
11619
11620   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11621     
11622   // Do an explicit clear, this shrinks the map if needed.
11623   WorklistMap.clear();
11624   return Changed;
11625 }
11626
11627
11628 bool InstCombiner::runOnFunction(Function &F) {
11629   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11630   
11631   bool EverMadeChange = false;
11632
11633   // Iterate while there is work to do.
11634   unsigned Iteration = 0;
11635   while (DoOneIteration(F, Iteration++))
11636     EverMadeChange = true;
11637   return EverMadeChange;
11638 }
11639
11640 FunctionPass *llvm::createInstructionCombiningPass() {
11641   return new InstCombiner();
11642 }
11643
11644