Remove misleading constant from comment.
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     std::vector<Instruction*> 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     Instruction *commonRemTransforms(BinaryOperator &I);
176     Instruction *commonIRemTransforms(BinaryOperator &I);
177     Instruction *commonDivTransforms(BinaryOperator &I);
178     Instruction *commonIDivTransforms(BinaryOperator &I);
179     Instruction *visitUDiv(BinaryOperator &I);
180     Instruction *visitSDiv(BinaryOperator &I);
181     Instruction *visitFDiv(BinaryOperator &I);
182     Instruction *visitAnd(BinaryOperator &I);
183     Instruction *visitOr (BinaryOperator &I);
184     Instruction *visitXor(BinaryOperator &I);
185     Instruction *visitShl(BinaryOperator &I);
186     Instruction *visitAShr(BinaryOperator &I);
187     Instruction *visitLShr(BinaryOperator &I);
188     Instruction *commonShiftTransforms(BinaryOperator &I);
189     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190                                       Constant *RHSC);
191     Instruction *visitFCmpInst(FCmpInst &I);
192     Instruction *visitICmpInst(ICmpInst &I);
193     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
194     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
195                                                 Instruction *LHS,
196                                                 ConstantInt *RHS);
197     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198                                 ConstantInt *DivRHS);
199
200     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201                              ICmpInst::Predicate Cond, Instruction &I);
202     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
203                                      BinaryOperator &I);
204     Instruction *commonCastTransforms(CastInst &CI);
205     Instruction *commonIntCastTransforms(CastInst &CI);
206     Instruction *commonPointerCastTransforms(CastInst &CI);
207     Instruction *visitTrunc(TruncInst &CI);
208     Instruction *visitZExt(ZExtInst &CI);
209     Instruction *visitSExt(SExtInst &CI);
210     Instruction *visitFPTrunc(FPTruncInst &CI);
211     Instruction *visitFPExt(CastInst &CI);
212     Instruction *visitFPToUI(FPToUIInst &FI);
213     Instruction *visitFPToSI(FPToSIInst &FI);
214     Instruction *visitUIToFP(CastInst &CI);
215     Instruction *visitSIToFP(CastInst &CI);
216     Instruction *visitPtrToInt(CastInst &CI);
217     Instruction *visitIntToPtr(IntToPtrInst &CI);
218     Instruction *visitBitCast(BitCastInst &CI);
219     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220                                 Instruction *FI);
221     Instruction *visitSelectInst(SelectInst &CI);
222     Instruction *visitCallInst(CallInst &CI);
223     Instruction *visitInvokeInst(InvokeInst &II);
224     Instruction *visitPHINode(PHINode &PN);
225     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
226     Instruction *visitAllocationInst(AllocationInst &AI);
227     Instruction *visitFreeInst(FreeInst &FI);
228     Instruction *visitLoadInst(LoadInst &LI);
229     Instruction *visitStoreInst(StoreInst &SI);
230     Instruction *visitBranchInst(BranchInst &BI);
231     Instruction *visitSwitchInst(SwitchInst &SI);
232     Instruction *visitInsertElementInst(InsertElementInst &IE);
233     Instruction *visitExtractElementInst(ExtractElementInst &EI);
234     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
235     Instruction *visitExtractValueInst(ExtractValueInst &EV);
236
237     // visitInstruction - Specify what to return for unhandled instructions...
238     Instruction *visitInstruction(Instruction &I) { return 0; }
239
240   private:
241     Instruction *visitCallSite(CallSite CS);
242     bool transformConstExprCastCall(CallSite CS);
243     Instruction *transformCallThroughTrampoline(CallSite CS);
244     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
245                                    bool DoXform = true);
246     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
247
248   public:
249     // InsertNewInstBefore - insert an instruction New before instruction Old
250     // in the program.  Add the new instruction to the worklist.
251     //
252     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
253       assert(New && New->getParent() == 0 &&
254              "New instruction already inserted into a basic block!");
255       BasicBlock *BB = Old.getParent();
256       BB->getInstList().insert(&Old, New);  // Insert inst
257       AddToWorkList(New);
258       return New;
259     }
260
261     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
262     /// This also adds the cast to the worklist.  Finally, this returns the
263     /// cast.
264     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
265                             Instruction &Pos) {
266       if (V->getType() == Ty) return V;
267
268       if (Constant *CV = dyn_cast<Constant>(V))
269         return ConstantExpr::getCast(opc, CV, Ty);
270       
271       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
272       AddToWorkList(C);
273       return C;
274     }
275         
276     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
277       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
278     }
279
280
281     // ReplaceInstUsesWith - This method is to be used when an instruction is
282     // found to be dead, replacable with another preexisting expression.  Here
283     // we add all uses of I to the worklist, replace all uses of I with the new
284     // value, then return I, so that the inst combiner will know that I was
285     // modified.
286     //
287     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
288       AddUsersToWorkList(I);         // Add all modified instrs to worklist
289       if (&I != V) {
290         I.replaceAllUsesWith(V);
291         return &I;
292       } else {
293         // If we are replacing the instruction with itself, this must be in a
294         // segment of unreachable code, so just clobber the instruction.
295         I.replaceAllUsesWith(UndefValue::get(I.getType()));
296         return &I;
297       }
298     }
299
300     // UpdateValueUsesWith - This method is to be used when an value is
301     // found to be replacable with another preexisting expression or was
302     // updated.  Here we add all uses of I to the worklist, replace all uses of
303     // I with the new value (unless the instruction was just updated), then
304     // return true, so that the inst combiner will know that I was modified.
305     //
306     bool UpdateValueUsesWith(Value *Old, Value *New) {
307       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
308       if (Old != New)
309         Old->replaceAllUsesWith(New);
310       if (Instruction *I = dyn_cast<Instruction>(Old))
311         AddToWorkList(I);
312       if (Instruction *I = dyn_cast<Instruction>(New))
313         AddToWorkList(I);
314       return true;
315     }
316     
317     // EraseInstFromFunction - When dealing with an instruction that has side
318     // effects or produces a void value, we can't rely on DCE to delete the
319     // instruction.  Instead, visit methods should return the value returned by
320     // this function.
321     Instruction *EraseInstFromFunction(Instruction &I) {
322       assert(I.use_empty() && "Cannot erase instruction that is used!");
323       AddUsesToWorkList(I);
324       RemoveFromWorkList(&I);
325       I.eraseFromParent();
326       return 0;  // Don't do anything with FI
327     }
328         
329     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330                            APInt &KnownOne, unsigned Depth = 0) const {
331       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332     }
333     
334     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
335                            unsigned Depth = 0) const {
336       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337     }
338     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339       return llvm::ComputeNumSignBits(Op, TD, Depth);
340     }
341
342   private:
343     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
344     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
345     /// casts that are known to not do anything...
346     ///
347     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
348                                    Value *V, const Type *DestTy,
349                                    Instruction *InsertBefore);
350
351     /// SimplifyCommutative - This performs a few simplifications for 
352     /// commutative operators.
353     bool SimplifyCommutative(BinaryOperator &I);
354
355     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
356     /// most-complex to least-complex order.
357     bool SimplifyCompare(CmpInst &I);
358
359     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
360     /// on the demanded bits.
361     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
362                               APInt& KnownZero, APInt& KnownOne,
363                               unsigned Depth = 0);
364
365     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
366                                       uint64_t &UndefElts, unsigned Depth = 0);
367       
368     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369     // PHI node as operand #0, see if we can fold the instruction into the PHI
370     // (which is only possible if all operands to the PHI are constants).
371     Instruction *FoldOpIntoPhi(Instruction &I);
372
373     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374     // operator and they all are only used by the PHI, PHI together their
375     // inputs, and do the operation once, to the result of the PHI.
376     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378     
379     
380     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
382     
383     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384                               bool isSub, Instruction &I);
385     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386                                  bool isSigned, bool Inside, Instruction &IB);
387     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388     Instruction *MatchBSwap(BinaryOperator &I);
389     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
390     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
391     Instruction *SimplifyMemSet(MemSetInst *MI);
392
393
394     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
395
396     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
397                                     unsigned CastOpc,
398                                     int &NumCastsRemoved);
399     unsigned GetOrEnforceKnownAlignment(Value *V,
400                                         unsigned PrefAlign = 0);
401
402   };
403 }
404
405 char InstCombiner::ID = 0;
406 static RegisterPass<InstCombiner>
407 X("instcombine", "Combine redundant instructions");
408
409 // getComplexity:  Assign a complexity or rank value to LLVM Values...
410 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411 static unsigned getComplexity(Value *V) {
412   if (isa<Instruction>(V)) {
413     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
414       return 3;
415     return 4;
416   }
417   if (isa<Argument>(V)) return 3;
418   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
419 }
420
421 // isOnlyUse - Return true if this instruction will be deleted if we stop using
422 // it.
423 static bool isOnlyUse(Value *V) {
424   return V->hasOneUse() || isa<Constant>(V);
425 }
426
427 // getPromotedType - Return the specified type promoted as it would be to pass
428 // though a va_arg area...
429 static const Type *getPromotedType(const Type *Ty) {
430   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431     if (ITy->getBitWidth() < 32)
432       return Type::Int32Ty;
433   }
434   return Ty;
435 }
436
437 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
438 /// expression bitcast,  return the operand value, otherwise return null.
439 static Value *getBitCastOperand(Value *V) {
440   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
441     return I->getOperand(0);
442   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
443     if (CE->getOpcode() == Instruction::BitCast)
444       return CE->getOperand(0);
445   return 0;
446 }
447
448 /// This function is a wrapper around CastInst::isEliminableCastPair. It
449 /// simply extracts arguments and returns what that function returns.
450 static Instruction::CastOps 
451 isEliminableCastPair(
452   const CastInst *CI, ///< The first cast instruction
453   unsigned opcode,       ///< The opcode of the second cast instruction
454   const Type *DstTy,     ///< The target type for the second cast instruction
455   TargetData *TD         ///< The target data for pointer size
456 ) {
457   
458   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
459   const Type *MidTy = CI->getType();                  // B from above
460
461   // Get the opcodes of the two Cast instructions
462   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
463   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
464
465   return Instruction::CastOps(
466       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
467                                      DstTy, TD->getIntPtrType()));
468 }
469
470 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
471 /// in any code being generated.  It does not require codegen if V is simple
472 /// enough or if the cast can be folded into other casts.
473 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
474                               const Type *Ty, TargetData *TD) {
475   if (V->getType() == Ty || isa<Constant>(V)) return false;
476   
477   // If this is another cast that can be eliminated, it isn't codegen either.
478   if (const CastInst *CI = dyn_cast<CastInst>(V))
479     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
480       return false;
481   return true;
482 }
483
484 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
485 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
486 /// casts that are known to not do anything...
487 ///
488 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
489                                              Value *V, const Type *DestTy,
490                                              Instruction *InsertBefore) {
491   if (V->getType() == DestTy) return V;
492   if (Constant *C = dyn_cast<Constant>(V))
493     return ConstantExpr::getCast(opcode, C, DestTy);
494   
495   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
496 }
497
498 // SimplifyCommutative - This performs a few simplifications for commutative
499 // operators:
500 //
501 //  1. Order operands such that they are listed from right (least complex) to
502 //     left (most complex).  This puts constants before unary operators before
503 //     binary operators.
504 //
505 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
506 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
507 //
508 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
509   bool Changed = false;
510   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
511     Changed = !I.swapOperands();
512
513   if (!I.isAssociative()) return Changed;
514   Instruction::BinaryOps Opcode = I.getOpcode();
515   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517       if (isa<Constant>(I.getOperand(1))) {
518         Constant *Folded = ConstantExpr::get(I.getOpcode(),
519                                              cast<Constant>(I.getOperand(1)),
520                                              cast<Constant>(Op->getOperand(1)));
521         I.setOperand(0, Op->getOperand(0));
522         I.setOperand(1, Folded);
523         return true;
524       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526             isOnlyUse(Op) && isOnlyUse(Op1)) {
527           Constant *C1 = cast<Constant>(Op->getOperand(1));
528           Constant *C2 = cast<Constant>(Op1->getOperand(1));
529
530           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
531           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
532           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
533                                                     Op1->getOperand(0),
534                                                     Op1->getName(), &I);
535           AddToWorkList(New);
536           I.setOperand(0, New);
537           I.setOperand(1, Folded);
538           return true;
539         }
540     }
541   return Changed;
542 }
543
544 /// SimplifyCompare - For a CmpInst this function just orders the operands
545 /// so that theyare listed from right (least complex) to left (most complex).
546 /// This puts constants before unary operators before binary operators.
547 bool InstCombiner::SimplifyCompare(CmpInst &I) {
548   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
549     return false;
550   I.swapOperands();
551   // Compare instructions are not associative so there's nothing else we can do.
552   return true;
553 }
554
555 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
556 // if the LHS is a constant zero (which is the 'negate' form).
557 //
558 static inline Value *dyn_castNegVal(Value *V) {
559   if (BinaryOperator::isNeg(V))
560     return BinaryOperator::getNegArgument(V);
561
562   // Constants can be considered to be negated values if they can be folded.
563   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
564     return ConstantExpr::getNeg(C);
565
566   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
567     if (C->getType()->getElementType()->isInteger())
568       return ConstantExpr::getNeg(C);
569
570   return 0;
571 }
572
573 static inline Value *dyn_castNotVal(Value *V) {
574   if (BinaryOperator::isNot(V))
575     return BinaryOperator::getNotArgument(V);
576
577   // Constants can be considered to be not'ed values...
578   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
579     return ConstantInt::get(~C->getValue());
580   return 0;
581 }
582
583 // dyn_castFoldableMul - If this value is a multiply that can be folded into
584 // other computations (because it has a constant operand), return the
585 // non-constant operand of the multiply, and set CST to point to the multiplier.
586 // Otherwise, return null.
587 //
588 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
589   if (V->hasOneUse() && V->getType()->isInteger())
590     if (Instruction *I = dyn_cast<Instruction>(V)) {
591       if (I->getOpcode() == Instruction::Mul)
592         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
593           return I->getOperand(0);
594       if (I->getOpcode() == Instruction::Shl)
595         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
596           // The multiplier is really 1 << CST.
597           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
598           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
599           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
600           return I->getOperand(0);
601         }
602     }
603   return 0;
604 }
605
606 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
607 /// expression, return it.
608 static User *dyn_castGetElementPtr(Value *V) {
609   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
610   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
611     if (CE->getOpcode() == Instruction::GetElementPtr)
612       return cast<User>(V);
613   return false;
614 }
615
616 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
617 /// opcode value. Otherwise return UserOp1.
618 static unsigned getOpcode(const Value *V) {
619   if (const Instruction *I = dyn_cast<Instruction>(V))
620     return I->getOpcode();
621   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
622     return CE->getOpcode();
623   // Use UserOp1 to mean there's no opcode.
624   return Instruction::UserOp1;
625 }
626
627 /// AddOne - Add one to a ConstantInt
628 static ConstantInt *AddOne(ConstantInt *C) {
629   APInt Val(C->getValue());
630   return ConstantInt::get(++Val);
631 }
632 /// SubOne - Subtract one from a ConstantInt
633 static ConstantInt *SubOne(ConstantInt *C) {
634   APInt Val(C->getValue());
635   return ConstantInt::get(--Val);
636 }
637 /// Add - Add two ConstantInts together
638 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
639   return ConstantInt::get(C1->getValue() + C2->getValue());
640 }
641 /// And - Bitwise AND two ConstantInts together
642 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
643   return ConstantInt::get(C1->getValue() & C2->getValue());
644 }
645 /// Subtract - Subtract one ConstantInt from another
646 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
647   return ConstantInt::get(C1->getValue() - C2->getValue());
648 }
649 /// Multiply - Multiply two ConstantInts together
650 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
651   return ConstantInt::get(C1->getValue() * C2->getValue());
652 }
653 /// MultiplyOverflows - True if the multiply can not be expressed in an int
654 /// this size.
655 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
656   uint32_t W = C1->getBitWidth();
657   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
658   if (sign) {
659     LHSExt.sext(W * 2);
660     RHSExt.sext(W * 2);
661   } else {
662     LHSExt.zext(W * 2);
663     RHSExt.zext(W * 2);
664   }
665
666   APInt MulExt = LHSExt * RHSExt;
667
668   if (sign) {
669     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
670     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
671     return MulExt.slt(Min) || MulExt.sgt(Max);
672   } else 
673     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
674 }
675
676
677 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
678 /// specified instruction is a constant integer.  If so, check to see if there
679 /// are any bits set in the constant that are not demanded.  If so, shrink the
680 /// constant and return true.
681 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
682                                    APInt Demanded) {
683   assert(I && "No instruction?");
684   assert(OpNo < I->getNumOperands() && "Operand index too large");
685
686   // If the operand is not a constant integer, nothing to do.
687   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
688   if (!OpC) return false;
689
690   // If there are no bits set that aren't demanded, nothing to do.
691   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
692   if ((~Demanded & OpC->getValue()) == 0)
693     return false;
694
695   // This instruction is producing bits that are not demanded. Shrink the RHS.
696   Demanded &= OpC->getValue();
697   I->setOperand(OpNo, ConstantInt::get(Demanded));
698   return true;
699 }
700
701 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
702 // set of known zero and one bits, compute the maximum and minimum values that
703 // could have the specified known zero and known one bits, returning them in
704 // min/max.
705 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
706                                                    const APInt& KnownZero,
707                                                    const APInt& KnownOne,
708                                                    APInt& Min, APInt& Max) {
709   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
710   assert(KnownZero.getBitWidth() == BitWidth && 
711          KnownOne.getBitWidth() == BitWidth &&
712          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
713          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
714   APInt UnknownBits = ~(KnownZero|KnownOne);
715
716   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
717   // bit if it is unknown.
718   Min = KnownOne;
719   Max = KnownOne|UnknownBits;
720   
721   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
722     Min.set(BitWidth-1);
723     Max.clear(BitWidth-1);
724   }
725 }
726
727 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
728 // a set of known zero and one bits, compute the maximum and minimum values that
729 // could have the specified known zero and known one bits, returning them in
730 // min/max.
731 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
732                                                      const APInt &KnownZero,
733                                                      const APInt &KnownOne,
734                                                      APInt &Min, APInt &Max) {
735   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
736   assert(KnownZero.getBitWidth() == BitWidth && 
737          KnownOne.getBitWidth() == BitWidth &&
738          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
739          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
740   APInt UnknownBits = ~(KnownZero|KnownOne);
741   
742   // The minimum value is when the unknown bits are all zeros.
743   Min = KnownOne;
744   // The maximum value is when the unknown bits are all ones.
745   Max = KnownOne|UnknownBits;
746 }
747
748 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
749 /// value based on the demanded bits. When this function is called, it is known
750 /// that only the bits set in DemandedMask of the result of V are ever used
751 /// downstream. Consequently, depending on the mask and V, it may be possible
752 /// to replace V with a constant or one of its operands. In such cases, this
753 /// function does the replacement and returns true. In all other cases, it
754 /// returns false after analyzing the expression and setting KnownOne and known
755 /// to be one in the expression. KnownZero contains all the bits that are known
756 /// to be zero in the expression. These are provided to potentially allow the
757 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
758 /// the expression. KnownOne and KnownZero always follow the invariant that 
759 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
760 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
761 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
762 /// and KnownOne must all be the same.
763 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
764                                         APInt& KnownZero, APInt& KnownOne,
765                                         unsigned Depth) {
766   assert(V != 0 && "Null pointer of Value???");
767   assert(Depth <= 6 && "Limit Search Depth");
768   uint32_t BitWidth = DemandedMask.getBitWidth();
769   const IntegerType *VTy = cast<IntegerType>(V->getType());
770   assert(VTy->getBitWidth() == BitWidth && 
771          KnownZero.getBitWidth() == BitWidth && 
772          KnownOne.getBitWidth() == BitWidth &&
773          "Value *V, DemandedMask, KnownZero and KnownOne \
774           must have same BitWidth");
775   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
776     // We know all of the bits for a constant!
777     KnownOne = CI->getValue() & DemandedMask;
778     KnownZero = ~KnownOne & DemandedMask;
779     return false;
780   }
781   
782   KnownZero.clear(); 
783   KnownOne.clear();
784   if (!V->hasOneUse()) {    // Other users may use these bits.
785     if (Depth != 0) {       // Not at the root.
786       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
787       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
788       return false;
789     }
790     // If this is the root being simplified, allow it to have multiple uses,
791     // just set the DemandedMask to all bits.
792     DemandedMask = APInt::getAllOnesValue(BitWidth);
793   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
794     if (V != UndefValue::get(VTy))
795       return UpdateValueUsesWith(V, UndefValue::get(VTy));
796     return false;
797   } else if (Depth == 6) {        // Limit search depth.
798     return false;
799   }
800   
801   Instruction *I = dyn_cast<Instruction>(V);
802   if (!I) return false;        // Only analyze instructions.
803
804   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
805   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
806   switch (I->getOpcode()) {
807   default:
808     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
809     break;
810   case Instruction::And:
811     // If either the LHS or the RHS are Zero, the result is zero.
812     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
813                              RHSKnownZero, RHSKnownOne, Depth+1))
814       return true;
815     assert((RHSKnownZero & RHSKnownOne) == 0 && 
816            "Bits known to be one AND zero?"); 
817
818     // If something is known zero on the RHS, the bits aren't demanded on the
819     // LHS.
820     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
821                              LHSKnownZero, LHSKnownOne, Depth+1))
822       return true;
823     assert((LHSKnownZero & LHSKnownOne) == 0 && 
824            "Bits known to be one AND zero?"); 
825
826     // If all of the demanded bits are known 1 on one side, return the other.
827     // These bits cannot contribute to the result of the 'and'.
828     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
829         (DemandedMask & ~LHSKnownZero))
830       return UpdateValueUsesWith(I, I->getOperand(0));
831     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
832         (DemandedMask & ~RHSKnownZero))
833       return UpdateValueUsesWith(I, I->getOperand(1));
834     
835     // If all of the demanded bits in the inputs are known zeros, return zero.
836     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
837       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
838       
839     // If the RHS is a constant, see if we can simplify it.
840     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
841       return UpdateValueUsesWith(I, I);
842       
843     // Output known-1 bits are only known if set in both the LHS & RHS.
844     RHSKnownOne &= LHSKnownOne;
845     // Output known-0 are known to be clear if zero in either the LHS | RHS.
846     RHSKnownZero |= LHSKnownZero;
847     break;
848   case Instruction::Or:
849     // If either the LHS or the RHS are One, the result is One.
850     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
851                              RHSKnownZero, RHSKnownOne, Depth+1))
852       return true;
853     assert((RHSKnownZero & RHSKnownOne) == 0 && 
854            "Bits known to be one AND zero?"); 
855     // If something is known one on the RHS, the bits aren't demanded on the
856     // LHS.
857     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
858                              LHSKnownZero, LHSKnownOne, Depth+1))
859       return true;
860     assert((LHSKnownZero & LHSKnownOne) == 0 && 
861            "Bits known to be one AND zero?"); 
862     
863     // If all of the demanded bits are known zero on one side, return the other.
864     // These bits cannot contribute to the result of the 'or'.
865     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
866         (DemandedMask & ~LHSKnownOne))
867       return UpdateValueUsesWith(I, I->getOperand(0));
868     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
869         (DemandedMask & ~RHSKnownOne))
870       return UpdateValueUsesWith(I, I->getOperand(1));
871
872     // If all of the potentially set bits on one side are known to be set on
873     // the other side, just use the 'other' side.
874     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
875         (DemandedMask & (~RHSKnownZero)))
876       return UpdateValueUsesWith(I, I->getOperand(0));
877     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
878         (DemandedMask & (~LHSKnownZero)))
879       return UpdateValueUsesWith(I, I->getOperand(1));
880         
881     // If the RHS is a constant, see if we can simplify it.
882     if (ShrinkDemandedConstant(I, 1, DemandedMask))
883       return UpdateValueUsesWith(I, I);
884           
885     // Output known-0 bits are only known if clear in both the LHS & RHS.
886     RHSKnownZero &= LHSKnownZero;
887     // Output known-1 are known to be set if set in either the LHS | RHS.
888     RHSKnownOne |= LHSKnownOne;
889     break;
890   case Instruction::Xor: {
891     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
892                              RHSKnownZero, RHSKnownOne, Depth+1))
893       return true;
894     assert((RHSKnownZero & RHSKnownOne) == 0 && 
895            "Bits known to be one AND zero?"); 
896     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
897                              LHSKnownZero, LHSKnownOne, Depth+1))
898       return true;
899     assert((LHSKnownZero & LHSKnownOne) == 0 && 
900            "Bits known to be one AND zero?"); 
901     
902     // If all of the demanded bits are known zero on one side, return the other.
903     // These bits cannot contribute to the result of the 'xor'.
904     if ((DemandedMask & RHSKnownZero) == DemandedMask)
905       return UpdateValueUsesWith(I, I->getOperand(0));
906     if ((DemandedMask & LHSKnownZero) == DemandedMask)
907       return UpdateValueUsesWith(I, I->getOperand(1));
908     
909     // Output known-0 bits are known if clear or set in both the LHS & RHS.
910     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
911                          (RHSKnownOne & LHSKnownOne);
912     // Output known-1 are known to be set if set in only one of the LHS, RHS.
913     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
914                         (RHSKnownOne & LHSKnownZero);
915     
916     // If all of the demanded bits are known to be zero on one side or the
917     // other, turn this into an *inclusive* or.
918     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
919     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
920       Instruction *Or =
921         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
922                                  I->getName());
923       InsertNewInstBefore(Or, *I);
924       return UpdateValueUsesWith(I, Or);
925     }
926     
927     // If all of the demanded bits on one side are known, and all of the set
928     // bits on that side are also known to be set on the other side, turn this
929     // into an AND, as we know the bits will be cleared.
930     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
931     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
932       // all known
933       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
934         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
935         Instruction *And = 
936           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
937         InsertNewInstBefore(And, *I);
938         return UpdateValueUsesWith(I, And);
939       }
940     }
941     
942     // If the RHS is a constant, see if we can simplify it.
943     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
944     if (ShrinkDemandedConstant(I, 1, DemandedMask))
945       return UpdateValueUsesWith(I, I);
946     
947     RHSKnownZero = KnownZeroOut;
948     RHSKnownOne  = KnownOneOut;
949     break;
950   }
951   case Instruction::Select:
952     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
953                              RHSKnownZero, RHSKnownOne, Depth+1))
954       return true;
955     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
956                              LHSKnownZero, LHSKnownOne, Depth+1))
957       return true;
958     assert((RHSKnownZero & RHSKnownOne) == 0 && 
959            "Bits known to be one AND zero?"); 
960     assert((LHSKnownZero & LHSKnownOne) == 0 && 
961            "Bits known to be one AND zero?"); 
962     
963     // If the operands are constants, see if we can simplify them.
964     if (ShrinkDemandedConstant(I, 1, DemandedMask))
965       return UpdateValueUsesWith(I, I);
966     if (ShrinkDemandedConstant(I, 2, DemandedMask))
967       return UpdateValueUsesWith(I, I);
968     
969     // Only known if known in both the LHS and RHS.
970     RHSKnownOne &= LHSKnownOne;
971     RHSKnownZero &= LHSKnownZero;
972     break;
973   case Instruction::Trunc: {
974     uint32_t truncBf = 
975       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
976     DemandedMask.zext(truncBf);
977     RHSKnownZero.zext(truncBf);
978     RHSKnownOne.zext(truncBf);
979     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
980                              RHSKnownZero, RHSKnownOne, Depth+1))
981       return true;
982     DemandedMask.trunc(BitWidth);
983     RHSKnownZero.trunc(BitWidth);
984     RHSKnownOne.trunc(BitWidth);
985     assert((RHSKnownZero & RHSKnownOne) == 0 && 
986            "Bits known to be one AND zero?"); 
987     break;
988   }
989   case Instruction::BitCast:
990     if (!I->getOperand(0)->getType()->isInteger())
991       return false;
992       
993     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
994                              RHSKnownZero, RHSKnownOne, Depth+1))
995       return true;
996     assert((RHSKnownZero & RHSKnownOne) == 0 && 
997            "Bits known to be one AND zero?"); 
998     break;
999   case Instruction::ZExt: {
1000     // Compute the bits in the result that are not present in the input.
1001     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1002     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1003     
1004     DemandedMask.trunc(SrcBitWidth);
1005     RHSKnownZero.trunc(SrcBitWidth);
1006     RHSKnownOne.trunc(SrcBitWidth);
1007     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008                              RHSKnownZero, RHSKnownOne, Depth+1))
1009       return true;
1010     DemandedMask.zext(BitWidth);
1011     RHSKnownZero.zext(BitWidth);
1012     RHSKnownOne.zext(BitWidth);
1013     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1014            "Bits known to be one AND zero?"); 
1015     // The top bits are known to be zero.
1016     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1017     break;
1018   }
1019   case Instruction::SExt: {
1020     // Compute the bits in the result that are not present in the input.
1021     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1022     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1023     
1024     APInt InputDemandedBits = DemandedMask & 
1025                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1026
1027     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1028     // If any of the sign extended bits are demanded, we know that the sign
1029     // bit is demanded.
1030     if ((NewBits & DemandedMask) != 0)
1031       InputDemandedBits.set(SrcBitWidth-1);
1032       
1033     InputDemandedBits.trunc(SrcBitWidth);
1034     RHSKnownZero.trunc(SrcBitWidth);
1035     RHSKnownOne.trunc(SrcBitWidth);
1036     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1037                              RHSKnownZero, RHSKnownOne, Depth+1))
1038       return true;
1039     InputDemandedBits.zext(BitWidth);
1040     RHSKnownZero.zext(BitWidth);
1041     RHSKnownOne.zext(BitWidth);
1042     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1043            "Bits known to be one AND zero?"); 
1044       
1045     // If the sign bit of the input is known set or clear, then we know the
1046     // top bits of the result.
1047
1048     // If the input sign bit is known zero, or if the NewBits are not demanded
1049     // convert this into a zero extension.
1050     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1051     {
1052       // Convert to ZExt cast
1053       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1054       return UpdateValueUsesWith(I, NewCast);
1055     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1056       RHSKnownOne |= NewBits;
1057     }
1058     break;
1059   }
1060   case Instruction::Add: {
1061     // Figure out what the input bits are.  If the top bits of the and result
1062     // are not demanded, then the add doesn't demand them from its input
1063     // either.
1064     uint32_t NLZ = DemandedMask.countLeadingZeros();
1065       
1066     // If there is a constant on the RHS, there are a variety of xformations
1067     // we can do.
1068     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1069       // If null, this should be simplified elsewhere.  Some of the xforms here
1070       // won't work if the RHS is zero.
1071       if (RHS->isZero())
1072         break;
1073       
1074       // If the top bit of the output is demanded, demand everything from the
1075       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1076       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1077
1078       // Find information about known zero/one bits in the input.
1079       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1080                                LHSKnownZero, LHSKnownOne, Depth+1))
1081         return true;
1082
1083       // If the RHS of the add has bits set that can't affect the input, reduce
1084       // the constant.
1085       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1086         return UpdateValueUsesWith(I, I);
1087       
1088       // Avoid excess work.
1089       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1090         break;
1091       
1092       // Turn it into OR if input bits are zero.
1093       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1094         Instruction *Or =
1095           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1096                                    I->getName());
1097         InsertNewInstBefore(Or, *I);
1098         return UpdateValueUsesWith(I, Or);
1099       }
1100       
1101       // We can say something about the output known-zero and known-one bits,
1102       // depending on potential carries from the input constant and the
1103       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1104       // bits set and the RHS constant is 0x01001, then we know we have a known
1105       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1106       
1107       // To compute this, we first compute the potential carry bits.  These are
1108       // the bits which may be modified.  I'm not aware of a better way to do
1109       // this scan.
1110       const APInt& RHSVal = RHS->getValue();
1111       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1112       
1113       // Now that we know which bits have carries, compute the known-1/0 sets.
1114       
1115       // Bits are known one if they are known zero in one operand and one in the
1116       // other, and there is no input carry.
1117       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1118                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1119       
1120       // Bits are known zero if they are known zero in both operands and there
1121       // is no input carry.
1122       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1123     } else {
1124       // If the high-bits of this ADD are not demanded, then it does not demand
1125       // the high bits of its LHS or RHS.
1126       if (DemandedMask[BitWidth-1] == 0) {
1127         // Right fill the mask of bits for this ADD to demand the most
1128         // significant bit and all those below it.
1129         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1130         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1131                                  LHSKnownZero, LHSKnownOne, Depth+1))
1132           return true;
1133         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1134                                  LHSKnownZero, LHSKnownOne, Depth+1))
1135           return true;
1136       }
1137     }
1138     break;
1139   }
1140   case Instruction::Sub:
1141     // If the high-bits of this SUB are not demanded, then it does not demand
1142     // the high bits of its LHS or RHS.
1143     if (DemandedMask[BitWidth-1] == 0) {
1144       // Right fill the mask of bits for this SUB to demand the most
1145       // significant bit and all those below it.
1146       uint32_t NLZ = DemandedMask.countLeadingZeros();
1147       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1148       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1149                                LHSKnownZero, LHSKnownOne, Depth+1))
1150         return true;
1151       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1152                                LHSKnownZero, LHSKnownOne, Depth+1))
1153         return true;
1154     }
1155     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1156     // the known zeros and ones.
1157     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1158     break;
1159   case Instruction::Shl:
1160     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1162       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1163       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1164                                RHSKnownZero, RHSKnownOne, Depth+1))
1165         return true;
1166       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1167              "Bits known to be one AND zero?"); 
1168       RHSKnownZero <<= ShiftAmt;
1169       RHSKnownOne  <<= ShiftAmt;
1170       // low bits known zero.
1171       if (ShiftAmt)
1172         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1173     }
1174     break;
1175   case Instruction::LShr:
1176     // For a logical shift right
1177     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1179       
1180       // Unsigned shift right.
1181       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1182       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1183                                RHSKnownZero, RHSKnownOne, Depth+1))
1184         return true;
1185       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1186              "Bits known to be one AND zero?"); 
1187       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1188       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1189       if (ShiftAmt) {
1190         // Compute the new bits that are at the top now.
1191         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1192         RHSKnownZero |= HighBits;  // high bits known zero.
1193       }
1194     }
1195     break;
1196   case Instruction::AShr:
1197     // If this is an arithmetic shift right and only the low-bit is set, we can
1198     // always convert this into a logical shr, even if the shift amount is
1199     // variable.  The low bit of the shift cannot be an input sign bit unless
1200     // the shift amount is >= the size of the datatype, which is undefined.
1201     if (DemandedMask == 1) {
1202       // Perform the logical shift right.
1203       Value *NewVal = BinaryOperator::CreateLShr(
1204                         I->getOperand(0), I->getOperand(1), I->getName());
1205       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1206       return UpdateValueUsesWith(I, NewVal);
1207     }    
1208
1209     // If the sign bit is the only bit demanded by this ashr, then there is no
1210     // need to do it, the shift doesn't change the high bit.
1211     if (DemandedMask.isSignBit())
1212       return UpdateValueUsesWith(I, I->getOperand(0));
1213     
1214     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1216       
1217       // Signed shift right.
1218       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1219       // If any of the "high bits" are demanded, we should set the sign bit as
1220       // demanded.
1221       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1222         DemandedMaskIn.set(BitWidth-1);
1223       if (SimplifyDemandedBits(I->getOperand(0),
1224                                DemandedMaskIn,
1225                                RHSKnownZero, RHSKnownOne, Depth+1))
1226         return true;
1227       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1228              "Bits known to be one AND zero?"); 
1229       // Compute the new bits that are at the top now.
1230       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1231       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1232       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1233         
1234       // Handle the sign bits.
1235       APInt SignBit(APInt::getSignBit(BitWidth));
1236       // Adjust to where it is now in the mask.
1237       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1238         
1239       // If the input sign bit is known to be zero, or if none of the top bits
1240       // are demanded, turn this into an unsigned shift right.
1241       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1242           (HighBits & ~DemandedMask) == HighBits) {
1243         // Perform the logical shift right.
1244         Value *NewVal = BinaryOperator::CreateLShr(
1245                           I->getOperand(0), SA, I->getName());
1246         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1247         return UpdateValueUsesWith(I, NewVal);
1248       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1249         RHSKnownOne |= HighBits;
1250       }
1251     }
1252     break;
1253   case Instruction::SRem:
1254     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1255       APInt RA = Rem->getValue();
1256       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1257         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1258         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1259         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1260                                  LHSKnownZero, LHSKnownOne, Depth+1))
1261           return true;
1262
1263         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1264           LHSKnownZero |= ~LowBits;
1265         else if (LHSKnownOne[BitWidth-1])
1266           LHSKnownOne |= ~LowBits;
1267
1268         KnownZero |= LHSKnownZero & DemandedMask;
1269         KnownOne |= LHSKnownOne & DemandedMask;
1270
1271         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1272       }
1273     }
1274     break;
1275   case Instruction::URem: {
1276     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1277       APInt RA = Rem->getValue();
1278       if (RA.isPowerOf2()) {
1279         APInt LowBits = (RA - 1);
1280         APInt Mask2 = LowBits & DemandedMask;
1281         KnownZero |= ~LowBits & DemandedMask;
1282         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1283                                  KnownZero, KnownOne, Depth+1))
1284           return true;
1285
1286         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1287         break;
1288       }
1289     }
1290
1291     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1292     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1293     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1294                              KnownZero2, KnownOne2, Depth+1))
1295       return true;
1296
1297     uint32_t Leaders = KnownZero2.countLeadingOnes();
1298     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1299                              KnownZero2, KnownOne2, Depth+1))
1300       return true;
1301
1302     Leaders = std::max(Leaders,
1303                        KnownZero2.countLeadingOnes());
1304     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1305     break;
1306   }
1307   case Instruction::Call:
1308     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1309       switch (II->getIntrinsicID()) {
1310       default: break;
1311       case Intrinsic::bswap: {
1312         // If the only bits demanded come from one byte of the bswap result,
1313         // just shift the input byte into position to eliminate the bswap.
1314         unsigned NLZ = DemandedMask.countLeadingZeros();
1315         unsigned NTZ = DemandedMask.countTrailingZeros();
1316           
1317         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1318         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1319         // have 14 leading zeros, round to 8.
1320         NLZ &= ~7;
1321         NTZ &= ~7;
1322         // If we need exactly one byte, we can do this transformation.
1323         if (BitWidth-NLZ-NTZ == 8) {
1324           unsigned ResultBit = NTZ;
1325           unsigned InputBit = BitWidth-NTZ-8;
1326           
1327           // Replace this with either a left or right shift to get the byte into
1328           // the right place.
1329           Instruction *NewVal;
1330           if (InputBit > ResultBit)
1331             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1332                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1333           else
1334             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1335                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1336           NewVal->takeName(I);
1337           InsertNewInstBefore(NewVal, *I);
1338           return UpdateValueUsesWith(I, NewVal);
1339         }
1340           
1341         // TODO: Could compute known zero/one bits based on the input.
1342         break;
1343       }
1344       }
1345     }
1346     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1347     break;
1348   }
1349   
1350   // If the client is only demanding bits that we know, return the known
1351   // constant.
1352   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1353     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1354   return false;
1355 }
1356
1357
1358 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1359 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1360 /// actually used by the caller.  This method analyzes which elements of the
1361 /// operand are undef and returns that information in UndefElts.
1362 ///
1363 /// If the information about demanded elements can be used to simplify the
1364 /// operation, the operation is simplified, then the resultant value is
1365 /// returned.  This returns null if no change was made.
1366 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1367                                                 uint64_t &UndefElts,
1368                                                 unsigned Depth) {
1369   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1370   assert(VWidth <= 64 && "Vector too wide to analyze!");
1371   uint64_t EltMask = ~0ULL >> (64-VWidth);
1372   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1373          "Invalid DemandedElts!");
1374
1375   if (isa<UndefValue>(V)) {
1376     // If the entire vector is undefined, just return this info.
1377     UndefElts = EltMask;
1378     return 0;
1379   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1380     UndefElts = EltMask;
1381     return UndefValue::get(V->getType());
1382   }
1383   
1384   UndefElts = 0;
1385   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1386     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1387     Constant *Undef = UndefValue::get(EltTy);
1388
1389     std::vector<Constant*> Elts;
1390     for (unsigned i = 0; i != VWidth; ++i)
1391       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1392         Elts.push_back(Undef);
1393         UndefElts |= (1ULL << i);
1394       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1395         Elts.push_back(Undef);
1396         UndefElts |= (1ULL << i);
1397       } else {                               // Otherwise, defined.
1398         Elts.push_back(CP->getOperand(i));
1399       }
1400         
1401     // If we changed the constant, return it.
1402     Constant *NewCP = ConstantVector::get(Elts);
1403     return NewCP != CP ? NewCP : 0;
1404   } else if (isa<ConstantAggregateZero>(V)) {
1405     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1406     // set to undef.
1407     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1408     Constant *Zero = Constant::getNullValue(EltTy);
1409     Constant *Undef = UndefValue::get(EltTy);
1410     std::vector<Constant*> Elts;
1411     for (unsigned i = 0; i != VWidth; ++i)
1412       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1413     UndefElts = DemandedElts ^ EltMask;
1414     return ConstantVector::get(Elts);
1415   }
1416   
1417   if (!V->hasOneUse()) {    // Other users may use these bits.
1418     if (Depth != 0) {       // Not at the root.
1419       // TODO: Just compute the UndefElts information recursively.
1420       return false;
1421     }
1422     return false;
1423   } else if (Depth == 10) {        // Limit search depth.
1424     return false;
1425   }
1426   
1427   Instruction *I = dyn_cast<Instruction>(V);
1428   if (!I) return false;        // Only analyze instructions.
1429   
1430   bool MadeChange = false;
1431   uint64_t UndefElts2;
1432   Value *TmpV;
1433   switch (I->getOpcode()) {
1434   default: break;
1435     
1436   case Instruction::InsertElement: {
1437     // If this is a variable index, we don't know which element it overwrites.
1438     // demand exactly the same input as we produce.
1439     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1440     if (Idx == 0) {
1441       // Note that we can't propagate undef elt info, because we don't know
1442       // which elt is getting updated.
1443       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1444                                         UndefElts2, Depth+1);
1445       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1446       break;
1447     }
1448     
1449     // If this is inserting an element that isn't demanded, remove this
1450     // insertelement.
1451     unsigned IdxNo = Idx->getZExtValue();
1452     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1453       return AddSoonDeadInstToWorklist(*I, 0);
1454     
1455     // Otherwise, the element inserted overwrites whatever was there, so the
1456     // input demanded set is simpler than the output set.
1457     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1458                                       DemandedElts & ~(1ULL << IdxNo),
1459                                       UndefElts, Depth+1);
1460     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1461
1462     // The inserted element is defined.
1463     UndefElts |= 1ULL << IdxNo;
1464     break;
1465   }
1466   case Instruction::BitCast: {
1467     // Vector->vector casts only.
1468     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1469     if (!VTy) break;
1470     unsigned InVWidth = VTy->getNumElements();
1471     uint64_t InputDemandedElts = 0;
1472     unsigned Ratio;
1473
1474     if (VWidth == InVWidth) {
1475       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1476       // elements as are demanded of us.
1477       Ratio = 1;
1478       InputDemandedElts = DemandedElts;
1479     } else if (VWidth > InVWidth) {
1480       // Untested so far.
1481       break;
1482       
1483       // If there are more elements in the result than there are in the source,
1484       // then an input element is live if any of the corresponding output
1485       // elements are live.
1486       Ratio = VWidth/InVWidth;
1487       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1488         if (DemandedElts & (1ULL << OutIdx))
1489           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1490       }
1491     } else {
1492       // Untested so far.
1493       break;
1494       
1495       // If there are more elements in the source than there are in the result,
1496       // then an input element is live if the corresponding output element is
1497       // live.
1498       Ratio = InVWidth/VWidth;
1499       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1500         if (DemandedElts & (1ULL << InIdx/Ratio))
1501           InputDemandedElts |= 1ULL << InIdx;
1502     }
1503     
1504     // div/rem demand all inputs, because they don't want divide by zero.
1505     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1506                                       UndefElts2, Depth+1);
1507     if (TmpV) {
1508       I->setOperand(0, TmpV);
1509       MadeChange = true;
1510     }
1511     
1512     UndefElts = UndefElts2;
1513     if (VWidth > InVWidth) {
1514       assert(0 && "Unimp");
1515       // If there are more elements in the result than there are in the source,
1516       // then an output element is undef if the corresponding input element is
1517       // undef.
1518       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1519         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1520           UndefElts |= 1ULL << OutIdx;
1521     } else if (VWidth < InVWidth) {
1522       assert(0 && "Unimp");
1523       // If there are more elements in the source than there are in the result,
1524       // then a result element is undef if all of the corresponding input
1525       // elements are undef.
1526       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1527       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1528         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1529           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1530     }
1531     break;
1532   }
1533   case Instruction::And:
1534   case Instruction::Or:
1535   case Instruction::Xor:
1536   case Instruction::Add:
1537   case Instruction::Sub:
1538   case Instruction::Mul:
1539     // div/rem demand all inputs, because they don't want divide by zero.
1540     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1541                                       UndefElts, Depth+1);
1542     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1544                                       UndefElts2, Depth+1);
1545     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1546       
1547     // Output elements are undefined if both are undefined.  Consider things
1548     // like undef&0.  The result is known zero, not undef.
1549     UndefElts &= UndefElts2;
1550     break;
1551     
1552   case Instruction::Call: {
1553     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1554     if (!II) break;
1555     switch (II->getIntrinsicID()) {
1556     default: break;
1557       
1558     // Binary vector operations that work column-wise.  A dest element is a
1559     // function of the corresponding input elements from the two inputs.
1560     case Intrinsic::x86_sse_sub_ss:
1561     case Intrinsic::x86_sse_mul_ss:
1562     case Intrinsic::x86_sse_min_ss:
1563     case Intrinsic::x86_sse_max_ss:
1564     case Intrinsic::x86_sse2_sub_sd:
1565     case Intrinsic::x86_sse2_mul_sd:
1566     case Intrinsic::x86_sse2_min_sd:
1567     case Intrinsic::x86_sse2_max_sd:
1568       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1569                                         UndefElts, Depth+1);
1570       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1571       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1572                                         UndefElts2, Depth+1);
1573       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1574
1575       // If only the low elt is demanded and this is a scalarizable intrinsic,
1576       // scalarize it now.
1577       if (DemandedElts == 1) {
1578         switch (II->getIntrinsicID()) {
1579         default: break;
1580         case Intrinsic::x86_sse_sub_ss:
1581         case Intrinsic::x86_sse_mul_ss:
1582         case Intrinsic::x86_sse2_sub_sd:
1583         case Intrinsic::x86_sse2_mul_sd:
1584           // TODO: Lower MIN/MAX/ABS/etc
1585           Value *LHS = II->getOperand(1);
1586           Value *RHS = II->getOperand(2);
1587           // Extract the element as scalars.
1588           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1589           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1590           
1591           switch (II->getIntrinsicID()) {
1592           default: assert(0 && "Case stmts out of sync!");
1593           case Intrinsic::x86_sse_sub_ss:
1594           case Intrinsic::x86_sse2_sub_sd:
1595             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1596                                                         II->getName()), *II);
1597             break;
1598           case Intrinsic::x86_sse_mul_ss:
1599           case Intrinsic::x86_sse2_mul_sd:
1600             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1601                                                          II->getName()), *II);
1602             break;
1603           }
1604           
1605           Instruction *New =
1606             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1607                                       II->getName());
1608           InsertNewInstBefore(New, *II);
1609           AddSoonDeadInstToWorklist(*II, 0);
1610           return New;
1611         }            
1612       }
1613         
1614       // Output elements are undefined if both are undefined.  Consider things
1615       // like undef&0.  The result is known zero, not undef.
1616       UndefElts &= UndefElts2;
1617       break;
1618     }
1619     break;
1620   }
1621   }
1622   return MadeChange ? I : 0;
1623 }
1624
1625
1626 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1627 /// function is designed to check a chain of associative operators for a
1628 /// potential to apply a certain optimization.  Since the optimization may be
1629 /// applicable if the expression was reassociated, this checks the chain, then
1630 /// reassociates the expression as necessary to expose the optimization
1631 /// opportunity.  This makes use of a special Functor, which must define
1632 /// 'shouldApply' and 'apply' methods.
1633 ///
1634 template<typename Functor>
1635 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1636   unsigned Opcode = Root.getOpcode();
1637   Value *LHS = Root.getOperand(0);
1638
1639   // Quick check, see if the immediate LHS matches...
1640   if (F.shouldApply(LHS))
1641     return F.apply(Root);
1642
1643   // Otherwise, if the LHS is not of the same opcode as the root, return.
1644   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1645   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1646     // Should we apply this transform to the RHS?
1647     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1648
1649     // If not to the RHS, check to see if we should apply to the LHS...
1650     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1651       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1652       ShouldApply = true;
1653     }
1654
1655     // If the functor wants to apply the optimization to the RHS of LHSI,
1656     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1657     if (ShouldApply) {
1658       // Now all of the instructions are in the current basic block, go ahead
1659       // and perform the reassociation.
1660       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1661
1662       // First move the selected RHS to the LHS of the root...
1663       Root.setOperand(0, LHSI->getOperand(1));
1664
1665       // Make what used to be the LHS of the root be the user of the root...
1666       Value *ExtraOperand = TmpLHSI->getOperand(1);
1667       if (&Root == TmpLHSI) {
1668         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1669         return 0;
1670       }
1671       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1672       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1673       BasicBlock::iterator ARI = &Root; ++ARI;
1674       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1675       ARI = Root;
1676
1677       // Now propagate the ExtraOperand down the chain of instructions until we
1678       // get to LHSI.
1679       while (TmpLHSI != LHSI) {
1680         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1681         // Move the instruction to immediately before the chain we are
1682         // constructing to avoid breaking dominance properties.
1683         NextLHSI->moveBefore(ARI);
1684         ARI = NextLHSI;
1685
1686         Value *NextOp = NextLHSI->getOperand(1);
1687         NextLHSI->setOperand(1, ExtraOperand);
1688         TmpLHSI = NextLHSI;
1689         ExtraOperand = NextOp;
1690       }
1691
1692       // Now that the instructions are reassociated, have the functor perform
1693       // the transformation...
1694       return F.apply(Root);
1695     }
1696
1697     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1698   }
1699   return 0;
1700 }
1701
1702 namespace {
1703
1704 // AddRHS - Implements: X + X --> X << 1
1705 struct AddRHS {
1706   Value *RHS;
1707   AddRHS(Value *rhs) : RHS(rhs) {}
1708   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1709   Instruction *apply(BinaryOperator &Add) const {
1710     return BinaryOperator::CreateShl(Add.getOperand(0),
1711                                      ConstantInt::get(Add.getType(), 1));
1712   }
1713 };
1714
1715 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1716 //                 iff C1&C2 == 0
1717 struct AddMaskingAnd {
1718   Constant *C2;
1719   AddMaskingAnd(Constant *c) : C2(c) {}
1720   bool shouldApply(Value *LHS) const {
1721     ConstantInt *C1;
1722     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1723            ConstantExpr::getAnd(C1, C2)->isNullValue();
1724   }
1725   Instruction *apply(BinaryOperator &Add) const {
1726     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1727   }
1728 };
1729
1730 }
1731
1732 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1733                                              InstCombiner *IC) {
1734   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1735     if (Constant *SOC = dyn_cast<Constant>(SO))
1736       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1737
1738     return IC->InsertNewInstBefore(CastInst::Create(
1739           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1740   }
1741
1742   // Figure out if the constant is the left or the right argument.
1743   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1744   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1745
1746   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1747     if (ConstIsRHS)
1748       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1749     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1750   }
1751
1752   Value *Op0 = SO, *Op1 = ConstOperand;
1753   if (!ConstIsRHS)
1754     std::swap(Op0, Op1);
1755   Instruction *New;
1756   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1757     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1758   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1759     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1760                           SO->getName()+".cmp");
1761   else {
1762     assert(0 && "Unknown binary instruction type!");
1763     abort();
1764   }
1765   return IC->InsertNewInstBefore(New, I);
1766 }
1767
1768 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1769 // constant as the other operand, try to fold the binary operator into the
1770 // select arguments.  This also works for Cast instructions, which obviously do
1771 // not have a second operand.
1772 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1773                                      InstCombiner *IC) {
1774   // Don't modify shared select instructions
1775   if (!SI->hasOneUse()) return 0;
1776   Value *TV = SI->getOperand(1);
1777   Value *FV = SI->getOperand(2);
1778
1779   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1780     // Bool selects with constant operands can be folded to logical ops.
1781     if (SI->getType() == Type::Int1Ty) return 0;
1782
1783     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1784     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1785
1786     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1787                               SelectFalseVal);
1788   }
1789   return 0;
1790 }
1791
1792
1793 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1794 /// node as operand #0, see if we can fold the instruction into the PHI (which
1795 /// is only possible if all operands to the PHI are constants).
1796 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1797   PHINode *PN = cast<PHINode>(I.getOperand(0));
1798   unsigned NumPHIValues = PN->getNumIncomingValues();
1799   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1800
1801   // Check to see if all of the operands of the PHI are constants.  If there is
1802   // one non-constant value, remember the BB it is.  If there is more than one
1803   // or if *it* is a PHI, bail out.
1804   BasicBlock *NonConstBB = 0;
1805   for (unsigned i = 0; i != NumPHIValues; ++i)
1806     if (!isa<Constant>(PN->getIncomingValue(i))) {
1807       if (NonConstBB) return 0;  // More than one non-const value.
1808       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1809       NonConstBB = PN->getIncomingBlock(i);
1810       
1811       // If the incoming non-constant value is in I's block, we have an infinite
1812       // loop.
1813       if (NonConstBB == I.getParent())
1814         return 0;
1815     }
1816   
1817   // If there is exactly one non-constant value, we can insert a copy of the
1818   // operation in that block.  However, if this is a critical edge, we would be
1819   // inserting the computation one some other paths (e.g. inside a loop).  Only
1820   // do this if the pred block is unconditionally branching into the phi block.
1821   if (NonConstBB) {
1822     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1823     if (!BI || !BI->isUnconditional()) return 0;
1824   }
1825
1826   // Okay, we can do the transformation: create the new PHI node.
1827   PHINode *NewPN = PHINode::Create(I.getType(), "");
1828   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1829   InsertNewInstBefore(NewPN, *PN);
1830   NewPN->takeName(PN);
1831
1832   // Next, add all of the operands to the PHI.
1833   if (I.getNumOperands() == 2) {
1834     Constant *C = cast<Constant>(I.getOperand(1));
1835     for (unsigned i = 0; i != NumPHIValues; ++i) {
1836       Value *InV = 0;
1837       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1838         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1839           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1840         else
1841           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1842       } else {
1843         assert(PN->getIncomingBlock(i) == NonConstBB);
1844         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1845           InV = BinaryOperator::Create(BO->getOpcode(),
1846                                        PN->getIncomingValue(i), C, "phitmp",
1847                                        NonConstBB->getTerminator());
1848         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1849           InV = CmpInst::Create(CI->getOpcode(), 
1850                                 CI->getPredicate(),
1851                                 PN->getIncomingValue(i), C, "phitmp",
1852                                 NonConstBB->getTerminator());
1853         else
1854           assert(0 && "Unknown binop!");
1855         
1856         AddToWorkList(cast<Instruction>(InV));
1857       }
1858       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1859     }
1860   } else { 
1861     CastInst *CI = cast<CastInst>(&I);
1862     const Type *RetTy = CI->getType();
1863     for (unsigned i = 0; i != NumPHIValues; ++i) {
1864       Value *InV;
1865       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1866         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1867       } else {
1868         assert(PN->getIncomingBlock(i) == NonConstBB);
1869         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1870                                I.getType(), "phitmp", 
1871                                NonConstBB->getTerminator());
1872         AddToWorkList(cast<Instruction>(InV));
1873       }
1874       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1875     }
1876   }
1877   return ReplaceInstUsesWith(I, NewPN);
1878 }
1879
1880
1881 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1882 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1883 /// This basically requires proving that the add in the original type would not
1884 /// overflow to change the sign bit or have a carry out.
1885 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1886   // There are different heuristics we can use for this.  Here are some simple
1887   // ones.
1888   
1889   // Add has the property that adding any two 2's complement numbers can only 
1890   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1891   // have at least two sign bits, we know that the addition of the two values will
1892   // sign extend fine.
1893   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1894     return true;
1895   
1896   
1897   // If one of the operands only has one non-zero bit, and if the other operand
1898   // has a known-zero bit in a more significant place than it (not including the
1899   // sign bit) the ripple may go up to and fill the zero, but won't change the
1900   // sign.  For example, (X & ~4) + 1.
1901   
1902   // TODO: Implement.
1903   
1904   return false;
1905 }
1906
1907
1908 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1909   bool Changed = SimplifyCommutative(I);
1910   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1911
1912   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1913     // X + undef -> undef
1914     if (isa<UndefValue>(RHS))
1915       return ReplaceInstUsesWith(I, RHS);
1916
1917     // X + 0 --> X
1918     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1919       if (RHSC->isNullValue())
1920         return ReplaceInstUsesWith(I, LHS);
1921     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1922       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1923                               (I.getType())->getValueAPF()))
1924         return ReplaceInstUsesWith(I, LHS);
1925     }
1926
1927     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1928       // X + (signbit) --> X ^ signbit
1929       const APInt& Val = CI->getValue();
1930       uint32_t BitWidth = Val.getBitWidth();
1931       if (Val == APInt::getSignBit(BitWidth))
1932         return BinaryOperator::CreateXor(LHS, RHS);
1933       
1934       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1935       // (X & 254)+1 -> (X&254)|1
1936       if (!isa<VectorType>(I.getType())) {
1937         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1938         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1939                                  KnownZero, KnownOne))
1940           return &I;
1941       }
1942     }
1943
1944     if (isa<PHINode>(LHS))
1945       if (Instruction *NV = FoldOpIntoPhi(I))
1946         return NV;
1947     
1948     ConstantInt *XorRHS = 0;
1949     Value *XorLHS = 0;
1950     if (isa<ConstantInt>(RHSC) &&
1951         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1952       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1953       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1954       
1955       uint32_t Size = TySizeBits / 2;
1956       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1957       APInt CFF80Val(-C0080Val);
1958       do {
1959         if (TySizeBits > Size) {
1960           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1961           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1962           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1963               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1964             // This is a sign extend if the top bits are known zero.
1965             if (!MaskedValueIsZero(XorLHS, 
1966                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1967               Size = 0;  // Not a sign ext, but can't be any others either.
1968             break;
1969           }
1970         }
1971         Size >>= 1;
1972         C0080Val = APIntOps::lshr(C0080Val, Size);
1973         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1974       } while (Size >= 1);
1975       
1976       // FIXME: This shouldn't be necessary. When the backends can handle types
1977       // with funny bit widths then this switch statement should be removed. It
1978       // is just here to get the size of the "middle" type back up to something
1979       // that the back ends can handle.
1980       const Type *MiddleType = 0;
1981       switch (Size) {
1982         default: break;
1983         case 32: MiddleType = Type::Int32Ty; break;
1984         case 16: MiddleType = Type::Int16Ty; break;
1985         case  8: MiddleType = Type::Int8Ty; break;
1986       }
1987       if (MiddleType) {
1988         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1989         InsertNewInstBefore(NewTrunc, I);
1990         return new SExtInst(NewTrunc, I.getType(), I.getName());
1991       }
1992     }
1993   }
1994
1995   if (I.getType() == Type::Int1Ty)
1996     return BinaryOperator::CreateXor(LHS, RHS);
1997
1998   // X + X --> X << 1
1999   if (I.getType()->isInteger()) {
2000     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2001
2002     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2003       if (RHSI->getOpcode() == Instruction::Sub)
2004         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2005           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2006     }
2007     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2008       if (LHSI->getOpcode() == Instruction::Sub)
2009         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2010           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2011     }
2012   }
2013
2014   // -A + B  -->  B - A
2015   // -A + -B  -->  -(A + B)
2016   if (Value *LHSV = dyn_castNegVal(LHS)) {
2017     if (LHS->getType()->isIntOrIntVector()) {
2018       if (Value *RHSV = dyn_castNegVal(RHS)) {
2019         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2020         InsertNewInstBefore(NewAdd, I);
2021         return BinaryOperator::CreateNeg(NewAdd);
2022       }
2023     }
2024     
2025     return BinaryOperator::CreateSub(RHS, LHSV);
2026   }
2027
2028   // A + -B  -->  A - B
2029   if (!isa<Constant>(RHS))
2030     if (Value *V = dyn_castNegVal(RHS))
2031       return BinaryOperator::CreateSub(LHS, V);
2032
2033
2034   ConstantInt *C2;
2035   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2036     if (X == RHS)   // X*C + X --> X * (C+1)
2037       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2038
2039     // X*C1 + X*C2 --> X * (C1+C2)
2040     ConstantInt *C1;
2041     if (X == dyn_castFoldableMul(RHS, C1))
2042       return BinaryOperator::CreateMul(X, Add(C1, C2));
2043   }
2044
2045   // X + X*C --> X * (C+1)
2046   if (dyn_castFoldableMul(RHS, C2) == LHS)
2047     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2048
2049   // X + ~X --> -1   since   ~X = -X-1
2050   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2051     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2052   
2053
2054   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2055   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2056     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2057       return R;
2058   
2059   // A+B --> A|B iff A and B have no bits set in common.
2060   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2061     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2062     APInt LHSKnownOne(IT->getBitWidth(), 0);
2063     APInt LHSKnownZero(IT->getBitWidth(), 0);
2064     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2065     if (LHSKnownZero != 0) {
2066       APInt RHSKnownOne(IT->getBitWidth(), 0);
2067       APInt RHSKnownZero(IT->getBitWidth(), 0);
2068       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2069       
2070       // No bits in common -> bitwise or.
2071       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2072         return BinaryOperator::CreateOr(LHS, RHS);
2073     }
2074   }
2075
2076   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2077   if (I.getType()->isIntOrIntVector()) {
2078     Value *W, *X, *Y, *Z;
2079     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2080         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2081       if (W != Y) {
2082         if (W == Z) {
2083           std::swap(Y, Z);
2084         } else if (Y == X) {
2085           std::swap(W, X);
2086         } else if (X == Z) {
2087           std::swap(Y, Z);
2088           std::swap(W, X);
2089         }
2090       }
2091
2092       if (W == Y) {
2093         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2094                                                             LHS->getName()), I);
2095         return BinaryOperator::CreateMul(W, NewAdd);
2096       }
2097     }
2098   }
2099
2100   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2101     Value *X = 0;
2102     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2103       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2104
2105     // (X & FF00) + xx00  -> (X+xx00) & FF00
2106     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2107       Constant *Anded = And(CRHS, C2);
2108       if (Anded == CRHS) {
2109         // See if all bits from the first bit set in the Add RHS up are included
2110         // in the mask.  First, get the rightmost bit.
2111         const APInt& AddRHSV = CRHS->getValue();
2112
2113         // Form a mask of all bits from the lowest bit added through the top.
2114         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2115
2116         // See if the and mask includes all of these bits.
2117         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2118
2119         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2120           // Okay, the xform is safe.  Insert the new add pronto.
2121           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2122                                                             LHS->getName()), I);
2123           return BinaryOperator::CreateAnd(NewAdd, C2);
2124         }
2125       }
2126     }
2127
2128     // Try to fold constant add into select arguments.
2129     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2130       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2131         return R;
2132   }
2133
2134   // add (cast *A to intptrtype) B -> 
2135   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2136   {
2137     CastInst *CI = dyn_cast<CastInst>(LHS);
2138     Value *Other = RHS;
2139     if (!CI) {
2140       CI = dyn_cast<CastInst>(RHS);
2141       Other = LHS;
2142     }
2143     if (CI && CI->getType()->isSized() && 
2144         (CI->getType()->getPrimitiveSizeInBits() == 
2145          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2146         && isa<PointerType>(CI->getOperand(0)->getType())) {
2147       unsigned AS =
2148         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2149       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2150                                       PointerType::get(Type::Int8Ty, AS), I);
2151       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2152       return new PtrToIntInst(I2, CI->getType());
2153     }
2154   }
2155   
2156   // add (select X 0 (sub n A)) A  -->  select X A n
2157   {
2158     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2159     Value *Other = RHS;
2160     if (!SI) {
2161       SI = dyn_cast<SelectInst>(RHS);
2162       Other = LHS;
2163     }
2164     if (SI && SI->hasOneUse()) {
2165       Value *TV = SI->getTrueValue();
2166       Value *FV = SI->getFalseValue();
2167       Value *A, *N;
2168
2169       // Can we fold the add into the argument of the select?
2170       // We check both true and false select arguments for a matching subtract.
2171       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2172           A == Other)  // Fold the add into the true select value.
2173         return SelectInst::Create(SI->getCondition(), N, A);
2174       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2175           A == Other)  // Fold the add into the false select value.
2176         return SelectInst::Create(SI->getCondition(), A, N);
2177     }
2178   }
2179   
2180   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2181   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2182     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2183       return ReplaceInstUsesWith(I, LHS);
2184
2185   // Check for (add (sext x), y), see if we can merge this into an
2186   // integer add followed by a sext.
2187   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2188     // (add (sext x), cst) --> (sext (add x, cst'))
2189     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2190       Constant *CI = 
2191         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2192       if (LHSConv->hasOneUse() &&
2193           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2194           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2195         // Insert the new, smaller add.
2196         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2197                                                         CI, "addconv");
2198         InsertNewInstBefore(NewAdd, I);
2199         return new SExtInst(NewAdd, I.getType());
2200       }
2201     }
2202     
2203     // (add (sext x), (sext y)) --> (sext (add int x, y))
2204     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2205       // Only do this if x/y have the same type, if at last one of them has a
2206       // single use (so we don't increase the number of sexts), and if the
2207       // integer add will not overflow.
2208       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2209           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2210           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2211                                    RHSConv->getOperand(0))) {
2212         // Insert the new integer add.
2213         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2214                                                         RHSConv->getOperand(0),
2215                                                         "addconv");
2216         InsertNewInstBefore(NewAdd, I);
2217         return new SExtInst(NewAdd, I.getType());
2218       }
2219     }
2220   }
2221   
2222   // Check for (add double (sitofp x), y), see if we can merge this into an
2223   // integer add followed by a promotion.
2224   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2225     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2226     // ... if the constant fits in the integer value.  This is useful for things
2227     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2228     // requires a constant pool load, and generally allows the add to be better
2229     // instcombined.
2230     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2231       Constant *CI = 
2232       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2233       if (LHSConv->hasOneUse() &&
2234           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2235           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2236         // Insert the new integer add.
2237         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2238                                                         CI, "addconv");
2239         InsertNewInstBefore(NewAdd, I);
2240         return new SIToFPInst(NewAdd, I.getType());
2241       }
2242     }
2243     
2244     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2245     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2246       // Only do this if x/y have the same type, if at last one of them has a
2247       // single use (so we don't increase the number of int->fp conversions),
2248       // and if the integer add will not overflow.
2249       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2250           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2251           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2252                                    RHSConv->getOperand(0))) {
2253         // Insert the new integer add.
2254         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2255                                                         RHSConv->getOperand(0),
2256                                                         "addconv");
2257         InsertNewInstBefore(NewAdd, I);
2258         return new SIToFPInst(NewAdd, I.getType());
2259       }
2260     }
2261   }
2262   
2263   return Changed ? &I : 0;
2264 }
2265
2266 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2267   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2268
2269   if (Op0 == Op1)         // sub X, X  -> 0
2270     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2271
2272   // If this is a 'B = x-(-A)', change to B = x+A...
2273   if (Value *V = dyn_castNegVal(Op1))
2274     return BinaryOperator::CreateAdd(Op0, V);
2275
2276   if (isa<UndefValue>(Op0))
2277     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2278   if (isa<UndefValue>(Op1))
2279     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2280
2281   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2282     // Replace (-1 - A) with (~A)...
2283     if (C->isAllOnesValue())
2284       return BinaryOperator::CreateNot(Op1);
2285
2286     // C - ~X == X + (1+C)
2287     Value *X = 0;
2288     if (match(Op1, m_Not(m_Value(X))))
2289       return BinaryOperator::CreateAdd(X, AddOne(C));
2290
2291     // -(X >>u 31) -> (X >>s 31)
2292     // -(X >>s 31) -> (X >>u 31)
2293     if (C->isZero()) {
2294       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2295         if (SI->getOpcode() == Instruction::LShr) {
2296           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2297             // Check to see if we are shifting out everything but the sign bit.
2298             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2299                 SI->getType()->getPrimitiveSizeInBits()-1) {
2300               // Ok, the transformation is safe.  Insert AShr.
2301               return BinaryOperator::Create(Instruction::AShr, 
2302                                           SI->getOperand(0), CU, SI->getName());
2303             }
2304           }
2305         }
2306         else if (SI->getOpcode() == Instruction::AShr) {
2307           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2308             // Check to see if we are shifting out everything but the sign bit.
2309             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2310                 SI->getType()->getPrimitiveSizeInBits()-1) {
2311               // Ok, the transformation is safe.  Insert LShr. 
2312               return BinaryOperator::CreateLShr(
2313                                           SI->getOperand(0), CU, SI->getName());
2314             }
2315           }
2316         }
2317       }
2318     }
2319
2320     // Try to fold constant sub into select arguments.
2321     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2322       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2323         return R;
2324
2325     if (isa<PHINode>(Op0))
2326       if (Instruction *NV = FoldOpIntoPhi(I))
2327         return NV;
2328   }
2329
2330   if (I.getType() == Type::Int1Ty)
2331     return BinaryOperator::CreateXor(Op0, Op1);
2332
2333   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2334     if (Op1I->getOpcode() == Instruction::Add &&
2335         !Op0->getType()->isFPOrFPVector()) {
2336       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2337         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2338       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2339         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2340       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2341         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2342           // C1-(X+C2) --> (C1-C2)-X
2343           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2344                                            Op1I->getOperand(0));
2345       }
2346     }
2347
2348     if (Op1I->hasOneUse()) {
2349       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2350       // is not used by anyone else...
2351       //
2352       if (Op1I->getOpcode() == Instruction::Sub &&
2353           !Op1I->getType()->isFPOrFPVector()) {
2354         // Swap the two operands of the subexpr...
2355         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2356         Op1I->setOperand(0, IIOp1);
2357         Op1I->setOperand(1, IIOp0);
2358
2359         // Create the new top level add instruction...
2360         return BinaryOperator::CreateAdd(Op0, Op1);
2361       }
2362
2363       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2364       //
2365       if (Op1I->getOpcode() == Instruction::And &&
2366           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2367         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2368
2369         Value *NewNot =
2370           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2371         return BinaryOperator::CreateAnd(Op0, NewNot);
2372       }
2373
2374       // 0 - (X sdiv C)  -> (X sdiv -C)
2375       if (Op1I->getOpcode() == Instruction::SDiv)
2376         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2377           if (CSI->isZero())
2378             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2379               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2380                                                ConstantExpr::getNeg(DivRHS));
2381
2382       // X - X*C --> X * (1-C)
2383       ConstantInt *C2 = 0;
2384       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2385         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2386         return BinaryOperator::CreateMul(Op0, CP1);
2387       }
2388
2389       // X - ((X / Y) * Y) --> X % Y
2390       if (Op1I->getOpcode() == Instruction::Mul)
2391         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2392           if (Op0 == I->getOperand(0) &&
2393               Op1I->getOperand(1) == I->getOperand(1)) {
2394             if (I->getOpcode() == Instruction::SDiv)
2395               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2396             if (I->getOpcode() == Instruction::UDiv)
2397               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2398           }
2399     }
2400   }
2401
2402   if (!Op0->getType()->isFPOrFPVector())
2403     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2404       if (Op0I->getOpcode() == Instruction::Add) {
2405         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2406           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2407         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2408           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2409       } else if (Op0I->getOpcode() == Instruction::Sub) {
2410         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2411           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2412       }
2413     }
2414
2415   ConstantInt *C1;
2416   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2417     if (X == Op1)  // X*C - X --> X * (C-1)
2418       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2419
2420     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2421     if (X == dyn_castFoldableMul(Op1, C2))
2422       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2423   }
2424   return 0;
2425 }
2426
2427 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2428 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2429 /// TrueIfSigned if the result of the comparison is true when the input value is
2430 /// signed.
2431 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2432                            bool &TrueIfSigned) {
2433   switch (pred) {
2434   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2435     TrueIfSigned = true;
2436     return RHS->isZero();
2437   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2438     TrueIfSigned = true;
2439     return RHS->isAllOnesValue();
2440   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2441     TrueIfSigned = false;
2442     return RHS->isAllOnesValue();
2443   case ICmpInst::ICMP_UGT:
2444     // True if LHS u> RHS and RHS == high-bit-mask - 1
2445     TrueIfSigned = true;
2446     return RHS->getValue() ==
2447       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2448   case ICmpInst::ICMP_UGE: 
2449     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2450     TrueIfSigned = true;
2451     return RHS->getValue().isSignBit();
2452   default:
2453     return false;
2454   }
2455 }
2456
2457 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2458   bool Changed = SimplifyCommutative(I);
2459   Value *Op0 = I.getOperand(0);
2460
2461   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2462     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2463
2464   // Simplify mul instructions with a constant RHS...
2465   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2466     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2467
2468       // ((X << C1)*C2) == (X * (C2 << C1))
2469       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2470         if (SI->getOpcode() == Instruction::Shl)
2471           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2472             return BinaryOperator::CreateMul(SI->getOperand(0),
2473                                              ConstantExpr::getShl(CI, ShOp));
2474
2475       if (CI->isZero())
2476         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2477       if (CI->equalsInt(1))                  // X * 1  == X
2478         return ReplaceInstUsesWith(I, Op0);
2479       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2480         return BinaryOperator::CreateNeg(Op0, I.getName());
2481
2482       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2483       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2484         return BinaryOperator::CreateShl(Op0,
2485                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2486       }
2487     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2488       if (Op1F->isNullValue())
2489         return ReplaceInstUsesWith(I, Op1);
2490
2491       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2492       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2493       // We need a better interface for long double here.
2494       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2495         if (Op1F->isExactlyValue(1.0))
2496           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2497     }
2498     
2499     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2500       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2501           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2502         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2503         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2504                                                      Op1, "tmp");
2505         InsertNewInstBefore(Add, I);
2506         Value *C1C2 = ConstantExpr::getMul(Op1, 
2507                                            cast<Constant>(Op0I->getOperand(1)));
2508         return BinaryOperator::CreateAdd(Add, C1C2);
2509         
2510       }
2511
2512     // Try to fold constant mul into select arguments.
2513     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2514       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2515         return R;
2516
2517     if (isa<PHINode>(Op0))
2518       if (Instruction *NV = FoldOpIntoPhi(I))
2519         return NV;
2520   }
2521
2522   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2523     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2524       return BinaryOperator::CreateMul(Op0v, Op1v);
2525
2526   if (I.getType() == Type::Int1Ty)
2527     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2528
2529   // If one of the operands of the multiply is a cast from a boolean value, then
2530   // we know the bool is either zero or one, so this is a 'masking' multiply.
2531   // See if we can simplify things based on how the boolean was originally
2532   // formed.
2533   CastInst *BoolCast = 0;
2534   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2535     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2536       BoolCast = CI;
2537   if (!BoolCast)
2538     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2539       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2540         BoolCast = CI;
2541   if (BoolCast) {
2542     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2543       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2544       const Type *SCOpTy = SCIOp0->getType();
2545       bool TIS = false;
2546       
2547       // If the icmp is true iff the sign bit of X is set, then convert this
2548       // multiply into a shift/and combination.
2549       if (isa<ConstantInt>(SCIOp1) &&
2550           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2551           TIS) {
2552         // Shift the X value right to turn it into "all signbits".
2553         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2554                                           SCOpTy->getPrimitiveSizeInBits()-1);
2555         Value *V =
2556           InsertNewInstBefore(
2557             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2558                                             BoolCast->getOperand(0)->getName()+
2559                                             ".mask"), I);
2560
2561         // If the multiply type is not the same as the source type, sign extend
2562         // or truncate to the multiply type.
2563         if (I.getType() != V->getType()) {
2564           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2565           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2566           Instruction::CastOps opcode = 
2567             (SrcBits == DstBits ? Instruction::BitCast : 
2568              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2569           V = InsertCastBefore(opcode, V, I.getType(), I);
2570         }
2571
2572         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2573         return BinaryOperator::CreateAnd(V, OtherOp);
2574       }
2575     }
2576   }
2577
2578   return Changed ? &I : 0;
2579 }
2580
2581 /// This function implements the transforms on div instructions that work
2582 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2583 /// used by the visitors to those instructions.
2584 /// @brief Transforms common to all three div instructions
2585 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2586   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2587
2588   // undef / X -> 0        for integer.
2589   // undef / X -> undef    for FP (the undef could be a snan).
2590   if (isa<UndefValue>(Op0)) {
2591     if (Op0->getType()->isFPOrFPVector())
2592       return ReplaceInstUsesWith(I, Op0);
2593     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2594   }
2595
2596   // X / undef -> undef
2597   if (isa<UndefValue>(Op1))
2598     return ReplaceInstUsesWith(I, Op1);
2599
2600   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2601   // This does not apply for fdiv.
2602   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2603     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2604     // the same basic block, then we replace the select with Y, and the
2605     // condition of the select with false (if the cond value is in the same BB).
2606     // If the select has uses other than the div, this allows them to be
2607     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2608     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2609       if (ST->isNullValue()) {
2610         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2611         if (CondI && CondI->getParent() == I.getParent())
2612           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2613         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2614           I.setOperand(1, SI->getOperand(2));
2615         else
2616           UpdateValueUsesWith(SI, SI->getOperand(2));
2617         return &I;
2618       }
2619
2620     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2621     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2622       if (ST->isNullValue()) {
2623         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2624         if (CondI && CondI->getParent() == I.getParent())
2625           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2626         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2627           I.setOperand(1, SI->getOperand(1));
2628         else
2629           UpdateValueUsesWith(SI, SI->getOperand(1));
2630         return &I;
2631       }
2632   }
2633
2634   return 0;
2635 }
2636
2637 /// This function implements the transforms common to both integer division
2638 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2639 /// division instructions.
2640 /// @brief Common integer divide transforms
2641 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2642   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2643
2644   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2645   if (Op0 == Op1) {
2646     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2647       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2648       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2649       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2650     }
2651
2652     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2653     return ReplaceInstUsesWith(I, CI);
2654   }
2655   
2656   if (Instruction *Common = commonDivTransforms(I))
2657     return Common;
2658
2659   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2660     // div X, 1 == X
2661     if (RHS->equalsInt(1))
2662       return ReplaceInstUsesWith(I, Op0);
2663
2664     // (X / C1) / C2  -> X / (C1*C2)
2665     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2666       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2667         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2668           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2669             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2670           else 
2671             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2672                                           Multiply(RHS, LHSRHS));
2673         }
2674
2675     if (!RHS->isZero()) { // avoid X udiv 0
2676       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2677         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2678           return R;
2679       if (isa<PHINode>(Op0))
2680         if (Instruction *NV = FoldOpIntoPhi(I))
2681           return NV;
2682     }
2683   }
2684
2685   // 0 / X == 0, we don't need to preserve faults!
2686   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2687     if (LHS->equalsInt(0))
2688       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2689
2690   // It can't be division by zero, hence it must be division by one.
2691   if (I.getType() == Type::Int1Ty)
2692     return ReplaceInstUsesWith(I, Op0);
2693
2694   return 0;
2695 }
2696
2697 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2698   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2699
2700   // Handle the integer div common cases
2701   if (Instruction *Common = commonIDivTransforms(I))
2702     return Common;
2703
2704   // X udiv C^2 -> X >> C
2705   // Check to see if this is an unsigned division with an exact power of 2,
2706   // if so, convert to a right shift.
2707   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2708     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2709       return BinaryOperator::CreateLShr(Op0, 
2710                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2711   }
2712
2713   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2714   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2715     if (RHSI->getOpcode() == Instruction::Shl &&
2716         isa<ConstantInt>(RHSI->getOperand(0))) {
2717       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2718       if (C1.isPowerOf2()) {
2719         Value *N = RHSI->getOperand(1);
2720         const Type *NTy = N->getType();
2721         if (uint32_t C2 = C1.logBase2()) {
2722           Constant *C2V = ConstantInt::get(NTy, C2);
2723           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2724         }
2725         return BinaryOperator::CreateLShr(Op0, N);
2726       }
2727     }
2728   }
2729   
2730   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2731   // where C1&C2 are powers of two.
2732   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2733     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2734       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2735         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2736         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2737           // Compute the shift amounts
2738           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2739           // Construct the "on true" case of the select
2740           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2741           Instruction *TSI = BinaryOperator::CreateLShr(
2742                                                  Op0, TC, SI->getName()+".t");
2743           TSI = InsertNewInstBefore(TSI, I);
2744   
2745           // Construct the "on false" case of the select
2746           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2747           Instruction *FSI = BinaryOperator::CreateLShr(
2748                                                  Op0, FC, SI->getName()+".f");
2749           FSI = InsertNewInstBefore(FSI, I);
2750
2751           // construct the select instruction and return it.
2752           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2753         }
2754       }
2755   return 0;
2756 }
2757
2758 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2759   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2760
2761   // Handle the integer div common cases
2762   if (Instruction *Common = commonIDivTransforms(I))
2763     return Common;
2764
2765   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2766     // sdiv X, -1 == -X
2767     if (RHS->isAllOnesValue())
2768       return BinaryOperator::CreateNeg(Op0);
2769
2770     // -X/C -> X/-C
2771     if (Value *LHSNeg = dyn_castNegVal(Op0))
2772       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2773   }
2774
2775   // If the sign bits of both operands are zero (i.e. we can prove they are
2776   // unsigned inputs), turn this into a udiv.
2777   if (I.getType()->isInteger()) {
2778     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2779     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2780       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2781       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2782     }
2783   }      
2784   
2785   return 0;
2786 }
2787
2788 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2789   return commonDivTransforms(I);
2790 }
2791
2792 /// This function implements the transforms on rem instructions that work
2793 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2794 /// is used by the visitors to those instructions.
2795 /// @brief Transforms common to all three rem instructions
2796 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2797   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2798
2799   // 0 % X == 0 for integer, we don't need to preserve faults!
2800   if (Constant *LHS = dyn_cast<Constant>(Op0))
2801     if (LHS->isNullValue())
2802       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2803
2804   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2805     if (I.getType()->isFPOrFPVector())
2806       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2807     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2808   }
2809   if (isa<UndefValue>(Op1))
2810     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2811
2812   // Handle cases involving: rem X, (select Cond, Y, Z)
2813   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2814     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2815     // the same basic block, then we replace the select with Y, and the
2816     // condition of the select with false (if the cond value is in the same
2817     // BB).  If the select has uses other than the div, this allows them to be
2818     // simplified also.
2819     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2820       if (ST->isNullValue()) {
2821         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2822         if (CondI && CondI->getParent() == I.getParent())
2823           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2824         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2825           I.setOperand(1, SI->getOperand(2));
2826         else
2827           UpdateValueUsesWith(SI, SI->getOperand(2));
2828         return &I;
2829       }
2830     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2831     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2832       if (ST->isNullValue()) {
2833         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2834         if (CondI && CondI->getParent() == I.getParent())
2835           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2836         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2837           I.setOperand(1, SI->getOperand(1));
2838         else
2839           UpdateValueUsesWith(SI, SI->getOperand(1));
2840         return &I;
2841       }
2842   }
2843
2844   return 0;
2845 }
2846
2847 /// This function implements the transforms common to both integer remainder
2848 /// instructions (urem and srem). It is called by the visitors to those integer
2849 /// remainder instructions.
2850 /// @brief Common integer remainder transforms
2851 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2852   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2853
2854   if (Instruction *common = commonRemTransforms(I))
2855     return common;
2856
2857   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2858     // X % 0 == undef, we don't need to preserve faults!
2859     if (RHS->equalsInt(0))
2860       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2861     
2862     if (RHS->equalsInt(1))  // X % 1 == 0
2863       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2864
2865     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2866       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2867         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2868           return R;
2869       } else if (isa<PHINode>(Op0I)) {
2870         if (Instruction *NV = FoldOpIntoPhi(I))
2871           return NV;
2872       }
2873
2874       // See if we can fold away this rem instruction.
2875       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2876       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2877       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2878                                KnownZero, KnownOne))
2879         return &I;
2880     }
2881   }
2882
2883   return 0;
2884 }
2885
2886 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2887   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2888
2889   if (Instruction *common = commonIRemTransforms(I))
2890     return common;
2891   
2892   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2893     // X urem C^2 -> X and C
2894     // Check to see if this is an unsigned remainder with an exact power of 2,
2895     // if so, convert to a bitwise and.
2896     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2897       if (C->getValue().isPowerOf2())
2898         return BinaryOperator::CreateAnd(Op0, SubOne(C));
2899   }
2900
2901   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2902     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2903     if (RHSI->getOpcode() == Instruction::Shl &&
2904         isa<ConstantInt>(RHSI->getOperand(0))) {
2905       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2906         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2907         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2908                                                                    "tmp"), I);
2909         return BinaryOperator::CreateAnd(Op0, Add);
2910       }
2911     }
2912   }
2913
2914   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2915   // where C1&C2 are powers of two.
2916   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2917     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2918       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2919         // STO == 0 and SFO == 0 handled above.
2920         if ((STO->getValue().isPowerOf2()) && 
2921             (SFO->getValue().isPowerOf2())) {
2922           Value *TrueAnd = InsertNewInstBefore(
2923             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2924           Value *FalseAnd = InsertNewInstBefore(
2925             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2926           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2927         }
2928       }
2929   }
2930   
2931   return 0;
2932 }
2933
2934 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2935   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2936
2937   // Handle the integer rem common cases
2938   if (Instruction *common = commonIRemTransforms(I))
2939     return common;
2940   
2941   if (Value *RHSNeg = dyn_castNegVal(Op1))
2942     if (!isa<ConstantInt>(RHSNeg) || 
2943         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2944       // X % -Y -> X % Y
2945       AddUsesToWorkList(I);
2946       I.setOperand(1, RHSNeg);
2947       return &I;
2948     }
2949  
2950   // If the sign bits of both operands are zero (i.e. we can prove they are
2951   // unsigned inputs), turn this into a urem.
2952   if (I.getType()->isInteger()) {
2953     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2954     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2955       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2956       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2957     }
2958   }
2959
2960   return 0;
2961 }
2962
2963 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2964   return commonRemTransforms(I);
2965 }
2966
2967 // isOneBitSet - Return true if there is exactly one bit set in the specified
2968 // constant.
2969 static bool isOneBitSet(const ConstantInt *CI) {
2970   return CI->getValue().isPowerOf2();
2971 }
2972
2973 // isHighOnes - Return true if the constant is of the form 1+0+.
2974 // This is the same as lowones(~X).
2975 static bool isHighOnes(const ConstantInt *CI) {
2976   return (~CI->getValue() + 1).isPowerOf2();
2977 }
2978
2979 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2980 /// are carefully arranged to allow folding of expressions such as:
2981 ///
2982 ///      (A < B) | (A > B) --> (A != B)
2983 ///
2984 /// Note that this is only valid if the first and second predicates have the
2985 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2986 ///
2987 /// Three bits are used to represent the condition, as follows:
2988 ///   0  A > B
2989 ///   1  A == B
2990 ///   2  A < B
2991 ///
2992 /// <=>  Value  Definition
2993 /// 000     0   Always false
2994 /// 001     1   A >  B
2995 /// 010     2   A == B
2996 /// 011     3   A >= B
2997 /// 100     4   A <  B
2998 /// 101     5   A != B
2999 /// 110     6   A <= B
3000 /// 111     7   Always true
3001 ///  
3002 static unsigned getICmpCode(const ICmpInst *ICI) {
3003   switch (ICI->getPredicate()) {
3004     // False -> 0
3005   case ICmpInst::ICMP_UGT: return 1;  // 001
3006   case ICmpInst::ICMP_SGT: return 1;  // 001
3007   case ICmpInst::ICMP_EQ:  return 2;  // 010
3008   case ICmpInst::ICMP_UGE: return 3;  // 011
3009   case ICmpInst::ICMP_SGE: return 3;  // 011
3010   case ICmpInst::ICMP_ULT: return 4;  // 100
3011   case ICmpInst::ICMP_SLT: return 4;  // 100
3012   case ICmpInst::ICMP_NE:  return 5;  // 101
3013   case ICmpInst::ICMP_ULE: return 6;  // 110
3014   case ICmpInst::ICMP_SLE: return 6;  // 110
3015     // True -> 7
3016   default:
3017     assert(0 && "Invalid ICmp predicate!");
3018     return 0;
3019   }
3020 }
3021
3022 /// getICmpValue - This is the complement of getICmpCode, which turns an
3023 /// opcode and two operands into either a constant true or false, or a brand 
3024 /// new ICmp instruction. The sign is passed in to determine which kind
3025 /// of predicate to use in new icmp instructions.
3026 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3027   switch (code) {
3028   default: assert(0 && "Illegal ICmp code!");
3029   case  0: return ConstantInt::getFalse();
3030   case  1: 
3031     if (sign)
3032       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3033     else
3034       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3035   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3036   case  3: 
3037     if (sign)
3038       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3039     else
3040       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3041   case  4: 
3042     if (sign)
3043       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3044     else
3045       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3046   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3047   case  6: 
3048     if (sign)
3049       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3050     else
3051       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3052   case  7: return ConstantInt::getTrue();
3053   }
3054 }
3055
3056 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3057   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3058     (ICmpInst::isSignedPredicate(p1) && 
3059      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3060     (ICmpInst::isSignedPredicate(p2) && 
3061      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3062 }
3063
3064 namespace { 
3065 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3066 struct FoldICmpLogical {
3067   InstCombiner &IC;
3068   Value *LHS, *RHS;
3069   ICmpInst::Predicate pred;
3070   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3071     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3072       pred(ICI->getPredicate()) {}
3073   bool shouldApply(Value *V) const {
3074     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3075       if (PredicatesFoldable(pred, ICI->getPredicate()))
3076         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3077                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3078     return false;
3079   }
3080   Instruction *apply(Instruction &Log) const {
3081     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3082     if (ICI->getOperand(0) != LHS) {
3083       assert(ICI->getOperand(1) == LHS);
3084       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3085     }
3086
3087     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3088     unsigned LHSCode = getICmpCode(ICI);
3089     unsigned RHSCode = getICmpCode(RHSICI);
3090     unsigned Code;
3091     switch (Log.getOpcode()) {
3092     case Instruction::And: Code = LHSCode & RHSCode; break;
3093     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3094     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3095     default: assert(0 && "Illegal logical opcode!"); return 0;
3096     }
3097
3098     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3099                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3100       
3101     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3102     if (Instruction *I = dyn_cast<Instruction>(RV))
3103       return I;
3104     // Otherwise, it's a constant boolean value...
3105     return IC.ReplaceInstUsesWith(Log, RV);
3106   }
3107 };
3108 } // end anonymous namespace
3109
3110 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3111 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3112 // guaranteed to be a binary operator.
3113 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3114                                     ConstantInt *OpRHS,
3115                                     ConstantInt *AndRHS,
3116                                     BinaryOperator &TheAnd) {
3117   Value *X = Op->getOperand(0);
3118   Constant *Together = 0;
3119   if (!Op->isShift())
3120     Together = And(AndRHS, OpRHS);
3121
3122   switch (Op->getOpcode()) {
3123   case Instruction::Xor:
3124     if (Op->hasOneUse()) {
3125       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3126       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3127       InsertNewInstBefore(And, TheAnd);
3128       And->takeName(Op);
3129       return BinaryOperator::CreateXor(And, Together);
3130     }
3131     break;
3132   case Instruction::Or:
3133     if (Together == AndRHS) // (X | C) & C --> C
3134       return ReplaceInstUsesWith(TheAnd, AndRHS);
3135
3136     if (Op->hasOneUse() && Together != OpRHS) {
3137       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3138       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3139       InsertNewInstBefore(Or, TheAnd);
3140       Or->takeName(Op);
3141       return BinaryOperator::CreateAnd(Or, AndRHS);
3142     }
3143     break;
3144   case Instruction::Add:
3145     if (Op->hasOneUse()) {
3146       // Adding a one to a single bit bit-field should be turned into an XOR
3147       // of the bit.  First thing to check is to see if this AND is with a
3148       // single bit constant.
3149       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3150
3151       // If there is only one bit set...
3152       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3153         // Ok, at this point, we know that we are masking the result of the
3154         // ADD down to exactly one bit.  If the constant we are adding has
3155         // no bits set below this bit, then we can eliminate the ADD.
3156         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3157
3158         // Check to see if any bits below the one bit set in AndRHSV are set.
3159         if ((AddRHS & (AndRHSV-1)) == 0) {
3160           // If not, the only thing that can effect the output of the AND is
3161           // the bit specified by AndRHSV.  If that bit is set, the effect of
3162           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3163           // no effect.
3164           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3165             TheAnd.setOperand(0, X);
3166             return &TheAnd;
3167           } else {
3168             // Pull the XOR out of the AND.
3169             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3170             InsertNewInstBefore(NewAnd, TheAnd);
3171             NewAnd->takeName(Op);
3172             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3173           }
3174         }
3175       }
3176     }
3177     break;
3178
3179   case Instruction::Shl: {
3180     // We know that the AND will not produce any of the bits shifted in, so if
3181     // the anded constant includes them, clear them now!
3182     //
3183     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3184     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3185     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3186     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3187
3188     if (CI->getValue() == ShlMask) { 
3189     // Masking out bits that the shift already masks
3190       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3191     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3192       TheAnd.setOperand(1, CI);
3193       return &TheAnd;
3194     }
3195     break;
3196   }
3197   case Instruction::LShr:
3198   {
3199     // We know that the AND will not produce any of the bits shifted in, so if
3200     // the anded constant includes them, clear them now!  This only applies to
3201     // unsigned shifts, because a signed shr may bring in set bits!
3202     //
3203     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3204     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3205     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3206     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3207
3208     if (CI->getValue() == ShrMask) {   
3209     // Masking out bits that the shift already masks.
3210       return ReplaceInstUsesWith(TheAnd, Op);
3211     } else if (CI != AndRHS) {
3212       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3213       return &TheAnd;
3214     }
3215     break;
3216   }
3217   case Instruction::AShr:
3218     // Signed shr.
3219     // See if this is shifting in some sign extension, then masking it out
3220     // with an and.
3221     if (Op->hasOneUse()) {
3222       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3223       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3224       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3225       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3226       if (C == AndRHS) {          // Masking out bits shifted in.
3227         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3228         // Make the argument unsigned.
3229         Value *ShVal = Op->getOperand(0);
3230         ShVal = InsertNewInstBefore(
3231             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3232                                    Op->getName()), TheAnd);
3233         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3234       }
3235     }
3236     break;
3237   }
3238   return 0;
3239 }
3240
3241
3242 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3243 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3244 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3245 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3246 /// insert new instructions.
3247 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3248                                            bool isSigned, bool Inside, 
3249                                            Instruction &IB) {
3250   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3251             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3252          "Lo is not <= Hi in range emission code!");
3253     
3254   if (Inside) {
3255     if (Lo == Hi)  // Trivially false.
3256       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3257
3258     // V >= Min && V < Hi --> V < Hi
3259     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3260       ICmpInst::Predicate pred = (isSigned ? 
3261         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3262       return new ICmpInst(pred, V, Hi);
3263     }
3264
3265     // Emit V-Lo <u Hi-Lo
3266     Constant *NegLo = ConstantExpr::getNeg(Lo);
3267     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3268     InsertNewInstBefore(Add, IB);
3269     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3270     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3271   }
3272
3273   if (Lo == Hi)  // Trivially true.
3274     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3275
3276   // V < Min || V >= Hi -> V > Hi-1
3277   Hi = SubOne(cast<ConstantInt>(Hi));
3278   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3279     ICmpInst::Predicate pred = (isSigned ? 
3280         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3281     return new ICmpInst(pred, V, Hi);
3282   }
3283
3284   // Emit V-Lo >u Hi-1-Lo
3285   // Note that Hi has already had one subtracted from it, above.
3286   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3287   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3288   InsertNewInstBefore(Add, IB);
3289   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3290   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3291 }
3292
3293 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3294 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3295 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3296 // not, since all 1s are not contiguous.
3297 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3298   const APInt& V = Val->getValue();
3299   uint32_t BitWidth = Val->getType()->getBitWidth();
3300   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3301
3302   // look for the first zero bit after the run of ones
3303   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3304   // look for the first non-zero bit
3305   ME = V.getActiveBits(); 
3306   return true;
3307 }
3308
3309 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3310 /// where isSub determines whether the operator is a sub.  If we can fold one of
3311 /// the following xforms:
3312 /// 
3313 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3314 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3315 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3316 ///
3317 /// return (A +/- B).
3318 ///
3319 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3320                                         ConstantInt *Mask, bool isSub,
3321                                         Instruction &I) {
3322   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3323   if (!LHSI || LHSI->getNumOperands() != 2 ||
3324       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3325
3326   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3327
3328   switch (LHSI->getOpcode()) {
3329   default: return 0;
3330   case Instruction::And:
3331     if (And(N, Mask) == Mask) {
3332       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3333       if ((Mask->getValue().countLeadingZeros() + 
3334            Mask->getValue().countPopulation()) == 
3335           Mask->getValue().getBitWidth())
3336         break;
3337
3338       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3339       // part, we don't need any explicit masks to take them out of A.  If that
3340       // is all N is, ignore it.
3341       uint32_t MB = 0, ME = 0;
3342       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3343         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3344         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3345         if (MaskedValueIsZero(RHS, Mask))
3346           break;
3347       }
3348     }
3349     return 0;
3350   case Instruction::Or:
3351   case Instruction::Xor:
3352     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3353     if ((Mask->getValue().countLeadingZeros() + 
3354          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3355         && And(N, Mask)->isZero())
3356       break;
3357     return 0;
3358   }
3359   
3360   Instruction *New;
3361   if (isSub)
3362     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3363   else
3364     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3365   return InsertNewInstBefore(New, I);
3366 }
3367
3368 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3369   bool Changed = SimplifyCommutative(I);
3370   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3371
3372   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3373     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3374
3375   // and X, X = X
3376   if (Op0 == Op1)
3377     return ReplaceInstUsesWith(I, Op1);
3378
3379   // See if we can simplify any instructions used by the instruction whose sole 
3380   // purpose is to compute bits we don't care about.
3381   if (!isa<VectorType>(I.getType())) {
3382     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3383     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3384     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3385                              KnownZero, KnownOne))
3386       return &I;
3387   } else {
3388     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3389       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3390         return ReplaceInstUsesWith(I, I.getOperand(0));
3391     } else if (isa<ConstantAggregateZero>(Op1)) {
3392       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3393     }
3394   }
3395   
3396   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3397     const APInt& AndRHSMask = AndRHS->getValue();
3398     APInt NotAndRHS(~AndRHSMask);
3399
3400     // Optimize a variety of ((val OP C1) & C2) combinations...
3401     if (isa<BinaryOperator>(Op0)) {
3402       Instruction *Op0I = cast<Instruction>(Op0);
3403       Value *Op0LHS = Op0I->getOperand(0);
3404       Value *Op0RHS = Op0I->getOperand(1);
3405       switch (Op0I->getOpcode()) {
3406       case Instruction::Xor:
3407       case Instruction::Or:
3408         // If the mask is only needed on one incoming arm, push it up.
3409         if (Op0I->hasOneUse()) {
3410           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3411             // Not masking anything out for the LHS, move to RHS.
3412             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3413                                                    Op0RHS->getName()+".masked");
3414             InsertNewInstBefore(NewRHS, I);
3415             return BinaryOperator::Create(
3416                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3417           }
3418           if (!isa<Constant>(Op0RHS) &&
3419               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3420             // Not masking anything out for the RHS, move to LHS.
3421             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3422                                                    Op0LHS->getName()+".masked");
3423             InsertNewInstBefore(NewLHS, I);
3424             return BinaryOperator::Create(
3425                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3426           }
3427         }
3428
3429         break;
3430       case Instruction::Add:
3431         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3432         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3433         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3434         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3435           return BinaryOperator::CreateAnd(V, AndRHS);
3436         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3437           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3438         break;
3439
3440       case Instruction::Sub:
3441         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3442         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3443         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3444         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3445           return BinaryOperator::CreateAnd(V, AndRHS);
3446
3447         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3448         // has 1's for all bits that the subtraction with A might affect.
3449         if (Op0I->hasOneUse()) {
3450           uint32_t BitWidth = AndRHSMask.getBitWidth();
3451           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3452           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3453
3454           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3455           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3456               MaskedValueIsZero(Op0LHS, Mask)) {
3457             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3458             InsertNewInstBefore(NewNeg, I);
3459             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3460           }
3461         }
3462         break;
3463
3464       case Instruction::Shl:
3465       case Instruction::LShr:
3466         // (1 << x) & 1 --> zext(x == 0)
3467         // (1 >> x) & 1 --> zext(x == 0)
3468         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3469           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3470                                            Constant::getNullValue(I.getType()));
3471           InsertNewInstBefore(NewICmp, I);
3472           return new ZExtInst(NewICmp, I.getType());
3473         }
3474         break;
3475       }
3476
3477       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3478         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3479           return Res;
3480     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3481       // If this is an integer truncation or change from signed-to-unsigned, and
3482       // if the source is an and/or with immediate, transform it.  This
3483       // frequently occurs for bitfield accesses.
3484       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3485         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3486             CastOp->getNumOperands() == 2)
3487           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3488             if (CastOp->getOpcode() == Instruction::And) {
3489               // Change: and (cast (and X, C1) to T), C2
3490               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3491               // This will fold the two constants together, which may allow 
3492               // other simplifications.
3493               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3494                 CastOp->getOperand(0), I.getType(), 
3495                 CastOp->getName()+".shrunk");
3496               NewCast = InsertNewInstBefore(NewCast, I);
3497               // trunc_or_bitcast(C1)&C2
3498               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3499               C3 = ConstantExpr::getAnd(C3, AndRHS);
3500               return BinaryOperator::CreateAnd(NewCast, C3);
3501             } else if (CastOp->getOpcode() == Instruction::Or) {
3502               // Change: and (cast (or X, C1) to T), C2
3503               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3504               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3505               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3506                 return ReplaceInstUsesWith(I, AndRHS);
3507             }
3508           }
3509       }
3510     }
3511
3512     // Try to fold constant and into select arguments.
3513     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3514       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3515         return R;
3516     if (isa<PHINode>(Op0))
3517       if (Instruction *NV = FoldOpIntoPhi(I))
3518         return NV;
3519   }
3520
3521   Value *Op0NotVal = dyn_castNotVal(Op0);
3522   Value *Op1NotVal = dyn_castNotVal(Op1);
3523
3524   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3525     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3526
3527   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3528   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3529     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3530                                                I.getName()+".demorgan");
3531     InsertNewInstBefore(Or, I);
3532     return BinaryOperator::CreateNot(Or);
3533   }
3534   
3535   {
3536     Value *A = 0, *B = 0, *C = 0, *D = 0;
3537     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3538       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3539         return ReplaceInstUsesWith(I, Op1);
3540     
3541       // (A|B) & ~(A&B) -> A^B
3542       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3543         if ((A == C && B == D) || (A == D && B == C))
3544           return BinaryOperator::CreateXor(A, B);
3545       }
3546     }
3547     
3548     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3549       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3550         return ReplaceInstUsesWith(I, Op0);
3551
3552       // ~(A&B) & (A|B) -> A^B
3553       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3554         if ((A == C && B == D) || (A == D && B == C))
3555           return BinaryOperator::CreateXor(A, B);
3556       }
3557     }
3558     
3559     if (Op0->hasOneUse() &&
3560         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3561       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3562         I.swapOperands();     // Simplify below
3563         std::swap(Op0, Op1);
3564       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3565         cast<BinaryOperator>(Op0)->swapOperands();
3566         I.swapOperands();     // Simplify below
3567         std::swap(Op0, Op1);
3568       }
3569     }
3570     if (Op1->hasOneUse() &&
3571         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3572       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3573         cast<BinaryOperator>(Op1)->swapOperands();
3574         std::swap(A, B);
3575       }
3576       if (A == Op0) {                                // A&(A^B) -> A & ~B
3577         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3578         InsertNewInstBefore(NotB, I);
3579         return BinaryOperator::CreateAnd(A, NotB);
3580       }
3581     }
3582   }
3583   
3584   
3585   { // (icmp ugt/ult A, C) & (icmp B, C) --> (icmp (A|B), C)
3586     // where C is a power of 2
3587     Value *A, *B;
3588     ConstantInt *C1, *C2;
3589     ICmpInst::Predicate LHSCC, RHSCC;
3590     if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3591                         m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3592       if (C1 == C2 && LHSCC == RHSCC && C1->getValue().isPowerOf2() &&
3593           (LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_UGT)) {
3594         Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3595         InsertNewInstBefore(NewOr, I);
3596         return new ICmpInst(LHSCC, NewOr, C1);
3597       }
3598   }
3599
3600   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3601     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3602     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3603       return R;
3604
3605     Value *LHSVal, *RHSVal;
3606     ConstantInt *LHSCst, *RHSCst;
3607     ICmpInst::Predicate LHSCC, RHSCC;
3608     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3609       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3610         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3611             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3612             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3613             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3614             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3615             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3616             
3617             // Don't try to fold ICMP_SLT + ICMP_ULT.
3618             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3619              ICmpInst::isSignedPredicate(LHSCC) == 
3620                  ICmpInst::isSignedPredicate(RHSCC))) {
3621           // Ensure that the larger constant is on the RHS.
3622           ICmpInst::Predicate GT;
3623           if (ICmpInst::isSignedPredicate(LHSCC) ||
3624               (ICmpInst::isEquality(LHSCC) && 
3625                ICmpInst::isSignedPredicate(RHSCC)))
3626             GT = ICmpInst::ICMP_SGT;
3627           else
3628             GT = ICmpInst::ICMP_UGT;
3629           
3630           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3631           ICmpInst *LHS = cast<ICmpInst>(Op0);
3632           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3633             std::swap(LHS, RHS);
3634             std::swap(LHSCst, RHSCst);
3635             std::swap(LHSCC, RHSCC);
3636           }
3637
3638           // At this point, we know we have have two icmp instructions
3639           // comparing a value against two constants and and'ing the result
3640           // together.  Because of the above check, we know that we only have
3641           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3642           // (from the FoldICmpLogical check above), that the two constants 
3643           // are not equal and that the larger constant is on the RHS
3644           assert(LHSCst != RHSCst && "Compares not folded above?");
3645
3646           switch (LHSCC) {
3647           default: assert(0 && "Unknown integer condition code!");
3648           case ICmpInst::ICMP_EQ:
3649             switch (RHSCC) {
3650             default: assert(0 && "Unknown integer condition code!");
3651             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3652             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3653             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3654               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3655             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3656             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3657             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3658               return ReplaceInstUsesWith(I, LHS);
3659             }
3660           case ICmpInst::ICMP_NE:
3661             switch (RHSCC) {
3662             default: assert(0 && "Unknown integer condition code!");
3663             case ICmpInst::ICMP_ULT:
3664               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3665                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3666               break;                        // (X != 13 & X u< 15) -> no change
3667             case ICmpInst::ICMP_SLT:
3668               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3669                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3670               break;                        // (X != 13 & X s< 15) -> no change
3671             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3672             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3673             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3674               return ReplaceInstUsesWith(I, RHS);
3675             case ICmpInst::ICMP_NE:
3676               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3677                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3678                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3679                                                       LHSVal->getName()+".off");
3680                 InsertNewInstBefore(Add, I);
3681                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3682                                     ConstantInt::get(Add->getType(), 1));
3683               }
3684               break;                        // (X != 13 & X != 15) -> no change
3685             }
3686             break;
3687           case ICmpInst::ICMP_ULT:
3688             switch (RHSCC) {
3689             default: assert(0 && "Unknown integer condition code!");
3690             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3691             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3692               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3693             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3694               break;
3695             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3696             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3697               return ReplaceInstUsesWith(I, LHS);
3698             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3699               break;
3700             }
3701             break;
3702           case ICmpInst::ICMP_SLT:
3703             switch (RHSCC) {
3704             default: assert(0 && "Unknown integer condition code!");
3705             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3706             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3707               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3708             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3709               break;
3710             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3711             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3712               return ReplaceInstUsesWith(I, LHS);
3713             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3714               break;
3715             }
3716             break;
3717           case ICmpInst::ICMP_UGT:
3718             switch (RHSCC) {
3719             default: assert(0 && "Unknown integer condition code!");
3720             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3721             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3722               return ReplaceInstUsesWith(I, RHS);
3723             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3724               break;
3725             case ICmpInst::ICMP_NE:
3726               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3727                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3728               break;                        // (X u> 13 & X != 15) -> no change
3729             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3730               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3731                                      true, I);
3732             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3733               break;
3734             }
3735             break;
3736           case ICmpInst::ICMP_SGT:
3737             switch (RHSCC) {
3738             default: assert(0 && "Unknown integer condition code!");
3739             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3740             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3741               return ReplaceInstUsesWith(I, RHS);
3742             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3743               break;
3744             case ICmpInst::ICMP_NE:
3745               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3746                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3747               break;                        // (X s> 13 & X != 15) -> no change
3748             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3749               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3750                                      true, I);
3751             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3752               break;
3753             }
3754             break;
3755           }
3756         }
3757   }
3758
3759   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3760   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3761     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3762       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3763         const Type *SrcTy = Op0C->getOperand(0)->getType();
3764         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3765             // Only do this if the casts both really cause code to be generated.
3766             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3767                               I.getType(), TD) &&
3768             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3769                               I.getType(), TD)) {
3770           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3771                                                          Op1C->getOperand(0),
3772                                                          I.getName());
3773           InsertNewInstBefore(NewOp, I);
3774           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3775         }
3776       }
3777     
3778   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3779   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3780     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3781       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3782           SI0->getOperand(1) == SI1->getOperand(1) &&
3783           (SI0->hasOneUse() || SI1->hasOneUse())) {
3784         Instruction *NewOp =
3785           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3786                                                         SI1->getOperand(0),
3787                                                         SI0->getName()), I);
3788         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
3789                                       SI1->getOperand(1));
3790       }
3791   }
3792
3793   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3794   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3795     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3796       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3797           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3798         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3799           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3800             // If either of the constants are nans, then the whole thing returns
3801             // false.
3802             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3803               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3804             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3805                                 RHS->getOperand(0));
3806           }
3807     }
3808   }
3809
3810   return Changed ? &I : 0;
3811 }
3812
3813 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3814 /// in the result.  If it does, and if the specified byte hasn't been filled in
3815 /// yet, fill it in and return false.
3816 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3817   Instruction *I = dyn_cast<Instruction>(V);
3818   if (I == 0) return true;
3819
3820   // If this is an or instruction, it is an inner node of the bswap.
3821   if (I->getOpcode() == Instruction::Or)
3822     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3823            CollectBSwapParts(I->getOperand(1), ByteValues);
3824   
3825   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3826   // If this is a shift by a constant int, and it is "24", then its operand
3827   // defines a byte.  We only handle unsigned types here.
3828   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3829     // Not shifting the entire input by N-1 bytes?
3830     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3831         8*(ByteValues.size()-1))
3832       return true;
3833     
3834     unsigned DestNo;
3835     if (I->getOpcode() == Instruction::Shl) {
3836       // X << 24 defines the top byte with the lowest of the input bytes.
3837       DestNo = ByteValues.size()-1;
3838     } else {
3839       // X >>u 24 defines the low byte with the highest of the input bytes.
3840       DestNo = 0;
3841     }
3842     
3843     // If the destination byte value is already defined, the values are or'd
3844     // together, which isn't a bswap (unless it's an or of the same bits).
3845     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3846       return true;
3847     ByteValues[DestNo] = I->getOperand(0);
3848     return false;
3849   }
3850   
3851   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3852   // don't have this.
3853   Value *Shift = 0, *ShiftLHS = 0;
3854   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3855   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3856       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3857     return true;
3858   Instruction *SI = cast<Instruction>(Shift);
3859
3860   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3861   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3862       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3863     return true;
3864   
3865   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3866   unsigned DestByte;
3867   if (AndAmt->getValue().getActiveBits() > 64)
3868     return true;
3869   uint64_t AndAmtVal = AndAmt->getZExtValue();
3870   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3871     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3872       break;
3873   // Unknown mask for bswap.
3874   if (DestByte == ByteValues.size()) return true;
3875   
3876   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3877   unsigned SrcByte;
3878   if (SI->getOpcode() == Instruction::Shl)
3879     SrcByte = DestByte - ShiftBytes;
3880   else
3881     SrcByte = DestByte + ShiftBytes;
3882   
3883   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3884   if (SrcByte != ByteValues.size()-DestByte-1)
3885     return true;
3886   
3887   // If the destination byte value is already defined, the values are or'd
3888   // together, which isn't a bswap (unless it's an or of the same bits).
3889   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3890     return true;
3891   ByteValues[DestByte] = SI->getOperand(0);
3892   return false;
3893 }
3894
3895 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3896 /// If so, insert the new bswap intrinsic and return it.
3897 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3898   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3899   if (!ITy || ITy->getBitWidth() % 16) 
3900     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3901   
3902   /// ByteValues - For each byte of the result, we keep track of which value
3903   /// defines each byte.
3904   SmallVector<Value*, 8> ByteValues;
3905   ByteValues.resize(ITy->getBitWidth()/8);
3906     
3907   // Try to find all the pieces corresponding to the bswap.
3908   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3909       CollectBSwapParts(I.getOperand(1), ByteValues))
3910     return 0;
3911   
3912   // Check to see if all of the bytes come from the same value.
3913   Value *V = ByteValues[0];
3914   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3915   
3916   // Check to make sure that all of the bytes come from the same value.
3917   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3918     if (ByteValues[i] != V)
3919       return 0;
3920   const Type *Tys[] = { ITy };
3921   Module *M = I.getParent()->getParent()->getParent();
3922   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3923   return CallInst::Create(F, V);
3924 }
3925
3926
3927 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3928   bool Changed = SimplifyCommutative(I);
3929   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3930
3931   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3932     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3933
3934   // or X, X = X
3935   if (Op0 == Op1)
3936     return ReplaceInstUsesWith(I, Op0);
3937
3938   // See if we can simplify any instructions used by the instruction whose sole 
3939   // purpose is to compute bits we don't care about.
3940   if (!isa<VectorType>(I.getType())) {
3941     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3942     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3943     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3944                              KnownZero, KnownOne))
3945       return &I;
3946   } else if (isa<ConstantAggregateZero>(Op1)) {
3947     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3948   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3949     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3950       return ReplaceInstUsesWith(I, I.getOperand(1));
3951   }
3952     
3953
3954   
3955   // or X, -1 == -1
3956   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3957     ConstantInt *C1 = 0; Value *X = 0;
3958     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3959     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3960       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3961       InsertNewInstBefore(Or, I);
3962       Or->takeName(Op0);
3963       return BinaryOperator::CreateAnd(Or, 
3964                ConstantInt::get(RHS->getValue() | C1->getValue()));
3965     }
3966
3967     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3968     if (match(Op0, m_Xor(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::CreateXor(Or,
3973                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3974     }
3975
3976     // Try to fold constant and into select arguments.
3977     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3978       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3979         return R;
3980     if (isa<PHINode>(Op0))
3981       if (Instruction *NV = FoldOpIntoPhi(I))
3982         return NV;
3983   }
3984
3985   Value *A = 0, *B = 0;
3986   ConstantInt *C1 = 0, *C2 = 0;
3987
3988   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3989     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3990       return ReplaceInstUsesWith(I, Op1);
3991   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3992     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3993       return ReplaceInstUsesWith(I, Op0);
3994
3995   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3996   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3997   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3998       match(Op1, m_Or(m_Value(), m_Value())) ||
3999       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4000        match(Op1, m_Shift(m_Value(), m_Value())))) {
4001     if (Instruction *BSwap = MatchBSwap(I))
4002       return BSwap;
4003   }
4004   
4005   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4006   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4007       MaskedValueIsZero(Op1, C1->getValue())) {
4008     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4009     InsertNewInstBefore(NOr, I);
4010     NOr->takeName(Op0);
4011     return BinaryOperator::CreateXor(NOr, C1);
4012   }
4013
4014   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4015   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4016       MaskedValueIsZero(Op0, C1->getValue())) {
4017     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4018     InsertNewInstBefore(NOr, I);
4019     NOr->takeName(Op0);
4020     return BinaryOperator::CreateXor(NOr, C1);
4021   }
4022
4023   // (A & C)|(B & D)
4024   Value *C = 0, *D = 0;
4025   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4026       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4027     Value *V1 = 0, *V2 = 0, *V3 = 0;
4028     C1 = dyn_cast<ConstantInt>(C);
4029     C2 = dyn_cast<ConstantInt>(D);
4030     if (C1 && C2) {  // (A & C1)|(B & C2)
4031       // If we have: ((V + N) & C1) | (V & C2)
4032       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4033       // replace with V+N.
4034       if (C1->getValue() == ~C2->getValue()) {
4035         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4036             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4037           // Add commutes, try both ways.
4038           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4039             return ReplaceInstUsesWith(I, A);
4040           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4041             return ReplaceInstUsesWith(I, A);
4042         }
4043         // Or commutes, try both ways.
4044         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4045             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4046           // Add commutes, try both ways.
4047           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4048             return ReplaceInstUsesWith(I, B);
4049           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4050             return ReplaceInstUsesWith(I, B);
4051         }
4052       }
4053       V1 = 0; V2 = 0; V3 = 0;
4054     }
4055     
4056     // Check to see if we have any common things being and'ed.  If so, find the
4057     // terms for V1 & (V2|V3).
4058     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4059       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4060         V1 = A, V2 = C, V3 = D;
4061       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4062         V1 = A, V2 = B, V3 = C;
4063       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4064         V1 = C, V2 = A, V3 = D;
4065       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4066         V1 = C, V2 = A, V3 = B;
4067       
4068       if (V1) {
4069         Value *Or =
4070           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4071         return BinaryOperator::CreateAnd(V1, Or);
4072       }
4073     }
4074   }
4075   
4076   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4077   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4078     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4079       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4080           SI0->getOperand(1) == SI1->getOperand(1) &&
4081           (SI0->hasOneUse() || SI1->hasOneUse())) {
4082         Instruction *NewOp =
4083         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4084                                                      SI1->getOperand(0),
4085                                                      SI0->getName()), I);
4086         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4087                                       SI1->getOperand(1));
4088       }
4089   }
4090
4091   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4092     if (A == Op1)   // ~A | A == -1
4093       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4094   } else {
4095     A = 0;
4096   }
4097   // Note, A is still live here!
4098   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4099     if (Op0 == B)
4100       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4101
4102     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4103     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4104       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4105                                               I.getName()+".demorgan"), I);
4106       return BinaryOperator::CreateNot(And);
4107     }
4108   }
4109
4110   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4111   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4112     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4113       return R;
4114
4115     Value *LHSVal, *RHSVal;
4116     ConstantInt *LHSCst, *RHSCst;
4117     ICmpInst::Predicate LHSCC, RHSCC;
4118     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4119       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4120         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4121             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4122             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4123             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4124             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4125             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4126             // We can't fold (ugt x, C) | (sgt x, C2).
4127             PredicatesFoldable(LHSCC, RHSCC)) {
4128           // Ensure that the larger constant is on the RHS.
4129           ICmpInst *LHS = cast<ICmpInst>(Op0);
4130           bool NeedsSwap;
4131           if (ICmpInst::isSignedPredicate(LHSCC))
4132             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4133           else
4134             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4135             
4136           if (NeedsSwap) {
4137             std::swap(LHS, RHS);
4138             std::swap(LHSCst, RHSCst);
4139             std::swap(LHSCC, RHSCC);
4140           }
4141
4142           // At this point, we know we have have two icmp instructions
4143           // comparing a value against two constants and or'ing the result
4144           // together.  Because of the above check, we know that we only have
4145           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4146           // FoldICmpLogical check above), that the two constants are not
4147           // equal.
4148           assert(LHSCst != RHSCst && "Compares not folded above?");
4149
4150           switch (LHSCC) {
4151           default: assert(0 && "Unknown integer condition code!");
4152           case ICmpInst::ICMP_EQ:
4153             switch (RHSCC) {
4154             default: assert(0 && "Unknown integer condition code!");
4155             case ICmpInst::ICMP_EQ:
4156               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4157                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4158                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4159                                                       LHSVal->getName()+".off");
4160                 InsertNewInstBefore(Add, I);
4161                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4162                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4163               }
4164               break;                         // (X == 13 | X == 15) -> no change
4165             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4166             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4167               break;
4168             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4169             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4170             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4171               return ReplaceInstUsesWith(I, RHS);
4172             }
4173             break;
4174           case ICmpInst::ICMP_NE:
4175             switch (RHSCC) {
4176             default: assert(0 && "Unknown integer condition code!");
4177             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4178             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4179             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4180               return ReplaceInstUsesWith(I, LHS);
4181             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4182             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4183             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4184               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4185             }
4186             break;
4187           case ICmpInst::ICMP_ULT:
4188             switch (RHSCC) {
4189             default: assert(0 && "Unknown integer condition code!");
4190             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4191               break;
4192             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4193               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4194               // this can cause overflow.
4195               if (RHSCst->isMaxValue(false))
4196                 return ReplaceInstUsesWith(I, LHS);
4197               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4198                                      false, I);
4199             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4200               break;
4201             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4202             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4203               return ReplaceInstUsesWith(I, RHS);
4204             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4205               break;
4206             }
4207             break;
4208           case ICmpInst::ICMP_SLT:
4209             switch (RHSCC) {
4210             default: assert(0 && "Unknown integer condition code!");
4211             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4212               break;
4213             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4214               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4215               // this can cause overflow.
4216               if (RHSCst->isMaxValue(true))
4217                 return ReplaceInstUsesWith(I, LHS);
4218               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4219                                      false, I);
4220             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4221               break;
4222             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4223             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4224               return ReplaceInstUsesWith(I, RHS);
4225             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4226               break;
4227             }
4228             break;
4229           case ICmpInst::ICMP_UGT:
4230             switch (RHSCC) {
4231             default: assert(0 && "Unknown integer condition code!");
4232             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4233             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4234               return ReplaceInstUsesWith(I, LHS);
4235             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4236               break;
4237             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4238             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4239               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4240             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4241               break;
4242             }
4243             break;
4244           case ICmpInst::ICMP_SGT:
4245             switch (RHSCC) {
4246             default: assert(0 && "Unknown integer condition code!");
4247             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4248             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4249               return ReplaceInstUsesWith(I, LHS);
4250             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4251               break;
4252             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4253             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4254               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4255             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4256               break;
4257             }
4258             break;
4259           }
4260         }
4261   }
4262     
4263   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4264   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4265     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4266       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4267         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4268             !isa<ICmpInst>(Op1C->getOperand(0))) {
4269           const Type *SrcTy = Op0C->getOperand(0)->getType();
4270           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4271               // Only do this if the casts both really cause code to be
4272               // generated.
4273               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4274                                 I.getType(), TD) &&
4275               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4276                                 I.getType(), TD)) {
4277             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4278                                                           Op1C->getOperand(0),
4279                                                           I.getName());
4280             InsertNewInstBefore(NewOp, I);
4281             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4282           }
4283         }
4284       }
4285   }
4286   
4287     
4288   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4289   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4290     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4291       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4292           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4293           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4294         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4295           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4296             // If either of the constants are nans, then the whole thing returns
4297             // true.
4298             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4299               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4300             
4301             // Otherwise, no need to compare the two constants, compare the
4302             // rest.
4303             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4304                                 RHS->getOperand(0));
4305           }
4306     }
4307   }
4308
4309   return Changed ? &I : 0;
4310 }
4311
4312 namespace {
4313
4314 // XorSelf - Implements: X ^ X --> 0
4315 struct XorSelf {
4316   Value *RHS;
4317   XorSelf(Value *rhs) : RHS(rhs) {}
4318   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4319   Instruction *apply(BinaryOperator &Xor) const {
4320     return &Xor;
4321   }
4322 };
4323
4324 }
4325
4326 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4327   bool Changed = SimplifyCommutative(I);
4328   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4329
4330   if (isa<UndefValue>(Op1)) {
4331     if (isa<UndefValue>(Op0))
4332       // Handle undef ^ undef -> 0 special case. This is a common
4333       // idiom (misuse).
4334       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4335     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4336   }
4337
4338   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4339   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4340     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4341     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4342   }
4343   
4344   // See if we can simplify any instructions used by the instruction whose sole 
4345   // purpose is to compute bits we don't care about.
4346   if (!isa<VectorType>(I.getType())) {
4347     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4348     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4349     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4350                              KnownZero, KnownOne))
4351       return &I;
4352   } else if (isa<ConstantAggregateZero>(Op1)) {
4353     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4354   }
4355
4356   // Is this a ~ operation?
4357   if (Value *NotOp = dyn_castNotVal(&I)) {
4358     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4359     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4360     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4361       if (Op0I->getOpcode() == Instruction::And || 
4362           Op0I->getOpcode() == Instruction::Or) {
4363         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4364         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4365           Instruction *NotY =
4366             BinaryOperator::CreateNot(Op0I->getOperand(1),
4367                                       Op0I->getOperand(1)->getName()+".not");
4368           InsertNewInstBefore(NotY, I);
4369           if (Op0I->getOpcode() == Instruction::And)
4370             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4371           else
4372             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4373         }
4374       }
4375     }
4376   }
4377   
4378   
4379   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4380     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4381     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4382       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4383         return new ICmpInst(ICI->getInversePredicate(),
4384                             ICI->getOperand(0), ICI->getOperand(1));
4385
4386       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4387         return new FCmpInst(FCI->getInversePredicate(),
4388                             FCI->getOperand(0), FCI->getOperand(1));
4389     }
4390
4391     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4392     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4393       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4394         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4395           Instruction::CastOps Opcode = Op0C->getOpcode();
4396           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4397             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4398                                              Op0C->getDestTy())) {
4399               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4400                                      CI->getOpcode(), CI->getInversePredicate(),
4401                                      CI->getOperand(0), CI->getOperand(1)), I);
4402               NewCI->takeName(CI);
4403               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4404             }
4405           }
4406         }
4407       }
4408     }
4409
4410     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4411       // ~(c-X) == X-c-1 == X+(-c-1)
4412       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4413         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4414           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4415           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4416                                               ConstantInt::get(I.getType(), 1));
4417           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4418         }
4419           
4420       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4421         if (Op0I->getOpcode() == Instruction::Add) {
4422           // ~(X-c) --> (-c-1)-X
4423           if (RHS->isAllOnesValue()) {
4424             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4425             return BinaryOperator::CreateSub(
4426                            ConstantExpr::getSub(NegOp0CI,
4427                                              ConstantInt::get(I.getType(), 1)),
4428                                           Op0I->getOperand(0));
4429           } else if (RHS->getValue().isSignBit()) {
4430             // (X + C) ^ signbit -> (X + C + signbit)
4431             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4432             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4433
4434           }
4435         } else if (Op0I->getOpcode() == Instruction::Or) {
4436           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4437           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4438             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4439             // Anything in both C1 and C2 is known to be zero, remove it from
4440             // NewRHS.
4441             Constant *CommonBits = And(Op0CI, RHS);
4442             NewRHS = ConstantExpr::getAnd(NewRHS, 
4443                                           ConstantExpr::getNot(CommonBits));
4444             AddToWorkList(Op0I);
4445             I.setOperand(0, Op0I->getOperand(0));
4446             I.setOperand(1, NewRHS);
4447             return &I;
4448           }
4449         }
4450       }
4451     }
4452
4453     // Try to fold constant and into select arguments.
4454     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4455       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4456         return R;
4457     if (isa<PHINode>(Op0))
4458       if (Instruction *NV = FoldOpIntoPhi(I))
4459         return NV;
4460   }
4461
4462   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4463     if (X == Op1)
4464       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4465
4466   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4467     if (X == Op0)
4468       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4469
4470   
4471   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4472   if (Op1I) {
4473     Value *A, *B;
4474     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4475       if (A == Op0) {              // B^(B|A) == (A|B)^B
4476         Op1I->swapOperands();
4477         I.swapOperands();
4478         std::swap(Op0, Op1);
4479       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4480         I.swapOperands();     // Simplified below.
4481         std::swap(Op0, Op1);
4482       }
4483     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4484       if (Op0 == A)                                          // A^(A^B) == B
4485         return ReplaceInstUsesWith(I, B);
4486       else if (Op0 == B)                                     // A^(B^A) == B
4487         return ReplaceInstUsesWith(I, A);
4488     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4489       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4490         Op1I->swapOperands();
4491         std::swap(A, B);
4492       }
4493       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4494         I.swapOperands();     // Simplified below.
4495         std::swap(Op0, Op1);
4496       }
4497     }
4498   }
4499   
4500   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4501   if (Op0I) {
4502     Value *A, *B;
4503     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4504       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4505         std::swap(A, B);
4506       if (B == Op1) {                                // (A|B)^B == A & ~B
4507         Instruction *NotB =
4508           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4509         return BinaryOperator::CreateAnd(A, NotB);
4510       }
4511     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4512       if (Op1 == A)                                          // (A^B)^A == B
4513         return ReplaceInstUsesWith(I, B);
4514       else if (Op1 == B)                                     // (B^A)^A == B
4515         return ReplaceInstUsesWith(I, A);
4516     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4517       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4518         std::swap(A, B);
4519       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4520           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4521         Instruction *N =
4522           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4523         return BinaryOperator::CreateAnd(N, Op1);
4524       }
4525     }
4526   }
4527   
4528   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4529   if (Op0I && Op1I && Op0I->isShift() && 
4530       Op0I->getOpcode() == Op1I->getOpcode() && 
4531       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4532       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4533     Instruction *NewOp =
4534       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4535                                                     Op1I->getOperand(0),
4536                                                     Op0I->getName()), I);
4537     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4538                                   Op1I->getOperand(1));
4539   }
4540     
4541   if (Op0I && Op1I) {
4542     Value *A, *B, *C, *D;
4543     // (A & B)^(A | B) -> A ^ B
4544     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4545         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4546       if ((A == C && B == D) || (A == D && B == C)) 
4547         return BinaryOperator::CreateXor(A, B);
4548     }
4549     // (A | B)^(A & B) -> A ^ B
4550     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4551         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4552       if ((A == C && B == D) || (A == D && B == C)) 
4553         return BinaryOperator::CreateXor(A, B);
4554     }
4555     
4556     // (A & B)^(C & D)
4557     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4558         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4559         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4560       // (X & Y)^(X & Y) -> (Y^Z) & X
4561       Value *X = 0, *Y = 0, *Z = 0;
4562       if (A == C)
4563         X = A, Y = B, Z = D;
4564       else if (A == D)
4565         X = A, Y = B, Z = C;
4566       else if (B == C)
4567         X = B, Y = A, Z = D;
4568       else if (B == D)
4569         X = B, Y = A, Z = C;
4570       
4571       if (X) {
4572         Instruction *NewOp =
4573         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4574         return BinaryOperator::CreateAnd(NewOp, X);
4575       }
4576     }
4577   }
4578     
4579   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4580   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4581     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4582       return R;
4583
4584   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4585   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4586     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4587       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4588         const Type *SrcTy = Op0C->getOperand(0)->getType();
4589         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4590             // Only do this if the casts both really cause code to be generated.
4591             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4592                               I.getType(), TD) &&
4593             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4594                               I.getType(), TD)) {
4595           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4596                                                          Op1C->getOperand(0),
4597                                                          I.getName());
4598           InsertNewInstBefore(NewOp, I);
4599           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4600         }
4601       }
4602   }
4603
4604   return Changed ? &I : 0;
4605 }
4606
4607 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4608 /// overflowed for this type.
4609 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4610                             ConstantInt *In2, bool IsSigned = false) {
4611   Result = cast<ConstantInt>(Add(In1, In2));
4612
4613   if (IsSigned)
4614     if (In2->getValue().isNegative())
4615       return Result->getValue().sgt(In1->getValue());
4616     else
4617       return Result->getValue().slt(In1->getValue());
4618   else
4619     return Result->getValue().ult(In1->getValue());
4620 }
4621
4622 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4623 /// code necessary to compute the offset from the base pointer (without adding
4624 /// in the base pointer).  Return the result as a signed integer of intptr size.
4625 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4626   TargetData &TD = IC.getTargetData();
4627   gep_type_iterator GTI = gep_type_begin(GEP);
4628   const Type *IntPtrTy = TD.getIntPtrType();
4629   Value *Result = Constant::getNullValue(IntPtrTy);
4630
4631   // Build a mask for high order bits.
4632   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4633   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4634
4635   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4636        ++i, ++GTI) {
4637     Value *Op = *i;
4638     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4639     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4640       if (OpC->isZero()) continue;
4641       
4642       // Handle a struct index, which adds its field offset to the pointer.
4643       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4644         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4645         
4646         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4647           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4648         else
4649           Result = IC.InsertNewInstBefore(
4650                    BinaryOperator::CreateAdd(Result,
4651                                              ConstantInt::get(IntPtrTy, Size),
4652                                              GEP->getName()+".offs"), I);
4653         continue;
4654       }
4655       
4656       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4657       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4658       Scale = ConstantExpr::getMul(OC, Scale);
4659       if (Constant *RC = dyn_cast<Constant>(Result))
4660         Result = ConstantExpr::getAdd(RC, Scale);
4661       else {
4662         // Emit an add instruction.
4663         Result = IC.InsertNewInstBefore(
4664            BinaryOperator::CreateAdd(Result, Scale,
4665                                      GEP->getName()+".offs"), I);
4666       }
4667       continue;
4668     }
4669     // Convert to correct type.
4670     if (Op->getType() != IntPtrTy) {
4671       if (Constant *OpC = dyn_cast<Constant>(Op))
4672         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4673       else
4674         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4675                                                  Op->getName()+".c"), I);
4676     }
4677     if (Size != 1) {
4678       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4679       if (Constant *OpC = dyn_cast<Constant>(Op))
4680         Op = ConstantExpr::getMul(OpC, Scale);
4681       else    // We'll let instcombine(mul) convert this to a shl if possible.
4682         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4683                                                   GEP->getName()+".idx"), I);
4684     }
4685
4686     // Emit an add instruction.
4687     if (isa<Constant>(Op) && isa<Constant>(Result))
4688       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4689                                     cast<Constant>(Result));
4690     else
4691       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4692                                                   GEP->getName()+".offs"), I);
4693   }
4694   return Result;
4695 }
4696
4697
4698 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4699 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
4700 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
4701 /// complex, and scales are involved.  The above expression would also be legal
4702 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
4703 /// later form is less amenable to optimization though, and we are allowed to
4704 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4705 ///
4706 /// If we can't emit an optimized form for this expression, this returns null.
4707 /// 
4708 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4709                                           InstCombiner &IC) {
4710   TargetData &TD = IC.getTargetData();
4711   gep_type_iterator GTI = gep_type_begin(GEP);
4712
4713   // Check to see if this gep only has a single variable index.  If so, and if
4714   // any constant indices are a multiple of its scale, then we can compute this
4715   // in terms of the scale of the variable index.  For example, if the GEP
4716   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4717   // because the expression will cross zero at the same point.
4718   unsigned i, e = GEP->getNumOperands();
4719   int64_t Offset = 0;
4720   for (i = 1; i != e; ++i, ++GTI) {
4721     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4722       // Compute the aggregate offset of constant indices.
4723       if (CI->isZero()) continue;
4724
4725       // Handle a struct index, which adds its field offset to the pointer.
4726       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4727         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4728       } else {
4729         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4730         Offset += Size*CI->getSExtValue();
4731       }
4732     } else {
4733       // Found our variable index.
4734       break;
4735     }
4736   }
4737   
4738   // If there are no variable indices, we must have a constant offset, just
4739   // evaluate it the general way.
4740   if (i == e) return 0;
4741   
4742   Value *VariableIdx = GEP->getOperand(i);
4743   // Determine the scale factor of the variable element.  For example, this is
4744   // 4 if the variable index is into an array of i32.
4745   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4746   
4747   // Verify that there are no other variable indices.  If so, emit the hard way.
4748   for (++i, ++GTI; i != e; ++i, ++GTI) {
4749     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4750     if (!CI) return 0;
4751    
4752     // Compute the aggregate offset of constant indices.
4753     if (CI->isZero()) continue;
4754     
4755     // Handle a struct index, which adds its field offset to the pointer.
4756     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4757       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4758     } else {
4759       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4760       Offset += Size*CI->getSExtValue();
4761     }
4762   }
4763   
4764   // Okay, we know we have a single variable index, which must be a
4765   // pointer/array/vector index.  If there is no offset, life is simple, return
4766   // the index.
4767   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4768   if (Offset == 0) {
4769     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
4770     // we don't need to bother extending: the extension won't affect where the
4771     // computation crosses zero.
4772     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4773       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4774                                   VariableIdx->getNameStart(), &I);
4775     return VariableIdx;
4776   }
4777   
4778   // Otherwise, there is an index.  The computation we will do will be modulo
4779   // the pointer size, so get it.
4780   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4781   
4782   Offset &= PtrSizeMask;
4783   VariableScale &= PtrSizeMask;
4784
4785   // To do this transformation, any constant index must be a multiple of the
4786   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
4787   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
4788   // multiple of the variable scale.
4789   int64_t NewOffs = Offset / (int64_t)VariableScale;
4790   if (Offset != NewOffs*(int64_t)VariableScale)
4791     return 0;
4792
4793   // Okay, we can do this evaluation.  Start by converting the index to intptr.
4794   const Type *IntPtrTy = TD.getIntPtrType();
4795   if (VariableIdx->getType() != IntPtrTy)
4796     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4797                                               true /*SExt*/, 
4798                                               VariableIdx->getNameStart(), &I);
4799   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4800   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4801 }
4802
4803
4804 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4805 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4806 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4807                                        ICmpInst::Predicate Cond,
4808                                        Instruction &I) {
4809   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4810
4811   // Look through bitcasts.
4812   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4813     RHS = BCI->getOperand(0);
4814
4815   Value *PtrBase = GEPLHS->getOperand(0);
4816   if (PtrBase == RHS) {
4817     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4818     // This transformation (ignoring the base and scales) is valid because we
4819     // know pointers can't overflow.  See if we can output an optimized form.
4820     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4821     
4822     // If not, synthesize the offset the hard way.
4823     if (Offset == 0)
4824       Offset = EmitGEPOffset(GEPLHS, I, *this);
4825     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4826                         Constant::getNullValue(Offset->getType()));
4827   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4828     // If the base pointers are different, but the indices are the same, just
4829     // compare the base pointer.
4830     if (PtrBase != GEPRHS->getOperand(0)) {
4831       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4832       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4833                         GEPRHS->getOperand(0)->getType();
4834       if (IndicesTheSame)
4835         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4836           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4837             IndicesTheSame = false;
4838             break;
4839           }
4840
4841       // If all indices are the same, just compare the base pointers.
4842       if (IndicesTheSame)
4843         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4844                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4845
4846       // Otherwise, the base pointers are different and the indices are
4847       // different, bail out.
4848       return 0;
4849     }
4850
4851     // If one of the GEPs has all zero indices, recurse.
4852     bool AllZeros = true;
4853     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4854       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4855           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4856         AllZeros = false;
4857         break;
4858       }
4859     if (AllZeros)
4860       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4861                           ICmpInst::getSwappedPredicate(Cond), I);
4862
4863     // If the other GEP has all zero indices, recurse.
4864     AllZeros = true;
4865     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4866       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4867           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4868         AllZeros = false;
4869         break;
4870       }
4871     if (AllZeros)
4872       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4873
4874     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4875       // If the GEPs only differ by one index, compare it.
4876       unsigned NumDifferences = 0;  // Keep track of # differences.
4877       unsigned DiffOperand = 0;     // The operand that differs.
4878       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4879         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4880           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4881                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4882             // Irreconcilable differences.
4883             NumDifferences = 2;
4884             break;
4885           } else {
4886             if (NumDifferences++) break;
4887             DiffOperand = i;
4888           }
4889         }
4890
4891       if (NumDifferences == 0)   // SAME GEP?
4892         return ReplaceInstUsesWith(I, // No comparison is needed here.
4893                                    ConstantInt::get(Type::Int1Ty,
4894                                              ICmpInst::isTrueWhenEqual(Cond)));
4895
4896       else if (NumDifferences == 1) {
4897         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4898         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4899         // Make sure we do a signed comparison here.
4900         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4901       }
4902     }
4903
4904     // Only lower this if the icmp is the only user of the GEP or if we expect
4905     // the result to fold to a constant!
4906     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4907         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4908       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4909       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4910       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4911       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4912     }
4913   }
4914   return 0;
4915 }
4916
4917 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4918 ///
4919 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4920                                                 Instruction *LHSI,
4921                                                 Constant *RHSC) {
4922   if (!isa<ConstantFP>(RHSC)) return 0;
4923   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4924   
4925   // Get the width of the mantissa.  We don't want to hack on conversions that
4926   // might lose information from the integer, e.g. "i64 -> float"
4927   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4928   if (MantissaWidth == -1) return 0;  // Unknown.
4929   
4930   // Check to see that the input is converted from an integer type that is small
4931   // enough that preserves all bits.  TODO: check here for "known" sign bits.
4932   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4933   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4934   
4935   // If this is a uitofp instruction, we need an extra bit to hold the sign.
4936   if (isa<UIToFPInst>(LHSI))
4937     ++InputSize;
4938   
4939   // If the conversion would lose info, don't hack on this.
4940   if ((int)InputSize > MantissaWidth)
4941     return 0;
4942   
4943   // Otherwise, we can potentially simplify the comparison.  We know that it
4944   // will always come through as an integer value and we know the constant is
4945   // not a NAN (it would have been previously simplified).
4946   assert(!RHS.isNaN() && "NaN comparison not already folded!");
4947   
4948   ICmpInst::Predicate Pred;
4949   switch (I.getPredicate()) {
4950   default: assert(0 && "Unexpected predicate!");
4951   case FCmpInst::FCMP_UEQ:
4952   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4953   case FCmpInst::FCMP_UGT:
4954   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4955   case FCmpInst::FCMP_UGE:
4956   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4957   case FCmpInst::FCMP_ULT:
4958   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4959   case FCmpInst::FCMP_ULE:
4960   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4961   case FCmpInst::FCMP_UNE:
4962   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4963   case FCmpInst::FCMP_ORD:
4964     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4965   case FCmpInst::FCMP_UNO:
4966     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4967   }
4968   
4969   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4970   
4971   // Now we know that the APFloat is a normal number, zero or inf.
4972   
4973   // See if the FP constant is too large for the integer.  For example,
4974   // comparing an i8 to 300.0.
4975   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4976   
4977   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
4978   // and large values. 
4979   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4980   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4981                         APFloat::rmNearestTiesToEven);
4982   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
4983     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4984         Pred == ICmpInst::ICMP_SLE)
4985       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4986     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4987   }
4988   
4989   // See if the RHS value is < SignedMin.
4990   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4991   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4992                         APFloat::rmNearestTiesToEven);
4993   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4994     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4995         Pred == ICmpInst::ICMP_SGE)
4996       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4997     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4998   }
4999
5000   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5001   // it may still be fractional.  See if it is fractional by casting the FP
5002   // value to the integer value and back, checking for equality.  Don't do this
5003   // for zero, because -0.0 is not fractional.
5004   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5005   if (!RHS.isZero() &&
5006       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5007     // If we had a comparison against a fractional value, we have to adjust
5008     // the compare predicate and sometimes the value.  RHSC is rounded towards
5009     // zero at this point.
5010     switch (Pred) {
5011     default: assert(0 && "Unexpected integer comparison!");
5012     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5013       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5014     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5015       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5016     case ICmpInst::ICMP_SLE:
5017       // (float)int <= 4.4   --> int <= 4
5018       // (float)int <= -4.4  --> int < -4
5019       if (RHS.isNegative())
5020         Pred = ICmpInst::ICMP_SLT;
5021       break;
5022     case ICmpInst::ICMP_SLT:
5023       // (float)int < -4.4   --> int < -4
5024       // (float)int < 4.4    --> int <= 4
5025       if (!RHS.isNegative())
5026         Pred = ICmpInst::ICMP_SLE;
5027       break;
5028     case ICmpInst::ICMP_SGT:
5029       // (float)int > 4.4    --> int > 4
5030       // (float)int > -4.4   --> int >= -4
5031       if (RHS.isNegative())
5032         Pred = ICmpInst::ICMP_SGE;
5033       break;
5034     case ICmpInst::ICMP_SGE:
5035       // (float)int >= -4.4   --> int >= -4
5036       // (float)int >= 4.4    --> int > 4
5037       if (!RHS.isNegative())
5038         Pred = ICmpInst::ICMP_SGT;
5039       break;
5040     }
5041   }
5042
5043   // Lower this FP comparison into an appropriate integer version of the
5044   // comparison.
5045   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5046 }
5047
5048 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5049   bool Changed = SimplifyCompare(I);
5050   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5051
5052   // Fold trivial predicates.
5053   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5054     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5055   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5056     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5057   
5058   // Simplify 'fcmp pred X, X'
5059   if (Op0 == Op1) {
5060     switch (I.getPredicate()) {
5061     default: assert(0 && "Unknown predicate!");
5062     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5063     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5064     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5065       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5066     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5067     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5068     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5069       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5070       
5071     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5072     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5073     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5074     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5075       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5076       I.setPredicate(FCmpInst::FCMP_UNO);
5077       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5078       return &I;
5079       
5080     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5081     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5082     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5083     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5084       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5085       I.setPredicate(FCmpInst::FCMP_ORD);
5086       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5087       return &I;
5088     }
5089   }
5090     
5091   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5092     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5093
5094   // Handle fcmp with constant RHS
5095   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5096     // If the constant is a nan, see if we can fold the comparison based on it.
5097     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5098       if (CFP->getValueAPF().isNaN()) {
5099         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5100           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5101         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5102                "Comparison must be either ordered or unordered!");
5103         // True if unordered.
5104         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5105       }
5106     }
5107     
5108     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5109       switch (LHSI->getOpcode()) {
5110       case Instruction::PHI:
5111         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5112         // block.  If in the same block, we're encouraging jump threading.  If
5113         // not, we are just pessimizing the code by making an i1 phi.
5114         if (LHSI->getParent() == I.getParent())
5115           if (Instruction *NV = FoldOpIntoPhi(I))
5116             return NV;
5117         break;
5118       case Instruction::SIToFP:
5119       case Instruction::UIToFP:
5120         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5121           return NV;
5122         break;
5123       case Instruction::Select:
5124         // If either operand of the select is a constant, we can fold the
5125         // comparison into the select arms, which will cause one to be
5126         // constant folded and the select turned into a bitwise or.
5127         Value *Op1 = 0, *Op2 = 0;
5128         if (LHSI->hasOneUse()) {
5129           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5130             // Fold the known value into the constant operand.
5131             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5132             // Insert a new FCmp of the other select operand.
5133             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5134                                                       LHSI->getOperand(2), RHSC,
5135                                                       I.getName()), I);
5136           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5137             // Fold the known value into the constant operand.
5138             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5139             // Insert a new FCmp of the other select operand.
5140             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5141                                                       LHSI->getOperand(1), RHSC,
5142                                                       I.getName()), I);
5143           }
5144         }
5145
5146         if (Op1)
5147           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5148         break;
5149       }
5150   }
5151
5152   return Changed ? &I : 0;
5153 }
5154
5155 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5156   bool Changed = SimplifyCompare(I);
5157   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5158   const Type *Ty = Op0->getType();
5159
5160   // icmp X, X
5161   if (Op0 == Op1)
5162     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5163                                                    I.isTrueWhenEqual()));
5164
5165   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5166     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5167   
5168   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5169   // addresses never equal each other!  We already know that Op0 != Op1.
5170   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5171        isa<ConstantPointerNull>(Op0)) &&
5172       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5173        isa<ConstantPointerNull>(Op1)))
5174     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5175                                                    !I.isTrueWhenEqual()));
5176
5177   // icmp's with boolean values can always be turned into bitwise operations
5178   if (Ty == Type::Int1Ty) {
5179     switch (I.getPredicate()) {
5180     default: assert(0 && "Invalid icmp instruction!");
5181     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5182       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5183       InsertNewInstBefore(Xor, I);
5184       return BinaryOperator::CreateNot(Xor);
5185     }
5186     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5187       return BinaryOperator::CreateXor(Op0, Op1);
5188
5189     case ICmpInst::ICMP_UGT:
5190       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5191       // FALL THROUGH
5192     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5193       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5194       InsertNewInstBefore(Not, I);
5195       return BinaryOperator::CreateAnd(Not, Op1);
5196     }
5197     case ICmpInst::ICMP_SGT:
5198       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5199       // FALL THROUGH
5200     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5201       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5202       InsertNewInstBefore(Not, I);
5203       return BinaryOperator::CreateAnd(Not, Op0);
5204     }
5205     case ICmpInst::ICMP_UGE:
5206       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5207       // FALL THROUGH
5208     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5209       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5210       InsertNewInstBefore(Not, I);
5211       return BinaryOperator::CreateOr(Not, Op1);
5212     }
5213     case ICmpInst::ICMP_SGE:
5214       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5215       // FALL THROUGH
5216     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5217       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5218       InsertNewInstBefore(Not, I);
5219       return BinaryOperator::CreateOr(Not, Op0);
5220     }
5221     }
5222   }
5223
5224   // See if we are doing a comparison between a constant and an instruction that
5225   // can be folded into the comparison.
5226   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5227     Value *A, *B;
5228     
5229     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5230     if (I.isEquality() && CI->isNullValue() &&
5231         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5232       // (icmp cond A B) if cond is equality
5233       return new ICmpInst(I.getPredicate(), A, B);
5234     }
5235     
5236     // If we have a icmp le or icmp ge instruction, turn it into the appropriate
5237     // icmp lt or icmp gt instruction.  This allows us to rely on them being
5238     // folded in the code below.
5239     switch (I.getPredicate()) {
5240     default: break;
5241     case ICmpInst::ICMP_ULE:
5242       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5243         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5244       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5245     case ICmpInst::ICMP_SLE:
5246       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5247         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5248       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5249     case ICmpInst::ICMP_UGE:
5250       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5251         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5252       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5253     case ICmpInst::ICMP_SGE:
5254       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5255         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5256       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5257     }
5258     
5259     // See if we can fold the comparison based on range information we can get
5260     // by checking whether bits are known to be zero or one in the input.
5261     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5262     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5263     
5264     // If this comparison is a normal comparison, it demands all
5265     // bits, if it is a sign bit comparison, it only demands the sign bit.
5266     bool UnusedBit;
5267     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5268     
5269     if (SimplifyDemandedBits(Op0, 
5270                              isSignBit ? APInt::getSignBit(BitWidth)
5271                                        : APInt::getAllOnesValue(BitWidth),
5272                              KnownZero, KnownOne, 0))
5273       return &I;
5274         
5275     // Given the known and unknown bits, compute a range that the LHS could be
5276     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5277     // EQ and NE we use unsigned values.
5278     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5279     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5280       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5281     else
5282       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5283     
5284     // If Min and Max are known to be the same, then SimplifyDemandedBits
5285     // figured out that the LHS is a constant.  Just constant fold this now so
5286     // that code below can assume that Min != Max.
5287     if (Min == Max)
5288       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5289                                                           ConstantInt::get(Min),
5290                                                           CI));
5291     
5292     // Based on the range information we know about the LHS, see if we can
5293     // simplify this comparison.  For example, (x&4) < 8  is always true.
5294     const APInt &RHSVal = CI->getValue();
5295     switch (I.getPredicate()) {  // LE/GE have been folded already.
5296     default: assert(0 && "Unknown icmp opcode!");
5297     case ICmpInst::ICMP_EQ:
5298       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5299         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5300       break;
5301     case ICmpInst::ICMP_NE:
5302       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5303         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5304       break;
5305     case ICmpInst::ICMP_ULT:
5306       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5307         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5308       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5309         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5310       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5311         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5312       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5313         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5314         
5315       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5316       if (CI->isMinValue(true))
5317         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5318                             ConstantInt::getAllOnesValue(Op0->getType()));
5319       break;
5320     case ICmpInst::ICMP_UGT:
5321       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5322         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5323       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5324         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5325         
5326       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5327         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5328       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5329         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5330       
5331       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5332       if (CI->isMaxValue(true))
5333         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5334                             ConstantInt::getNullValue(Op0->getType()));
5335       break;
5336     case ICmpInst::ICMP_SLT:
5337       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5338         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5339       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5340         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5341       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5342         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5343       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5344         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5345       break;
5346     case ICmpInst::ICMP_SGT: 
5347       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5348         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5349       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5350         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5351         
5352       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5353         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5354       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5355         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5356       break;
5357     }
5358           
5359     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5360     // instruction, see if that instruction also has constants so that the 
5361     // instruction can be folded into the icmp 
5362     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5363       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5364         return Res;
5365   }
5366
5367   // Handle icmp with constant (but not simple integer constant) RHS
5368   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5369     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5370       switch (LHSI->getOpcode()) {
5371       case Instruction::GetElementPtr:
5372         if (RHSC->isNullValue()) {
5373           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5374           bool isAllZeros = true;
5375           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5376             if (!isa<Constant>(LHSI->getOperand(i)) ||
5377                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5378               isAllZeros = false;
5379               break;
5380             }
5381           if (isAllZeros)
5382             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5383                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5384         }
5385         break;
5386
5387       case Instruction::PHI:
5388         // Only fold icmp into the PHI if the phi and fcmp are in the same
5389         // block.  If in the same block, we're encouraging jump threading.  If
5390         // not, we are just pessimizing the code by making an i1 phi.
5391         if (LHSI->getParent() == I.getParent())
5392           if (Instruction *NV = FoldOpIntoPhi(I))
5393             return NV;
5394         break;
5395       case Instruction::Select: {
5396         // If either operand of the select is a constant, we can fold the
5397         // comparison into the select arms, which will cause one to be
5398         // constant folded and the select turned into a bitwise or.
5399         Value *Op1 = 0, *Op2 = 0;
5400         if (LHSI->hasOneUse()) {
5401           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5402             // Fold the known value into the constant operand.
5403             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5404             // Insert a new ICmp of the other select operand.
5405             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5406                                                    LHSI->getOperand(2), RHSC,
5407                                                    I.getName()), I);
5408           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5409             // Fold the known value into the constant operand.
5410             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5411             // Insert a new ICmp of the other select operand.
5412             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5413                                                    LHSI->getOperand(1), RHSC,
5414                                                    I.getName()), I);
5415           }
5416         }
5417
5418         if (Op1)
5419           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5420         break;
5421       }
5422       case Instruction::Malloc:
5423         // If we have (malloc != null), and if the malloc has a single use, we
5424         // can assume it is successful and remove the malloc.
5425         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5426           AddToWorkList(LHSI);
5427           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5428                                                          !I.isTrueWhenEqual()));
5429         }
5430         break;
5431       }
5432   }
5433
5434   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5435   if (User *GEP = dyn_castGetElementPtr(Op0))
5436     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5437       return NI;
5438   if (User *GEP = dyn_castGetElementPtr(Op1))
5439     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5440                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5441       return NI;
5442
5443   // Test to see if the operands of the icmp are casted versions of other
5444   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5445   // now.
5446   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5447     if (isa<PointerType>(Op0->getType()) && 
5448         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5449       // We keep moving the cast from the left operand over to the right
5450       // operand, where it can often be eliminated completely.
5451       Op0 = CI->getOperand(0);
5452
5453       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5454       // so eliminate it as well.
5455       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5456         Op1 = CI2->getOperand(0);
5457
5458       // If Op1 is a constant, we can fold the cast into the constant.
5459       if (Op0->getType() != Op1->getType()) {
5460         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5461           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5462         } else {
5463           // Otherwise, cast the RHS right before the icmp
5464           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5465         }
5466       }
5467       return new ICmpInst(I.getPredicate(), Op0, Op1);
5468     }
5469   }
5470   
5471   if (isa<CastInst>(Op0)) {
5472     // Handle the special case of: icmp (cast bool to X), <cst>
5473     // This comes up when you have code like
5474     //   int X = A < B;
5475     //   if (X) ...
5476     // For generality, we handle any zero-extension of any operand comparison
5477     // with a constant or another cast from the same type.
5478     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5479       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5480         return R;
5481   }
5482   
5483   // See if it's the same type of instruction on the left and right.
5484   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5485     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
5486       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5487           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5488           I.isEquality()) {
5489         switch (Op0I->getOpcode()) {
5490         default: break;
5491         case Instruction::Add:
5492         case Instruction::Sub:
5493         case Instruction::Xor:
5494           // a+x icmp eq/ne b+x --> a icmp b
5495           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5496                               Op1I->getOperand(0));
5497           break;
5498         case Instruction::Mul:
5499           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5500             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5501             if (!CI->isZero() && !CI->isOne()) {
5502               const APInt &AP = CI->getValue();
5503               ConstantInt *Mask = ConstantInt::get(
5504                                       APInt::getLowBitsSet(AP.getBitWidth(),
5505                                                            AP.getBitWidth() -
5506                                                       AP.countTrailingZeros()));
5507               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5508                                                             Mask);
5509               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5510                                                             Mask);
5511               InsertNewInstBefore(And1, I);
5512               InsertNewInstBefore(And2, I);
5513               return new ICmpInst(I.getPredicate(), And1, And2);
5514             }
5515           }
5516           break;
5517         }
5518       }
5519     }
5520   }
5521   
5522   // ~x < ~y --> y < x
5523   { Value *A, *B;
5524     if (match(Op0, m_Not(m_Value(A))) &&
5525         match(Op1, m_Not(m_Value(B))))
5526       return new ICmpInst(I.getPredicate(), B, A);
5527   }
5528   
5529   if (I.isEquality()) {
5530     Value *A, *B, *C, *D;
5531     
5532     // -x == -y --> x == y
5533     if (match(Op0, m_Neg(m_Value(A))) &&
5534         match(Op1, m_Neg(m_Value(B))))
5535       return new ICmpInst(I.getPredicate(), A, B);
5536     
5537     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5538       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5539         Value *OtherVal = A == Op1 ? B : A;
5540         return new ICmpInst(I.getPredicate(), OtherVal,
5541                             Constant::getNullValue(A->getType()));
5542       }
5543
5544       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5545         // A^c1 == C^c2 --> A == C^(c1^c2)
5546         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5547           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5548             if (Op1->hasOneUse()) {
5549               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5550               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5551               return new ICmpInst(I.getPredicate(), A,
5552                                   InsertNewInstBefore(Xor, I));
5553             }
5554         
5555         // A^B == A^D -> B == D
5556         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5557         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5558         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5559         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5560       }
5561     }
5562     
5563     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5564         (A == Op0 || B == Op0)) {
5565       // A == (A^B)  ->  B == 0
5566       Value *OtherVal = A == Op0 ? B : A;
5567       return new ICmpInst(I.getPredicate(), OtherVal,
5568                           Constant::getNullValue(A->getType()));
5569     }
5570     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5571       // (A-B) == A  ->  B == 0
5572       return new ICmpInst(I.getPredicate(), B,
5573                           Constant::getNullValue(B->getType()));
5574     }
5575     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5576       // A == (A-B)  ->  B == 0
5577       return new ICmpInst(I.getPredicate(), B,
5578                           Constant::getNullValue(B->getType()));
5579     }
5580     
5581     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5582     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5583         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5584         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5585       Value *X = 0, *Y = 0, *Z = 0;
5586       
5587       if (A == C) {
5588         X = B; Y = D; Z = A;
5589       } else if (A == D) {
5590         X = B; Y = C; Z = A;
5591       } else if (B == C) {
5592         X = A; Y = D; Z = B;
5593       } else if (B == D) {
5594         X = A; Y = C; Z = B;
5595       }
5596       
5597       if (X) {   // Build (X^Y) & Z
5598         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5599         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5600         I.setOperand(0, Op1);
5601         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5602         return &I;
5603       }
5604     }
5605   }
5606   return Changed ? &I : 0;
5607 }
5608
5609
5610 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5611 /// and CmpRHS are both known to be integer constants.
5612 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5613                                           ConstantInt *DivRHS) {
5614   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5615   const APInt &CmpRHSV = CmpRHS->getValue();
5616   
5617   // FIXME: If the operand types don't match the type of the divide 
5618   // then don't attempt this transform. The code below doesn't have the
5619   // logic to deal with a signed divide and an unsigned compare (and
5620   // vice versa). This is because (x /s C1) <s C2  produces different 
5621   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5622   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5623   // work. :(  The if statement below tests that condition and bails 
5624   // if it finds it. 
5625   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5626   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5627     return 0;
5628   if (DivRHS->isZero())
5629     return 0; // The ProdOV computation fails on divide by zero.
5630
5631   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5632   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5633   // C2 (CI). By solving for X we can turn this into a range check 
5634   // instead of computing a divide. 
5635   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5636
5637   // Determine if the product overflows by seeing if the product is
5638   // not equal to the divide. Make sure we do the same kind of divide
5639   // as in the LHS instruction that we're folding. 
5640   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5641                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5642
5643   // Get the ICmp opcode
5644   ICmpInst::Predicate Pred = ICI.getPredicate();
5645
5646   // Figure out the interval that is being checked.  For example, a comparison
5647   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5648   // Compute this interval based on the constants involved and the signedness of
5649   // the compare/divide.  This computes a half-open interval, keeping track of
5650   // whether either value in the interval overflows.  After analysis each
5651   // overflow variable is set to 0 if it's corresponding bound variable is valid
5652   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5653   int LoOverflow = 0, HiOverflow = 0;
5654   ConstantInt *LoBound = 0, *HiBound = 0;
5655   
5656   
5657   if (!DivIsSigned) {  // udiv
5658     // e.g. X/5 op 3  --> [15, 20)
5659     LoBound = Prod;
5660     HiOverflow = LoOverflow = ProdOV;
5661     if (!HiOverflow)
5662       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5663   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5664     if (CmpRHSV == 0) {       // (X / pos) op 0
5665       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5666       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5667       HiBound = DivRHS;
5668     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5669       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5670       HiOverflow = LoOverflow = ProdOV;
5671       if (!HiOverflow)
5672         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5673     } else {                       // (X / pos) op neg
5674       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5675       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5676       LoOverflow = AddWithOverflow(LoBound, Prod,
5677                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5678       HiBound = AddOne(Prod);
5679       HiOverflow = ProdOV ? -1 : 0;
5680     }
5681   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5682     if (CmpRHSV == 0) {       // (X / neg) op 0
5683       // e.g. X/-5 op 0  --> [-4, 5)
5684       LoBound = AddOne(DivRHS);
5685       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5686       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5687         HiOverflow = 1;            // [INTMIN+1, overflow)
5688         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5689       }
5690     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5691       // e.g. X/-5 op 3  --> [-19, -14)
5692       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5693       if (!LoOverflow)
5694         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5695       HiBound = AddOne(Prod);
5696     } else {                       // (X / neg) op neg
5697       // e.g. X/-5 op -3  --> [15, 20)
5698       LoBound = Prod;
5699       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5700       HiBound = Subtract(Prod, DivRHS);
5701     }
5702     
5703     // Dividing by a negative swaps the condition.  LT <-> GT
5704     Pred = ICmpInst::getSwappedPredicate(Pred);
5705   }
5706
5707   Value *X = DivI->getOperand(0);
5708   switch (Pred) {
5709   default: assert(0 && "Unhandled icmp opcode!");
5710   case ICmpInst::ICMP_EQ:
5711     if (LoOverflow && HiOverflow)
5712       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5713     else if (HiOverflow)
5714       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5715                           ICmpInst::ICMP_UGE, X, LoBound);
5716     else if (LoOverflow)
5717       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5718                           ICmpInst::ICMP_ULT, X, HiBound);
5719     else
5720       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5721   case ICmpInst::ICMP_NE:
5722     if (LoOverflow && HiOverflow)
5723       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5724     else if (HiOverflow)
5725       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5726                           ICmpInst::ICMP_ULT, X, LoBound);
5727     else if (LoOverflow)
5728       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5729                           ICmpInst::ICMP_UGE, X, HiBound);
5730     else
5731       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5732   case ICmpInst::ICMP_ULT:
5733   case ICmpInst::ICMP_SLT:
5734     if (LoOverflow == +1)   // Low bound is greater than input range.
5735       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5736     if (LoOverflow == -1)   // Low bound is less than input range.
5737       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5738     return new ICmpInst(Pred, X, LoBound);
5739   case ICmpInst::ICMP_UGT:
5740   case ICmpInst::ICMP_SGT:
5741     if (HiOverflow == +1)       // High bound greater than input range.
5742       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5743     else if (HiOverflow == -1)  // High bound less than input range.
5744       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5745     if (Pred == ICmpInst::ICMP_UGT)
5746       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5747     else
5748       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5749   }
5750 }
5751
5752
5753 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5754 ///
5755 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5756                                                           Instruction *LHSI,
5757                                                           ConstantInt *RHS) {
5758   const APInt &RHSV = RHS->getValue();
5759   
5760   switch (LHSI->getOpcode()) {
5761   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5762     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5763       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5764       // fold the xor.
5765       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5766           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5767         Value *CompareVal = LHSI->getOperand(0);
5768         
5769         // If the sign bit of the XorCST is not set, there is no change to
5770         // the operation, just stop using the Xor.
5771         if (!XorCST->getValue().isNegative()) {
5772           ICI.setOperand(0, CompareVal);
5773           AddToWorkList(LHSI);
5774           return &ICI;
5775         }
5776         
5777         // Was the old condition true if the operand is positive?
5778         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5779         
5780         // If so, the new one isn't.
5781         isTrueIfPositive ^= true;
5782         
5783         if (isTrueIfPositive)
5784           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5785         else
5786           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5787       }
5788     }
5789     break;
5790   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5791     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5792         LHSI->getOperand(0)->hasOneUse()) {
5793       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5794       
5795       // If the LHS is an AND of a truncating cast, we can widen the
5796       // and/compare to be the input width without changing the value
5797       // produced, eliminating a cast.
5798       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5799         // We can do this transformation if either the AND constant does not
5800         // have its sign bit set or if it is an equality comparison. 
5801         // Extending a relational comparison when we're checking the sign
5802         // bit would not work.
5803         if (Cast->hasOneUse() &&
5804             (ICI.isEquality() ||
5805              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5806           uint32_t BitWidth = 
5807             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5808           APInt NewCST = AndCST->getValue();
5809           NewCST.zext(BitWidth);
5810           APInt NewCI = RHSV;
5811           NewCI.zext(BitWidth);
5812           Instruction *NewAnd = 
5813             BinaryOperator::CreateAnd(Cast->getOperand(0),
5814                                       ConstantInt::get(NewCST),LHSI->getName());
5815           InsertNewInstBefore(NewAnd, ICI);
5816           return new ICmpInst(ICI.getPredicate(), NewAnd,
5817                               ConstantInt::get(NewCI));
5818         }
5819       }
5820       
5821       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5822       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5823       // happens a LOT in code produced by the C front-end, for bitfield
5824       // access.
5825       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5826       if (Shift && !Shift->isShift())
5827         Shift = 0;
5828       
5829       ConstantInt *ShAmt;
5830       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5831       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5832       const Type *AndTy = AndCST->getType();          // Type of the and.
5833       
5834       // We can fold this as long as we can't shift unknown bits
5835       // into the mask.  This can only happen with signed shift
5836       // rights, as they sign-extend.
5837       if (ShAmt) {
5838         bool CanFold = Shift->isLogicalShift();
5839         if (!CanFold) {
5840           // To test for the bad case of the signed shr, see if any
5841           // of the bits shifted in could be tested after the mask.
5842           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5843           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5844           
5845           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5846           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5847                AndCST->getValue()) == 0)
5848             CanFold = true;
5849         }
5850         
5851         if (CanFold) {
5852           Constant *NewCst;
5853           if (Shift->getOpcode() == Instruction::Shl)
5854             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5855           else
5856             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5857           
5858           // Check to see if we are shifting out any of the bits being
5859           // compared.
5860           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5861             // If we shifted bits out, the fold is not going to work out.
5862             // As a special case, check to see if this means that the
5863             // result is always true or false now.
5864             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5865               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5866             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5867               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5868           } else {
5869             ICI.setOperand(1, NewCst);
5870             Constant *NewAndCST;
5871             if (Shift->getOpcode() == Instruction::Shl)
5872               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5873             else
5874               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5875             LHSI->setOperand(1, NewAndCST);
5876             LHSI->setOperand(0, Shift->getOperand(0));
5877             AddToWorkList(Shift); // Shift is dead.
5878             AddUsesToWorkList(ICI);
5879             return &ICI;
5880           }
5881         }
5882       }
5883       
5884       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5885       // preferable because it allows the C<<Y expression to be hoisted out
5886       // of a loop if Y is invariant and X is not.
5887       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5888           ICI.isEquality() && !Shift->isArithmeticShift() &&
5889           isa<Instruction>(Shift->getOperand(0))) {
5890         // Compute C << Y.
5891         Value *NS;
5892         if (Shift->getOpcode() == Instruction::LShr) {
5893           NS = BinaryOperator::CreateShl(AndCST, 
5894                                          Shift->getOperand(1), "tmp");
5895         } else {
5896           // Insert a logical shift.
5897           NS = BinaryOperator::CreateLShr(AndCST,
5898                                           Shift->getOperand(1), "tmp");
5899         }
5900         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5901         
5902         // Compute X & (C << Y).
5903         Instruction *NewAnd = 
5904           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5905         InsertNewInstBefore(NewAnd, ICI);
5906         
5907         ICI.setOperand(0, NewAnd);
5908         return &ICI;
5909       }
5910     }
5911     break;
5912     
5913   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5914     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5915     if (!ShAmt) break;
5916     
5917     uint32_t TypeBits = RHSV.getBitWidth();
5918     
5919     // Check that the shift amount is in range.  If not, don't perform
5920     // undefined shifts.  When the shift is visited it will be
5921     // simplified.
5922     if (ShAmt->uge(TypeBits))
5923       break;
5924     
5925     if (ICI.isEquality()) {
5926       // If we are comparing against bits always shifted out, the
5927       // comparison cannot succeed.
5928       Constant *Comp =
5929         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5930       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5931         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5932         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5933         return ReplaceInstUsesWith(ICI, Cst);
5934       }
5935       
5936       if (LHSI->hasOneUse()) {
5937         // Otherwise strength reduce the shift into an and.
5938         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5939         Constant *Mask =
5940           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5941         
5942         Instruction *AndI =
5943           BinaryOperator::CreateAnd(LHSI->getOperand(0),
5944                                     Mask, LHSI->getName()+".mask");
5945         Value *And = InsertNewInstBefore(AndI, ICI);
5946         return new ICmpInst(ICI.getPredicate(), And,
5947                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5948       }
5949     }
5950     
5951     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5952     bool TrueIfSigned = false;
5953     if (LHSI->hasOneUse() &&
5954         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5955       // (X << 31) <s 0  --> (X&1) != 0
5956       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5957                                            (TypeBits-ShAmt->getZExtValue()-1));
5958       Instruction *AndI =
5959         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5960                                   Mask, LHSI->getName()+".mask");
5961       Value *And = InsertNewInstBefore(AndI, ICI);
5962       
5963       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5964                           And, Constant::getNullValue(And->getType()));
5965     }
5966     break;
5967   }
5968     
5969   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5970   case Instruction::AShr: {
5971     // Only handle equality comparisons of shift-by-constant.
5972     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5973     if (!ShAmt || !ICI.isEquality()) break;
5974
5975     // Check that the shift amount is in range.  If not, don't perform
5976     // undefined shifts.  When the shift is visited it will be
5977     // simplified.
5978     uint32_t TypeBits = RHSV.getBitWidth();
5979     if (ShAmt->uge(TypeBits))
5980       break;
5981     
5982     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5983       
5984     // If we are comparing against bits always shifted out, the
5985     // comparison cannot succeed.
5986     APInt Comp = RHSV << ShAmtVal;
5987     if (LHSI->getOpcode() == Instruction::LShr)
5988       Comp = Comp.lshr(ShAmtVal);
5989     else
5990       Comp = Comp.ashr(ShAmtVal);
5991     
5992     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5993       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5994       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5995       return ReplaceInstUsesWith(ICI, Cst);
5996     }
5997     
5998     // Otherwise, check to see if the bits shifted out are known to be zero.
5999     // If so, we can compare against the unshifted value:
6000     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6001     if (LHSI->hasOneUse() &&
6002         MaskedValueIsZero(LHSI->getOperand(0), 
6003                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6004       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6005                           ConstantExpr::getShl(RHS, ShAmt));
6006     }
6007       
6008     if (LHSI->hasOneUse()) {
6009       // Otherwise strength reduce the shift into an and.
6010       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6011       Constant *Mask = ConstantInt::get(Val);
6012       
6013       Instruction *AndI =
6014         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6015                                   Mask, LHSI->getName()+".mask");
6016       Value *And = InsertNewInstBefore(AndI, ICI);
6017       return new ICmpInst(ICI.getPredicate(), And,
6018                           ConstantExpr::getShl(RHS, ShAmt));
6019     }
6020     break;
6021   }
6022     
6023   case Instruction::SDiv:
6024   case Instruction::UDiv:
6025     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6026     // Fold this div into the comparison, producing a range check. 
6027     // Determine, based on the divide type, what the range is being 
6028     // checked.  If there is an overflow on the low or high side, remember 
6029     // it, otherwise compute the range [low, hi) bounding the new value.
6030     // See: InsertRangeTest above for the kinds of replacements possible.
6031     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6032       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6033                                           DivRHS))
6034         return R;
6035     break;
6036
6037   case Instruction::Add:
6038     // Fold: icmp pred (add, X, C1), C2
6039
6040     if (!ICI.isEquality()) {
6041       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6042       if (!LHSC) break;
6043       const APInt &LHSV = LHSC->getValue();
6044
6045       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6046                             .subtract(LHSV);
6047
6048       if (ICI.isSignedPredicate()) {
6049         if (CR.getLower().isSignBit()) {
6050           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6051                               ConstantInt::get(CR.getUpper()));
6052         } else if (CR.getUpper().isSignBit()) {
6053           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6054                               ConstantInt::get(CR.getLower()));
6055         }
6056       } else {
6057         if (CR.getLower().isMinValue()) {
6058           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6059                               ConstantInt::get(CR.getUpper()));
6060         } else if (CR.getUpper().isMinValue()) {
6061           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6062                               ConstantInt::get(CR.getLower()));
6063         }
6064       }
6065     }
6066     break;
6067   }
6068   
6069   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6070   if (ICI.isEquality()) {
6071     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6072     
6073     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6074     // the second operand is a constant, simplify a bit.
6075     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6076       switch (BO->getOpcode()) {
6077       case Instruction::SRem:
6078         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6079         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6080           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6081           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6082             Instruction *NewRem =
6083               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6084                                          BO->getName());
6085             InsertNewInstBefore(NewRem, ICI);
6086             return new ICmpInst(ICI.getPredicate(), NewRem, 
6087                                 Constant::getNullValue(BO->getType()));
6088           }
6089         }
6090         break;
6091       case Instruction::Add:
6092         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6093         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6094           if (BO->hasOneUse())
6095             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6096                                 Subtract(RHS, BOp1C));
6097         } else if (RHSV == 0) {
6098           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6099           // efficiently invertible, or if the add has just this one use.
6100           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6101           
6102           if (Value *NegVal = dyn_castNegVal(BOp1))
6103             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6104           else if (Value *NegVal = dyn_castNegVal(BOp0))
6105             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6106           else if (BO->hasOneUse()) {
6107             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6108             InsertNewInstBefore(Neg, ICI);
6109             Neg->takeName(BO);
6110             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6111           }
6112         }
6113         break;
6114       case Instruction::Xor:
6115         // For the xor case, we can xor two constants together, eliminating
6116         // the explicit xor.
6117         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6118           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6119                               ConstantExpr::getXor(RHS, BOC));
6120         
6121         // FALLTHROUGH
6122       case Instruction::Sub:
6123         // Replace (([sub|xor] A, B) != 0) with (A != B)
6124         if (RHSV == 0)
6125           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6126                               BO->getOperand(1));
6127         break;
6128         
6129       case Instruction::Or:
6130         // If bits are being or'd in that are not present in the constant we
6131         // are comparing against, then the comparison could never succeed!
6132         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6133           Constant *NotCI = ConstantExpr::getNot(RHS);
6134           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6135             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6136                                                              isICMP_NE));
6137         }
6138         break;
6139         
6140       case Instruction::And:
6141         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6142           // If bits are being compared against that are and'd out, then the
6143           // comparison can never succeed!
6144           if ((RHSV & ~BOC->getValue()) != 0)
6145             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6146                                                              isICMP_NE));
6147           
6148           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6149           if (RHS == BOC && RHSV.isPowerOf2())
6150             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6151                                 ICmpInst::ICMP_NE, LHSI,
6152                                 Constant::getNullValue(RHS->getType()));
6153           
6154           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6155           if (BOC->getValue().isSignBit()) {
6156             Value *X = BO->getOperand(0);
6157             Constant *Zero = Constant::getNullValue(X->getType());
6158             ICmpInst::Predicate pred = isICMP_NE ? 
6159               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6160             return new ICmpInst(pred, X, Zero);
6161           }
6162           
6163           // ((X & ~7) == 0) --> X < 8
6164           if (RHSV == 0 && isHighOnes(BOC)) {
6165             Value *X = BO->getOperand(0);
6166             Constant *NegX = ConstantExpr::getNeg(BOC);
6167             ICmpInst::Predicate pred = isICMP_NE ? 
6168               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6169             return new ICmpInst(pred, X, NegX);
6170           }
6171         }
6172       default: break;
6173       }
6174     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6175       // Handle icmp {eq|ne} <intrinsic>, intcst.
6176       if (II->getIntrinsicID() == Intrinsic::bswap) {
6177         AddToWorkList(II);
6178         ICI.setOperand(0, II->getOperand(1));
6179         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6180         return &ICI;
6181       }
6182     }
6183   } else {  // Not a ICMP_EQ/ICMP_NE
6184             // If the LHS is a cast from an integral value of the same size, 
6185             // then since we know the RHS is a constant, try to simlify.
6186     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6187       Value *CastOp = Cast->getOperand(0);
6188       const Type *SrcTy = CastOp->getType();
6189       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6190       if (SrcTy->isInteger() && 
6191           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6192         // If this is an unsigned comparison, try to make the comparison use
6193         // smaller constant values.
6194         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6195           // X u< 128 => X s> -1
6196           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6197                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6198         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6199                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6200           // X u> 127 => X s< 0
6201           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6202                               Constant::getNullValue(SrcTy));
6203         }
6204       }
6205     }
6206   }
6207   return 0;
6208 }
6209
6210 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6211 /// We only handle extending casts so far.
6212 ///
6213 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6214   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6215   Value *LHSCIOp        = LHSCI->getOperand(0);
6216   const Type *SrcTy     = LHSCIOp->getType();
6217   const Type *DestTy    = LHSCI->getType();
6218   Value *RHSCIOp;
6219
6220   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6221   // integer type is the same size as the pointer type.
6222   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6223       getTargetData().getPointerSizeInBits() == 
6224          cast<IntegerType>(DestTy)->getBitWidth()) {
6225     Value *RHSOp = 0;
6226     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6227       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6228     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6229       RHSOp = RHSC->getOperand(0);
6230       // If the pointer types don't match, insert a bitcast.
6231       if (LHSCIOp->getType() != RHSOp->getType())
6232         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6233     }
6234
6235     if (RHSOp)
6236       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6237   }
6238   
6239   // The code below only handles extension cast instructions, so far.
6240   // Enforce this.
6241   if (LHSCI->getOpcode() != Instruction::ZExt &&
6242       LHSCI->getOpcode() != Instruction::SExt)
6243     return 0;
6244
6245   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6246   bool isSignedCmp = ICI.isSignedPredicate();
6247
6248   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6249     // Not an extension from the same type?
6250     RHSCIOp = CI->getOperand(0);
6251     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6252       return 0;
6253     
6254     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6255     // and the other is a zext), then we can't handle this.
6256     if (CI->getOpcode() != LHSCI->getOpcode())
6257       return 0;
6258
6259     // Deal with equality cases early.
6260     if (ICI.isEquality())
6261       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6262
6263     // A signed comparison of sign extended values simplifies into a
6264     // signed comparison.
6265     if (isSignedCmp && isSignedExt)
6266       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6267
6268     // The other three cases all fold into an unsigned comparison.
6269     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6270   }
6271
6272   // If we aren't dealing with a constant on the RHS, exit early
6273   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6274   if (!CI)
6275     return 0;
6276
6277   // Compute the constant that would happen if we truncated to SrcTy then
6278   // reextended to DestTy.
6279   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6280   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6281
6282   // If the re-extended constant didn't change...
6283   if (Res2 == CI) {
6284     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6285     // For example, we might have:
6286     //    %A = sext short %X to uint
6287     //    %B = icmp ugt uint %A, 1330
6288     // It is incorrect to transform this into 
6289     //    %B = icmp ugt short %X, 1330 
6290     // because %A may have negative value. 
6291     //
6292     // However, we allow this when the compare is EQ/NE, because they are
6293     // signless.
6294     if (isSignedExt == isSignedCmp || ICI.isEquality())
6295       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6296     return 0;
6297   }
6298
6299   // The re-extended constant changed so the constant cannot be represented 
6300   // in the shorter type. Consequently, we cannot emit a simple comparison.
6301
6302   // First, handle some easy cases. We know the result cannot be equal at this
6303   // point so handle the ICI.isEquality() cases
6304   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6305     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6306   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6307     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6308
6309   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6310   // should have been folded away previously and not enter in here.
6311   Value *Result;
6312   if (isSignedCmp) {
6313     // We're performing a signed comparison.
6314     if (cast<ConstantInt>(CI)->getValue().isNegative())
6315       Result = ConstantInt::getFalse();          // X < (small) --> false
6316     else
6317       Result = ConstantInt::getTrue();           // X < (large) --> true
6318   } else {
6319     // We're performing an unsigned comparison.
6320     if (isSignedExt) {
6321       // We're performing an unsigned comp with a sign extended value.
6322       // This is true if the input is >= 0. [aka >s -1]
6323       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6324       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6325                                    NegOne, ICI.getName()), ICI);
6326     } else {
6327       // Unsigned extend & unsigned compare -> always true.
6328       Result = ConstantInt::getTrue();
6329     }
6330   }
6331
6332   // Finally, return the value computed.
6333   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6334       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6335     return ReplaceInstUsesWith(ICI, Result);
6336
6337   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6338           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6339          "ICmp should be folded!");
6340   if (Constant *CI = dyn_cast<Constant>(Result))
6341     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6342   return BinaryOperator::CreateNot(Result);
6343 }
6344
6345 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6346   return commonShiftTransforms(I);
6347 }
6348
6349 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6350   return commonShiftTransforms(I);
6351 }
6352
6353 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6354   if (Instruction *R = commonShiftTransforms(I))
6355     return R;
6356   
6357   Value *Op0 = I.getOperand(0);
6358   
6359   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6360   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6361     if (CSI->isAllOnesValue())
6362       return ReplaceInstUsesWith(I, CSI);
6363   
6364   // See if we can turn a signed shr into an unsigned shr.
6365   if (MaskedValueIsZero(Op0, 
6366                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6367     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6368   
6369   return 0;
6370 }
6371
6372 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6373   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6374   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6375
6376   // shl X, 0 == X and shr X, 0 == X
6377   // shl 0, X == 0 and shr 0, X == 0
6378   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6379       Op0 == Constant::getNullValue(Op0->getType()))
6380     return ReplaceInstUsesWith(I, Op0);
6381   
6382   if (isa<UndefValue>(Op0)) {            
6383     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6384       return ReplaceInstUsesWith(I, Op0);
6385     else                                    // undef << X -> 0, undef >>u X -> 0
6386       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6387   }
6388   if (isa<UndefValue>(Op1)) {
6389     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6390       return ReplaceInstUsesWith(I, Op0);          
6391     else                                     // X << undef, X >>u undef -> 0
6392       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6393   }
6394
6395   // Try to fold constant and into select arguments.
6396   if (isa<Constant>(Op0))
6397     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6398       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6399         return R;
6400
6401   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6402     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6403       return Res;
6404   return 0;
6405 }
6406
6407 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6408                                                BinaryOperator &I) {
6409   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6410
6411   // See if we can simplify any instructions used by the instruction whose sole 
6412   // purpose is to compute bits we don't care about.
6413   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6414   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6415   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6416                            KnownZero, KnownOne))
6417     return &I;
6418   
6419   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6420   // of a signed value.
6421   //
6422   if (Op1->uge(TypeBits)) {
6423     if (I.getOpcode() != Instruction::AShr)
6424       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6425     else {
6426       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6427       return &I;
6428     }
6429   }
6430   
6431   // ((X*C1) << C2) == (X * (C1 << C2))
6432   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6433     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6434       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6435         return BinaryOperator::CreateMul(BO->getOperand(0),
6436                                          ConstantExpr::getShl(BOOp, Op1));
6437   
6438   // Try to fold constant and into select arguments.
6439   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6440     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6441       return R;
6442   if (isa<PHINode>(Op0))
6443     if (Instruction *NV = FoldOpIntoPhi(I))
6444       return NV;
6445   
6446   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6447   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6448     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6449     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6450     // place.  Don't try to do this transformation in this case.  Also, we
6451     // require that the input operand is a shift-by-constant so that we have
6452     // confidence that the shifts will get folded together.  We could do this
6453     // xform in more cases, but it is unlikely to be profitable.
6454     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6455         isa<ConstantInt>(TrOp->getOperand(1))) {
6456       // Okay, we'll do this xform.  Make the shift of shift.
6457       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6458       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6459                                                 I.getName());
6460       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6461
6462       // For logical shifts, the truncation has the effect of making the high
6463       // part of the register be zeros.  Emulate this by inserting an AND to
6464       // clear the top bits as needed.  This 'and' will usually be zapped by
6465       // other xforms later if dead.
6466       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6467       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6468       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6469       
6470       // The mask we constructed says what the trunc would do if occurring
6471       // between the shifts.  We want to know the effect *after* the second
6472       // shift.  We know that it is a logical shift by a constant, so adjust the
6473       // mask as appropriate.
6474       if (I.getOpcode() == Instruction::Shl)
6475         MaskV <<= Op1->getZExtValue();
6476       else {
6477         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6478         MaskV = MaskV.lshr(Op1->getZExtValue());
6479       }
6480
6481       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6482                                                    TI->getName());
6483       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6484
6485       // Return the value truncated to the interesting size.
6486       return new TruncInst(And, I.getType());
6487     }
6488   }
6489   
6490   if (Op0->hasOneUse()) {
6491     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6492       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6493       Value *V1, *V2;
6494       ConstantInt *CC;
6495       switch (Op0BO->getOpcode()) {
6496         default: break;
6497         case Instruction::Add:
6498         case Instruction::And:
6499         case Instruction::Or:
6500         case Instruction::Xor: {
6501           // These operators commute.
6502           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6503           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6504               match(Op0BO->getOperand(1),
6505                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6506             Instruction *YS = BinaryOperator::CreateShl(
6507                                             Op0BO->getOperand(0), Op1,
6508                                             Op0BO->getName());
6509             InsertNewInstBefore(YS, I); // (Y << C)
6510             Instruction *X = 
6511               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6512                                      Op0BO->getOperand(1)->getName());
6513             InsertNewInstBefore(X, I);  // (X + (Y << C))
6514             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6515             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6516                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6517           }
6518           
6519           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6520           Value *Op0BOOp1 = Op0BO->getOperand(1);
6521           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6522               match(Op0BOOp1, 
6523                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6524               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6525               V2 == Op1) {
6526             Instruction *YS = BinaryOperator::CreateShl(
6527                                                      Op0BO->getOperand(0), Op1,
6528                                                      Op0BO->getName());
6529             InsertNewInstBefore(YS, I); // (Y << C)
6530             Instruction *XM =
6531               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6532                                         V1->getName()+".mask");
6533             InsertNewInstBefore(XM, I); // X & (CC << C)
6534             
6535             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6536           }
6537         }
6538           
6539         // FALL THROUGH.
6540         case Instruction::Sub: {
6541           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6542           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6543               match(Op0BO->getOperand(0),
6544                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6545             Instruction *YS = BinaryOperator::CreateShl(
6546                                                      Op0BO->getOperand(1), Op1,
6547                                                      Op0BO->getName());
6548             InsertNewInstBefore(YS, I); // (Y << C)
6549             Instruction *X =
6550               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6551                                      Op0BO->getOperand(0)->getName());
6552             InsertNewInstBefore(X, I);  // (X + (Y << C))
6553             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6554             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6555                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6556           }
6557           
6558           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6559           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6560               match(Op0BO->getOperand(0),
6561                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6562                           m_ConstantInt(CC))) && V2 == Op1 &&
6563               cast<BinaryOperator>(Op0BO->getOperand(0))
6564                   ->getOperand(0)->hasOneUse()) {
6565             Instruction *YS = BinaryOperator::CreateShl(
6566                                                      Op0BO->getOperand(1), Op1,
6567                                                      Op0BO->getName());
6568             InsertNewInstBefore(YS, I); // (Y << C)
6569             Instruction *XM =
6570               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6571                                         V1->getName()+".mask");
6572             InsertNewInstBefore(XM, I); // X & (CC << C)
6573             
6574             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6575           }
6576           
6577           break;
6578         }
6579       }
6580       
6581       
6582       // If the operand is an bitwise operator with a constant RHS, and the
6583       // shift is the only use, we can pull it out of the shift.
6584       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6585         bool isValid = true;     // Valid only for And, Or, Xor
6586         bool highBitSet = false; // Transform if high bit of constant set?
6587         
6588         switch (Op0BO->getOpcode()) {
6589           default: isValid = false; break;   // Do not perform transform!
6590           case Instruction::Add:
6591             isValid = isLeftShift;
6592             break;
6593           case Instruction::Or:
6594           case Instruction::Xor:
6595             highBitSet = false;
6596             break;
6597           case Instruction::And:
6598             highBitSet = true;
6599             break;
6600         }
6601         
6602         // If this is a signed shift right, and the high bit is modified
6603         // by the logical operation, do not perform the transformation.
6604         // The highBitSet boolean indicates the value of the high bit of
6605         // the constant which would cause it to be modified for this
6606         // operation.
6607         //
6608         if (isValid && I.getOpcode() == Instruction::AShr)
6609           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6610         
6611         if (isValid) {
6612           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6613           
6614           Instruction *NewShift =
6615             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6616           InsertNewInstBefore(NewShift, I);
6617           NewShift->takeName(Op0BO);
6618           
6619           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6620                                         NewRHS);
6621         }
6622       }
6623     }
6624   }
6625   
6626   // Find out if this is a shift of a shift by a constant.
6627   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6628   if (ShiftOp && !ShiftOp->isShift())
6629     ShiftOp = 0;
6630   
6631   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6632     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6633     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6634     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6635     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6636     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6637     Value *X = ShiftOp->getOperand(0);
6638     
6639     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6640     if (AmtSum > TypeBits)
6641       AmtSum = TypeBits;
6642     
6643     const IntegerType *Ty = cast<IntegerType>(I.getType());
6644     
6645     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6646     if (I.getOpcode() == ShiftOp->getOpcode()) {
6647       return BinaryOperator::Create(I.getOpcode(), X,
6648                                     ConstantInt::get(Ty, AmtSum));
6649     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6650                I.getOpcode() == Instruction::AShr) {
6651       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6652       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6653     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6654                I.getOpcode() == Instruction::LShr) {
6655       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6656       Instruction *Shift =
6657         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6658       InsertNewInstBefore(Shift, I);
6659
6660       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6661       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6662     }
6663     
6664     // Okay, if we get here, one shift must be left, and the other shift must be
6665     // right.  See if the amounts are equal.
6666     if (ShiftAmt1 == ShiftAmt2) {
6667       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6668       if (I.getOpcode() == Instruction::Shl) {
6669         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6670         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6671       }
6672       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6673       if (I.getOpcode() == Instruction::LShr) {
6674         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6675         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6676       }
6677       // We can simplify ((X << C) >>s C) into a trunc + sext.
6678       // NOTE: we could do this for any C, but that would make 'unusual' integer
6679       // types.  For now, just stick to ones well-supported by the code
6680       // generators.
6681       const Type *SExtType = 0;
6682       switch (Ty->getBitWidth() - ShiftAmt1) {
6683       case 1  :
6684       case 8  :
6685       case 16 :
6686       case 32 :
6687       case 64 :
6688       case 128:
6689         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6690         break;
6691       default: break;
6692       }
6693       if (SExtType) {
6694         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6695         InsertNewInstBefore(NewTrunc, I);
6696         return new SExtInst(NewTrunc, Ty);
6697       }
6698       // Otherwise, we can't handle it yet.
6699     } else if (ShiftAmt1 < ShiftAmt2) {
6700       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6701       
6702       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6703       if (I.getOpcode() == Instruction::Shl) {
6704         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6705                ShiftOp->getOpcode() == Instruction::AShr);
6706         Instruction *Shift =
6707           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6708         InsertNewInstBefore(Shift, I);
6709         
6710         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6711         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6712       }
6713       
6714       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6715       if (I.getOpcode() == Instruction::LShr) {
6716         assert(ShiftOp->getOpcode() == Instruction::Shl);
6717         Instruction *Shift =
6718           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6719         InsertNewInstBefore(Shift, I);
6720         
6721         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6722         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6723       }
6724       
6725       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6726     } else {
6727       assert(ShiftAmt2 < ShiftAmt1);
6728       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6729
6730       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6731       if (I.getOpcode() == Instruction::Shl) {
6732         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6733                ShiftOp->getOpcode() == Instruction::AShr);
6734         Instruction *Shift =
6735           BinaryOperator::Create(ShiftOp->getOpcode(), X,
6736                                  ConstantInt::get(Ty, ShiftDiff));
6737         InsertNewInstBefore(Shift, I);
6738         
6739         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6740         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6741       }
6742       
6743       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6744       if (I.getOpcode() == Instruction::LShr) {
6745         assert(ShiftOp->getOpcode() == Instruction::Shl);
6746         Instruction *Shift =
6747           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6748         InsertNewInstBefore(Shift, I);
6749         
6750         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6751         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6752       }
6753       
6754       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6755     }
6756   }
6757   return 0;
6758 }
6759
6760
6761 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6762 /// expression.  If so, decompose it, returning some value X, such that Val is
6763 /// X*Scale+Offset.
6764 ///
6765 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6766                                         int &Offset) {
6767   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6768   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6769     Offset = CI->getZExtValue();
6770     Scale  = 0;
6771     return ConstantInt::get(Type::Int32Ty, 0);
6772   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6773     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6774       if (I->getOpcode() == Instruction::Shl) {
6775         // This is a value scaled by '1 << the shift amt'.
6776         Scale = 1U << RHS->getZExtValue();
6777         Offset = 0;
6778         return I->getOperand(0);
6779       } else if (I->getOpcode() == Instruction::Mul) {
6780         // This value is scaled by 'RHS'.
6781         Scale = RHS->getZExtValue();
6782         Offset = 0;
6783         return I->getOperand(0);
6784       } else if (I->getOpcode() == Instruction::Add) {
6785         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6786         // where C1 is divisible by C2.
6787         unsigned SubScale;
6788         Value *SubVal = 
6789           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6790         Offset += RHS->getZExtValue();
6791         Scale = SubScale;
6792         return SubVal;
6793       }
6794     }
6795   }
6796
6797   // Otherwise, we can't look past this.
6798   Scale = 1;
6799   Offset = 0;
6800   return Val;
6801 }
6802
6803
6804 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6805 /// try to eliminate the cast by moving the type information into the alloc.
6806 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6807                                                    AllocationInst &AI) {
6808   const PointerType *PTy = cast<PointerType>(CI.getType());
6809   
6810   // Remove any uses of AI that are dead.
6811   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6812   
6813   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6814     Instruction *User = cast<Instruction>(*UI++);
6815     if (isInstructionTriviallyDead(User)) {
6816       while (UI != E && *UI == User)
6817         ++UI; // If this instruction uses AI more than once, don't break UI.
6818       
6819       ++NumDeadInst;
6820       DOUT << "IC: DCE: " << *User;
6821       EraseInstFromFunction(*User);
6822     }
6823   }
6824   
6825   // Get the type really allocated and the type casted to.
6826   const Type *AllocElTy = AI.getAllocatedType();
6827   const Type *CastElTy = PTy->getElementType();
6828   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6829
6830   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6831   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6832   if (CastElTyAlign < AllocElTyAlign) return 0;
6833
6834   // If the allocation has multiple uses, only promote it if we are strictly
6835   // increasing the alignment of the resultant allocation.  If we keep it the
6836   // same, we open the door to infinite loops of various kinds.
6837   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6838
6839   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6840   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6841   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6842
6843   // See if we can satisfy the modulus by pulling a scale out of the array
6844   // size argument.
6845   unsigned ArraySizeScale;
6846   int ArrayOffset;
6847   Value *NumElements = // See if the array size is a decomposable linear expr.
6848     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6849  
6850   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6851   // do the xform.
6852   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6853       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6854
6855   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6856   Value *Amt = 0;
6857   if (Scale == 1) {
6858     Amt = NumElements;
6859   } else {
6860     // If the allocation size is constant, form a constant mul expression
6861     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6862     if (isa<ConstantInt>(NumElements))
6863       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6864     // otherwise multiply the amount and the number of elements
6865     else if (Scale != 1) {
6866       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6867       Amt = InsertNewInstBefore(Tmp, AI);
6868     }
6869   }
6870   
6871   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6872     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6873     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6874     Amt = InsertNewInstBefore(Tmp, AI);
6875   }
6876   
6877   AllocationInst *New;
6878   if (isa<MallocInst>(AI))
6879     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6880   else
6881     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6882   InsertNewInstBefore(New, AI);
6883   New->takeName(&AI);
6884   
6885   // If the allocation has multiple uses, insert a cast and change all things
6886   // that used it to use the new cast.  This will also hack on CI, but it will
6887   // die soon.
6888   if (!AI.hasOneUse()) {
6889     AddUsesToWorkList(AI);
6890     // New is the allocation instruction, pointer typed. AI is the original
6891     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6892     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6893     InsertNewInstBefore(NewCast, AI);
6894     AI.replaceAllUsesWith(NewCast);
6895   }
6896   return ReplaceInstUsesWith(CI, New);
6897 }
6898
6899 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6900 /// and return it as type Ty without inserting any new casts and without
6901 /// changing the computed value.  This is used by code that tries to decide
6902 /// whether promoting or shrinking integer operations to wider or smaller types
6903 /// will allow us to eliminate a truncate or extend.
6904 ///
6905 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6906 /// extension operation if Ty is larger.
6907 ///
6908 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
6909 /// should return true if trunc(V) can be computed by computing V in the smaller
6910 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
6911 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6912 /// efficiently truncated.
6913 ///
6914 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6915 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6916 /// the final result.
6917 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6918                                               unsigned CastOpc,
6919                                               int &NumCastsRemoved) {
6920   // We can always evaluate constants in another type.
6921   if (isa<ConstantInt>(V))
6922     return true;
6923   
6924   Instruction *I = dyn_cast<Instruction>(V);
6925   if (!I) return false;
6926   
6927   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6928   
6929   // If this is an extension or truncate, we can often eliminate it.
6930   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6931     // If this is a cast from the destination type, we can trivially eliminate
6932     // it, and this will remove a cast overall.
6933     if (I->getOperand(0)->getType() == Ty) {
6934       // If the first operand is itself a cast, and is eliminable, do not count
6935       // this as an eliminable cast.  We would prefer to eliminate those two
6936       // casts first.
6937       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
6938         ++NumCastsRemoved;
6939       return true;
6940     }
6941   }
6942
6943   // We can't extend or shrink something that has multiple uses: doing so would
6944   // require duplicating the instruction in general, which isn't profitable.
6945   if (!I->hasOneUse()) return false;
6946
6947   switch (I->getOpcode()) {
6948   case Instruction::Add:
6949   case Instruction::Sub:
6950   case Instruction::Mul:
6951   case Instruction::And:
6952   case Instruction::Or:
6953   case Instruction::Xor:
6954     // These operators can all arbitrarily be extended or truncated.
6955     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6956                                       NumCastsRemoved) &&
6957            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6958                                       NumCastsRemoved);
6959
6960   case Instruction::Shl:
6961     // If we are truncating the result of this SHL, and if it's a shift of a
6962     // constant amount, we can always perform a SHL in a smaller type.
6963     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6964       uint32_t BitWidth = Ty->getBitWidth();
6965       if (BitWidth < OrigTy->getBitWidth() && 
6966           CI->getLimitedValue(BitWidth) < BitWidth)
6967         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6968                                           NumCastsRemoved);
6969     }
6970     break;
6971   case Instruction::LShr:
6972     // If this is a truncate of a logical shr, we can truncate it to a smaller
6973     // lshr iff we know that the bits we would otherwise be shifting in are
6974     // already zeros.
6975     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6976       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6977       uint32_t BitWidth = Ty->getBitWidth();
6978       if (BitWidth < OrigBitWidth &&
6979           MaskedValueIsZero(I->getOperand(0),
6980             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6981           CI->getLimitedValue(BitWidth) < BitWidth) {
6982         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6983                                           NumCastsRemoved);
6984       }
6985     }
6986     break;
6987   case Instruction::ZExt:
6988   case Instruction::SExt:
6989   case Instruction::Trunc:
6990     // If this is the same kind of case as our original (e.g. zext+zext), we
6991     // can safely replace it.  Note that replacing it does not reduce the number
6992     // of casts in the input.
6993     if (I->getOpcode() == CastOpc)
6994       return true;
6995     break;
6996   case Instruction::Select: {
6997     SelectInst *SI = cast<SelectInst>(I);
6998     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
6999                                       NumCastsRemoved) &&
7000            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7001                                       NumCastsRemoved);
7002   }
7003   case Instruction::PHI: {
7004     // We can change a phi if we can change all operands.
7005     PHINode *PN = cast<PHINode>(I);
7006     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7007       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7008                                       NumCastsRemoved))
7009         return false;
7010     return true;
7011   }
7012   default:
7013     // TODO: Can handle more cases here.
7014     break;
7015   }
7016   
7017   return false;
7018 }
7019
7020 /// EvaluateInDifferentType - Given an expression that 
7021 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7022 /// evaluate the expression.
7023 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7024                                              bool isSigned) {
7025   if (Constant *C = dyn_cast<Constant>(V))
7026     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7027
7028   // Otherwise, it must be an instruction.
7029   Instruction *I = cast<Instruction>(V);
7030   Instruction *Res = 0;
7031   switch (I->getOpcode()) {
7032   case Instruction::Add:
7033   case Instruction::Sub:
7034   case Instruction::Mul:
7035   case Instruction::And:
7036   case Instruction::Or:
7037   case Instruction::Xor:
7038   case Instruction::AShr:
7039   case Instruction::LShr:
7040   case Instruction::Shl: {
7041     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7042     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7043     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7044                                  LHS, RHS);
7045     break;
7046   }    
7047   case Instruction::Trunc:
7048   case Instruction::ZExt:
7049   case Instruction::SExt:
7050     // If the source type of the cast is the type we're trying for then we can
7051     // just return the source.  There's no need to insert it because it is not
7052     // new.
7053     if (I->getOperand(0)->getType() == Ty)
7054       return I->getOperand(0);
7055     
7056     // Otherwise, must be the same type of cast, so just reinsert a new one.
7057     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7058                            Ty);
7059     break;
7060   case Instruction::Select: {
7061     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7062     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7063     Res = SelectInst::Create(I->getOperand(0), True, False);
7064     break;
7065   }
7066   case Instruction::PHI: {
7067     PHINode *OPN = cast<PHINode>(I);
7068     PHINode *NPN = PHINode::Create(Ty);
7069     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7070       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7071       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7072     }
7073     Res = NPN;
7074     break;
7075   }
7076   default: 
7077     // TODO: Can handle more cases here.
7078     assert(0 && "Unreachable!");
7079     break;
7080   }
7081   
7082   Res->takeName(I);
7083   return InsertNewInstBefore(Res, *I);
7084 }
7085
7086 /// @brief Implement the transforms common to all CastInst visitors.
7087 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7088   Value *Src = CI.getOperand(0);
7089
7090   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7091   // eliminate it now.
7092   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7093     if (Instruction::CastOps opc = 
7094         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7095       // The first cast (CSrc) is eliminable so we need to fix up or replace
7096       // the second cast (CI). CSrc will then have a good chance of being dead.
7097       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7098     }
7099   }
7100
7101   // If we are casting a select then fold the cast into the select
7102   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7103     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7104       return NV;
7105
7106   // If we are casting a PHI then fold the cast into the PHI
7107   if (isa<PHINode>(Src))
7108     if (Instruction *NV = FoldOpIntoPhi(CI))
7109       return NV;
7110   
7111   return 0;
7112 }
7113
7114 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7115 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7116   Value *Src = CI.getOperand(0);
7117   
7118   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7119     // If casting the result of a getelementptr instruction with no offset, turn
7120     // this into a cast of the original pointer!
7121     if (GEP->hasAllZeroIndices()) {
7122       // Changing the cast operand is usually not a good idea but it is safe
7123       // here because the pointer operand is being replaced with another 
7124       // pointer operand so the opcode doesn't need to change.
7125       AddToWorkList(GEP);
7126       CI.setOperand(0, GEP->getOperand(0));
7127       return &CI;
7128     }
7129     
7130     // If the GEP has a single use, and the base pointer is a bitcast, and the
7131     // GEP computes a constant offset, see if we can convert these three
7132     // instructions into fewer.  This typically happens with unions and other
7133     // non-type-safe code.
7134     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7135       if (GEP->hasAllConstantIndices()) {
7136         // We are guaranteed to get a constant from EmitGEPOffset.
7137         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7138         int64_t Offset = OffsetV->getSExtValue();
7139         
7140         // Get the base pointer input of the bitcast, and the type it points to.
7141         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7142         const Type *GEPIdxTy =
7143           cast<PointerType>(OrigBase->getType())->getElementType();
7144         if (GEPIdxTy->isSized()) {
7145           SmallVector<Value*, 8> NewIndices;
7146           
7147           // Start with the index over the outer type.  Note that the type size
7148           // might be zero (even if the offset isn't zero) if the indexed type
7149           // is something like [0 x {int, int}]
7150           const Type *IntPtrTy = TD->getIntPtrType();
7151           int64_t FirstIdx = 0;
7152           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7153             FirstIdx = Offset/TySize;
7154             Offset %= TySize;
7155           
7156             // Handle silly modulus not returning values values [0..TySize).
7157             if (Offset < 0) {
7158               --FirstIdx;
7159               Offset += TySize;
7160               assert(Offset >= 0);
7161             }
7162             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7163           }
7164           
7165           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7166
7167           // Index into the types.  If we fail, set OrigBase to null.
7168           while (Offset) {
7169             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7170               const StructLayout *SL = TD->getStructLayout(STy);
7171               if (Offset < (int64_t)SL->getSizeInBytes()) {
7172                 unsigned Elt = SL->getElementContainingOffset(Offset);
7173                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7174               
7175                 Offset -= SL->getElementOffset(Elt);
7176                 GEPIdxTy = STy->getElementType(Elt);
7177               } else {
7178                 // Otherwise, we can't index into this, bail out.
7179                 Offset = 0;
7180                 OrigBase = 0;
7181               }
7182             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7183               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7184               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7185                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7186                 Offset %= EltSize;
7187               } else {
7188                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7189               }
7190               GEPIdxTy = STy->getElementType();
7191             } else {
7192               // Otherwise, we can't index into this, bail out.
7193               Offset = 0;
7194               OrigBase = 0;
7195             }
7196           }
7197           if (OrigBase) {
7198             // If we were able to index down into an element, create the GEP
7199             // and bitcast the result.  This eliminates one bitcast, potentially
7200             // two.
7201             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7202                                                           NewIndices.begin(),
7203                                                           NewIndices.end(), "");
7204             InsertNewInstBefore(NGEP, CI);
7205             NGEP->takeName(GEP);
7206             
7207             if (isa<BitCastInst>(CI))
7208               return new BitCastInst(NGEP, CI.getType());
7209             assert(isa<PtrToIntInst>(CI));
7210             return new PtrToIntInst(NGEP, CI.getType());
7211           }
7212         }
7213       }      
7214     }
7215   }
7216     
7217   return commonCastTransforms(CI);
7218 }
7219
7220
7221
7222 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7223 /// integer types. This function implements the common transforms for all those
7224 /// cases.
7225 /// @brief Implement the transforms common to CastInst with integer operands
7226 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7227   if (Instruction *Result = commonCastTransforms(CI))
7228     return Result;
7229
7230   Value *Src = CI.getOperand(0);
7231   const Type *SrcTy = Src->getType();
7232   const Type *DestTy = CI.getType();
7233   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7234   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7235
7236   // See if we can simplify any instructions used by the LHS whose sole 
7237   // purpose is to compute bits we don't care about.
7238   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7239   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7240                            KnownZero, KnownOne))
7241     return &CI;
7242
7243   // If the source isn't an instruction or has more than one use then we
7244   // can't do anything more. 
7245   Instruction *SrcI = dyn_cast<Instruction>(Src);
7246   if (!SrcI || !Src->hasOneUse())
7247     return 0;
7248
7249   // Attempt to propagate the cast into the instruction for int->int casts.
7250   int NumCastsRemoved = 0;
7251   if (!isa<BitCastInst>(CI) &&
7252       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7253                                  CI.getOpcode(), NumCastsRemoved)) {
7254     // If this cast is a truncate, evaluting in a different type always
7255     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7256     // we need to do an AND to maintain the clear top-part of the computation,
7257     // so we require that the input have eliminated at least one cast.  If this
7258     // is a sign extension, we insert two new casts (to do the extension) so we
7259     // require that two casts have been eliminated.
7260     bool DoXForm;
7261     switch (CI.getOpcode()) {
7262     default:
7263       // All the others use floating point so we shouldn't actually 
7264       // get here because of the check above.
7265       assert(0 && "Unknown cast type");
7266     case Instruction::Trunc:
7267       DoXForm = true;
7268       break;
7269     case Instruction::ZExt:
7270       DoXForm = NumCastsRemoved >= 1;
7271       break;
7272     case Instruction::SExt:
7273       DoXForm = NumCastsRemoved >= 2;
7274       break;
7275     }
7276     
7277     if (DoXForm) {
7278       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7279                                            CI.getOpcode() == Instruction::SExt);
7280       assert(Res->getType() == DestTy);
7281       switch (CI.getOpcode()) {
7282       default: assert(0 && "Unknown cast type!");
7283       case Instruction::Trunc:
7284       case Instruction::BitCast:
7285         // Just replace this cast with the result.
7286         return ReplaceInstUsesWith(CI, Res);
7287       case Instruction::ZExt: {
7288         // We need to emit an AND to clear the high bits.
7289         assert(SrcBitSize < DestBitSize && "Not a zext?");
7290         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7291                                                             SrcBitSize));
7292         return BinaryOperator::CreateAnd(Res, C);
7293       }
7294       case Instruction::SExt:
7295         // We need to emit a cast to truncate, then a cast to sext.
7296         return CastInst::Create(Instruction::SExt,
7297             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7298                              CI), DestTy);
7299       }
7300     }
7301   }
7302   
7303   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7304   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7305
7306   switch (SrcI->getOpcode()) {
7307   case Instruction::Add:
7308   case Instruction::Mul:
7309   case Instruction::And:
7310   case Instruction::Or:
7311   case Instruction::Xor:
7312     // If we are discarding information, rewrite.
7313     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7314       // Don't insert two casts if they cannot be eliminated.  We allow 
7315       // two casts to be inserted if the sizes are the same.  This could 
7316       // only be converting signedness, which is a noop.
7317       if (DestBitSize == SrcBitSize || 
7318           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7319           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7320         Instruction::CastOps opcode = CI.getOpcode();
7321         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7322         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7323         return BinaryOperator::Create(
7324             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7325       }
7326     }
7327
7328     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7329     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7330         SrcI->getOpcode() == Instruction::Xor &&
7331         Op1 == ConstantInt::getTrue() &&
7332         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7333       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7334       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7335     }
7336     break;
7337   case Instruction::SDiv:
7338   case Instruction::UDiv:
7339   case Instruction::SRem:
7340   case Instruction::URem:
7341     // If we are just changing the sign, rewrite.
7342     if (DestBitSize == SrcBitSize) {
7343       // Don't insert two casts if they cannot be eliminated.  We allow 
7344       // two casts to be inserted if the sizes are the same.  This could 
7345       // only be converting signedness, which is a noop.
7346       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7347           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7348         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7349                                               Op0, DestTy, SrcI);
7350         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7351                                               Op1, DestTy, SrcI);
7352         return BinaryOperator::Create(
7353           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7354       }
7355     }
7356     break;
7357
7358   case Instruction::Shl:
7359     // Allow changing the sign of the source operand.  Do not allow 
7360     // changing the size of the shift, UNLESS the shift amount is a 
7361     // constant.  We must not change variable sized shifts to a smaller 
7362     // size, because it is undefined to shift more bits out than exist 
7363     // in the value.
7364     if (DestBitSize == SrcBitSize ||
7365         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7366       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7367           Instruction::BitCast : Instruction::Trunc);
7368       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7369       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7370       return BinaryOperator::CreateShl(Op0c, Op1c);
7371     }
7372     break;
7373   case Instruction::AShr:
7374     // If this is a signed shr, and if all bits shifted in are about to be
7375     // truncated off, turn it into an unsigned shr to allow greater
7376     // simplifications.
7377     if (DestBitSize < SrcBitSize &&
7378         isa<ConstantInt>(Op1)) {
7379       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7380       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7381         // Insert the new logical shift right.
7382         return BinaryOperator::CreateLShr(Op0, Op1);
7383       }
7384     }
7385     break;
7386   }
7387   return 0;
7388 }
7389
7390 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7391   if (Instruction *Result = commonIntCastTransforms(CI))
7392     return Result;
7393   
7394   Value *Src = CI.getOperand(0);
7395   const Type *Ty = CI.getType();
7396   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7397   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7398   
7399   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7400     switch (SrcI->getOpcode()) {
7401     default: break;
7402     case Instruction::LShr:
7403       // We can shrink lshr to something smaller if we know the bits shifted in
7404       // are already zeros.
7405       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7406         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7407         
7408         // Get a mask for the bits shifting in.
7409         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7410         Value* SrcIOp0 = SrcI->getOperand(0);
7411         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7412           if (ShAmt >= DestBitWidth)        // All zeros.
7413             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7414
7415           // Okay, we can shrink this.  Truncate the input, then return a new
7416           // shift.
7417           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7418           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7419                                        Ty, CI);
7420           return BinaryOperator::CreateLShr(V1, V2);
7421         }
7422       } else {     // This is a variable shr.
7423         
7424         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7425         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7426         // loop-invariant and CSE'd.
7427         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7428           Value *One = ConstantInt::get(SrcI->getType(), 1);
7429
7430           Value *V = InsertNewInstBefore(
7431               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7432                                      "tmp"), CI);
7433           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7434                                                             SrcI->getOperand(0),
7435                                                             "tmp"), CI);
7436           Value *Zero = Constant::getNullValue(V->getType());
7437           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7438         }
7439       }
7440       break;
7441     }
7442   }
7443   
7444   return 0;
7445 }
7446
7447 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7448 /// in order to eliminate the icmp.
7449 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7450                                              bool DoXform) {
7451   // If we are just checking for a icmp eq of a single bit and zext'ing it
7452   // to an integer, then shift the bit to the appropriate place and then
7453   // cast to integer to avoid the comparison.
7454   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7455     const APInt &Op1CV = Op1C->getValue();
7456       
7457     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7458     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7459     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7460         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7461       if (!DoXform) return ICI;
7462
7463       Value *In = ICI->getOperand(0);
7464       Value *Sh = ConstantInt::get(In->getType(),
7465                                    In->getType()->getPrimitiveSizeInBits()-1);
7466       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7467                                                         In->getName()+".lobit"),
7468                                CI);
7469       if (In->getType() != CI.getType())
7470         In = CastInst::CreateIntegerCast(In, CI.getType(),
7471                                          false/*ZExt*/, "tmp", &CI);
7472
7473       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7474         Constant *One = ConstantInt::get(In->getType(), 1);
7475         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7476                                                          In->getName()+".not"),
7477                                  CI);
7478       }
7479
7480       return ReplaceInstUsesWith(CI, In);
7481     }
7482       
7483       
7484       
7485     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7486     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7487     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7488     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7489     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7490     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7491     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7492     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7493     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7494         // This only works for EQ and NE
7495         ICI->isEquality()) {
7496       // If Op1C some other power of two, convert:
7497       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7498       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7499       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7500       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7501         
7502       APInt KnownZeroMask(~KnownZero);
7503       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7504         if (!DoXform) return ICI;
7505
7506         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7507         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7508           // (X&4) == 2 --> false
7509           // (X&4) != 2 --> true
7510           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7511           Res = ConstantExpr::getZExt(Res, CI.getType());
7512           return ReplaceInstUsesWith(CI, Res);
7513         }
7514           
7515         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7516         Value *In = ICI->getOperand(0);
7517         if (ShiftAmt) {
7518           // Perform a logical shr by shiftamt.
7519           // Insert the shift to put the result in the low bit.
7520           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7521                                   ConstantInt::get(In->getType(), ShiftAmt),
7522                                                    In->getName()+".lobit"), CI);
7523         }
7524           
7525         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7526           Constant *One = ConstantInt::get(In->getType(), 1);
7527           In = BinaryOperator::CreateXor(In, One, "tmp");
7528           InsertNewInstBefore(cast<Instruction>(In), CI);
7529         }
7530           
7531         if (CI.getType() == In->getType())
7532           return ReplaceInstUsesWith(CI, In);
7533         else
7534           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7535       }
7536     }
7537   }
7538
7539   return 0;
7540 }
7541
7542 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7543   // If one of the common conversion will work ..
7544   if (Instruction *Result = commonIntCastTransforms(CI))
7545     return Result;
7546
7547   Value *Src = CI.getOperand(0);
7548
7549   // If this is a cast of a cast
7550   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7551     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7552     // types and if the sizes are just right we can convert this into a logical
7553     // 'and' which will be much cheaper than the pair of casts.
7554     if (isa<TruncInst>(CSrc)) {
7555       // Get the sizes of the types involved
7556       Value *A = CSrc->getOperand(0);
7557       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7558       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7559       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7560       // If we're actually extending zero bits and the trunc is a no-op
7561       if (MidSize < DstSize && SrcSize == DstSize) {
7562         // Replace both of the casts with an And of the type mask.
7563         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7564         Constant *AndConst = ConstantInt::get(AndValue);
7565         Instruction *And = 
7566           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7567         // Unfortunately, if the type changed, we need to cast it back.
7568         if (And->getType() != CI.getType()) {
7569           And->setName(CSrc->getName()+".mask");
7570           InsertNewInstBefore(And, CI);
7571           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7572         }
7573         return And;
7574       }
7575     }
7576   }
7577
7578   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7579     return transformZExtICmp(ICI, CI);
7580
7581   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7582   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7583     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7584     // of the (zext icmp) will be transformed.
7585     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7586     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7587     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7588         (transformZExtICmp(LHS, CI, false) ||
7589          transformZExtICmp(RHS, CI, false))) {
7590       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7591       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7592       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7593     }
7594   }
7595
7596   return 0;
7597 }
7598
7599 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7600   if (Instruction *I = commonIntCastTransforms(CI))
7601     return I;
7602   
7603   Value *Src = CI.getOperand(0);
7604   
7605   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7606   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7607   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7608     // If we are just checking for a icmp eq of a single bit and zext'ing it
7609     // to an integer, then shift the bit to the appropriate place and then
7610     // cast to integer to avoid the comparison.
7611     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7612       const APInt &Op1CV = Op1C->getValue();
7613       
7614       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7615       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7616       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7617           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7618         Value *In = ICI->getOperand(0);
7619         Value *Sh = ConstantInt::get(In->getType(),
7620                                      In->getType()->getPrimitiveSizeInBits()-1);
7621         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7622                                                         In->getName()+".lobit"),
7623                                  CI);
7624         if (In->getType() != CI.getType())
7625           In = CastInst::CreateIntegerCast(In, CI.getType(),
7626                                            true/*SExt*/, "tmp", &CI);
7627         
7628         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7629           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7630                                      In->getName()+".not"), CI);
7631         
7632         return ReplaceInstUsesWith(CI, In);
7633       }
7634     }
7635   }
7636
7637   // See if the value being truncated is already sign extended.  If so, just
7638   // eliminate the trunc/sext pair.
7639   if (getOpcode(Src) == Instruction::Trunc) {
7640     Value *Op = cast<User>(Src)->getOperand(0);
7641     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
7642     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
7643     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7644     unsigned NumSignBits = ComputeNumSignBits(Op);
7645
7646     if (OpBits == DestBits) {
7647       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7648       // bits, it is already ready.
7649       if (NumSignBits > DestBits-MidBits)
7650         return ReplaceInstUsesWith(CI, Op);
7651     } else if (OpBits < DestBits) {
7652       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7653       // bits, just sext from i32.
7654       if (NumSignBits > OpBits-MidBits)
7655         return new SExtInst(Op, CI.getType(), "tmp");
7656     } else {
7657       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7658       // bits, just truncate to i32.
7659       if (NumSignBits > OpBits-MidBits)
7660         return new TruncInst(Op, CI.getType(), "tmp");
7661     }
7662   }
7663       
7664   return 0;
7665 }
7666
7667 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7668 /// in the specified FP type without changing its value.
7669 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7670   APFloat F = CFP->getValueAPF();
7671   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7672     return ConstantFP::get(F);
7673   return 0;
7674 }
7675
7676 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7677 /// through it until we get the source value.
7678 static Value *LookThroughFPExtensions(Value *V) {
7679   if (Instruction *I = dyn_cast<Instruction>(V))
7680     if (I->getOpcode() == Instruction::FPExt)
7681       return LookThroughFPExtensions(I->getOperand(0));
7682   
7683   // If this value is a constant, return the constant in the smallest FP type
7684   // that can accurately represent it.  This allows us to turn
7685   // (float)((double)X+2.0) into x+2.0f.
7686   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7687     if (CFP->getType() == Type::PPC_FP128Ty)
7688       return V;  // No constant folding of this.
7689     // See if the value can be truncated to float and then reextended.
7690     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7691       return V;
7692     if (CFP->getType() == Type::DoubleTy)
7693       return V;  // Won't shrink.
7694     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7695       return V;
7696     // Don't try to shrink to various long double types.
7697   }
7698   
7699   return V;
7700 }
7701
7702 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7703   if (Instruction *I = commonCastTransforms(CI))
7704     return I;
7705   
7706   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7707   // smaller than the destination type, we can eliminate the truncate by doing
7708   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7709   // many builtins (sqrt, etc).
7710   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7711   if (OpI && OpI->hasOneUse()) {
7712     switch (OpI->getOpcode()) {
7713     default: break;
7714     case Instruction::Add:
7715     case Instruction::Sub:
7716     case Instruction::Mul:
7717     case Instruction::FDiv:
7718     case Instruction::FRem:
7719       const Type *SrcTy = OpI->getType();
7720       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7721       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7722       if (LHSTrunc->getType() != SrcTy && 
7723           RHSTrunc->getType() != SrcTy) {
7724         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7725         // If the source types were both smaller than the destination type of
7726         // the cast, do this xform.
7727         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7728             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7729           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7730                                       CI.getType(), CI);
7731           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7732                                       CI.getType(), CI);
7733           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7734         }
7735       }
7736       break;  
7737     }
7738   }
7739   return 0;
7740 }
7741
7742 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7743   return commonCastTransforms(CI);
7744 }
7745
7746 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7747   // fptoui(uitofp(X)) --> X  if the intermediate type has enough bits in its
7748   // mantissa to accurately represent all values of X.  For example, do not
7749   // do this with i64->float->i64.
7750   if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7751     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7752         (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7753                     SrcI->getType()->getFPMantissaWidth())
7754       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7755
7756   return commonCastTransforms(FI);
7757 }
7758
7759 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7760   // fptosi(sitofp(X)) --> X  if the intermediate type has enough bits in its
7761   // mantissa to accurately represent all values of X.  For example, do not
7762   // do this with i64->float->i64.
7763   if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7764     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7765         (int)FI.getType()->getPrimitiveSizeInBits() <= 
7766                     SrcI->getType()->getFPMantissaWidth())
7767       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7768   
7769   return commonCastTransforms(FI);
7770 }
7771
7772 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7773   return commonCastTransforms(CI);
7774 }
7775
7776 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7777   return commonCastTransforms(CI);
7778 }
7779
7780 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7781   return commonPointerCastTransforms(CI);
7782 }
7783
7784 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7785   if (Instruction *I = commonCastTransforms(CI))
7786     return I;
7787   
7788   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7789   if (!DestPointee->isSized()) return 0;
7790
7791   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7792   ConstantInt *Cst;
7793   Value *X;
7794   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7795                                     m_ConstantInt(Cst)))) {
7796     // If the source and destination operands have the same type, see if this
7797     // is a single-index GEP.
7798     if (X->getType() == CI.getType()) {
7799       // Get the size of the pointee type.
7800       uint64_t Size = TD->getABITypeSize(DestPointee);
7801
7802       // Convert the constant to intptr type.
7803       APInt Offset = Cst->getValue();
7804       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7805
7806       // If Offset is evenly divisible by Size, we can do this xform.
7807       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7808         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7809         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7810       }
7811     }
7812     // TODO: Could handle other cases, e.g. where add is indexing into field of
7813     // struct etc.
7814   } else if (CI.getOperand(0)->hasOneUse() &&
7815              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7816     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7817     // "inttoptr+GEP" instead of "add+intptr".
7818     
7819     // Get the size of the pointee type.
7820     uint64_t Size = TD->getABITypeSize(DestPointee);
7821     
7822     // Convert the constant to intptr type.
7823     APInt Offset = Cst->getValue();
7824     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7825     
7826     // If Offset is evenly divisible by Size, we can do this xform.
7827     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7828       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7829       
7830       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7831                                                             "tmp"), CI);
7832       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7833     }
7834   }
7835   return 0;
7836 }
7837
7838 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7839   // If the operands are integer typed then apply the integer transforms,
7840   // otherwise just apply the common ones.
7841   Value *Src = CI.getOperand(0);
7842   const Type *SrcTy = Src->getType();
7843   const Type *DestTy = CI.getType();
7844
7845   if (SrcTy->isInteger() && DestTy->isInteger()) {
7846     if (Instruction *Result = commonIntCastTransforms(CI))
7847       return Result;
7848   } else if (isa<PointerType>(SrcTy)) {
7849     if (Instruction *I = commonPointerCastTransforms(CI))
7850       return I;
7851   } else {
7852     if (Instruction *Result = commonCastTransforms(CI))
7853       return Result;
7854   }
7855
7856
7857   // Get rid of casts from one type to the same type. These are useless and can
7858   // be replaced by the operand.
7859   if (DestTy == Src->getType())
7860     return ReplaceInstUsesWith(CI, Src);
7861
7862   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7863     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7864     const Type *DstElTy = DstPTy->getElementType();
7865     const Type *SrcElTy = SrcPTy->getElementType();
7866     
7867     // If the address spaces don't match, don't eliminate the bitcast, which is
7868     // required for changing types.
7869     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7870       return 0;
7871     
7872     // If we are casting a malloc or alloca to a pointer to a type of the same
7873     // size, rewrite the allocation instruction to allocate the "right" type.
7874     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7875       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7876         return V;
7877     
7878     // If the source and destination are pointers, and this cast is equivalent
7879     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7880     // This can enhance SROA and other transforms that want type-safe pointers.
7881     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7882     unsigned NumZeros = 0;
7883     while (SrcElTy != DstElTy && 
7884            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7885            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7886       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7887       ++NumZeros;
7888     }
7889
7890     // If we found a path from the src to dest, create the getelementptr now.
7891     if (SrcElTy == DstElTy) {
7892       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7893       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
7894                                        ((Instruction*) NULL));
7895     }
7896   }
7897
7898   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7899     if (SVI->hasOneUse()) {
7900       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7901       // a bitconvert to a vector with the same # elts.
7902       if (isa<VectorType>(DestTy) && 
7903           cast<VectorType>(DestTy)->getNumElements() == 
7904                 SVI->getType()->getNumElements()) {
7905         CastInst *Tmp;
7906         // If either of the operands is a cast from CI.getType(), then
7907         // evaluating the shuffle in the casted destination's type will allow
7908         // us to eliminate at least one cast.
7909         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7910              Tmp->getOperand(0)->getType() == DestTy) ||
7911             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7912              Tmp->getOperand(0)->getType() == DestTy)) {
7913           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7914                                                SVI->getOperand(0), DestTy, &CI);
7915           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7916                                                SVI->getOperand(1), DestTy, &CI);
7917           // Return a new shuffle vector.  Use the same element ID's, as we
7918           // know the vector types match #elts.
7919           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7920         }
7921       }
7922     }
7923   }
7924   return 0;
7925 }
7926
7927 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7928 ///   %C = or %A, %B
7929 ///   %D = select %cond, %C, %A
7930 /// into:
7931 ///   %C = select %cond, %B, 0
7932 ///   %D = or %A, %C
7933 ///
7934 /// Assuming that the specified instruction is an operand to the select, return
7935 /// a bitmask indicating which operands of this instruction are foldable if they
7936 /// equal the other incoming value of the select.
7937 ///
7938 static unsigned GetSelectFoldableOperands(Instruction *I) {
7939   switch (I->getOpcode()) {
7940   case Instruction::Add:
7941   case Instruction::Mul:
7942   case Instruction::And:
7943   case Instruction::Or:
7944   case Instruction::Xor:
7945     return 3;              // Can fold through either operand.
7946   case Instruction::Sub:   // Can only fold on the amount subtracted.
7947   case Instruction::Shl:   // Can only fold on the shift amount.
7948   case Instruction::LShr:
7949   case Instruction::AShr:
7950     return 1;
7951   default:
7952     return 0;              // Cannot fold
7953   }
7954 }
7955
7956 /// GetSelectFoldableConstant - For the same transformation as the previous
7957 /// function, return the identity constant that goes into the select.
7958 static Constant *GetSelectFoldableConstant(Instruction *I) {
7959   switch (I->getOpcode()) {
7960   default: assert(0 && "This cannot happen!"); abort();
7961   case Instruction::Add:
7962   case Instruction::Sub:
7963   case Instruction::Or:
7964   case Instruction::Xor:
7965   case Instruction::Shl:
7966   case Instruction::LShr:
7967   case Instruction::AShr:
7968     return Constant::getNullValue(I->getType());
7969   case Instruction::And:
7970     return Constant::getAllOnesValue(I->getType());
7971   case Instruction::Mul:
7972     return ConstantInt::get(I->getType(), 1);
7973   }
7974 }
7975
7976 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7977 /// have the same opcode and only one use each.  Try to simplify this.
7978 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7979                                           Instruction *FI) {
7980   if (TI->getNumOperands() == 1) {
7981     // If this is a non-volatile load or a cast from the same type,
7982     // merge.
7983     if (TI->isCast()) {
7984       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7985         return 0;
7986     } else {
7987       return 0;  // unknown unary op.
7988     }
7989
7990     // Fold this by inserting a select from the input values.
7991     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7992                                            FI->getOperand(0), SI.getName()+".v");
7993     InsertNewInstBefore(NewSI, SI);
7994     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7995                             TI->getType());
7996   }
7997
7998   // Only handle binary operators here.
7999   if (!isa<BinaryOperator>(TI))
8000     return 0;
8001
8002   // Figure out if the operations have any operands in common.
8003   Value *MatchOp, *OtherOpT, *OtherOpF;
8004   bool MatchIsOpZero;
8005   if (TI->getOperand(0) == FI->getOperand(0)) {
8006     MatchOp  = TI->getOperand(0);
8007     OtherOpT = TI->getOperand(1);
8008     OtherOpF = FI->getOperand(1);
8009     MatchIsOpZero = true;
8010   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8011     MatchOp  = TI->getOperand(1);
8012     OtherOpT = TI->getOperand(0);
8013     OtherOpF = FI->getOperand(0);
8014     MatchIsOpZero = false;
8015   } else if (!TI->isCommutative()) {
8016     return 0;
8017   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8018     MatchOp  = TI->getOperand(0);
8019     OtherOpT = TI->getOperand(1);
8020     OtherOpF = FI->getOperand(0);
8021     MatchIsOpZero = true;
8022   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8023     MatchOp  = TI->getOperand(1);
8024     OtherOpT = TI->getOperand(0);
8025     OtherOpF = FI->getOperand(1);
8026     MatchIsOpZero = true;
8027   } else {
8028     return 0;
8029   }
8030
8031   // If we reach here, they do have operations in common.
8032   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8033                                          OtherOpF, SI.getName()+".v");
8034   InsertNewInstBefore(NewSI, SI);
8035
8036   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8037     if (MatchIsOpZero)
8038       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8039     else
8040       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8041   }
8042   assert(0 && "Shouldn't get here");
8043   return 0;
8044 }
8045
8046 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8047   Value *CondVal = SI.getCondition();
8048   Value *TrueVal = SI.getTrueValue();
8049   Value *FalseVal = SI.getFalseValue();
8050
8051   // select true, X, Y  -> X
8052   // select false, X, Y -> Y
8053   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8054     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8055
8056   // select C, X, X -> X
8057   if (TrueVal == FalseVal)
8058     return ReplaceInstUsesWith(SI, TrueVal);
8059
8060   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8061     return ReplaceInstUsesWith(SI, FalseVal);
8062   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8063     return ReplaceInstUsesWith(SI, TrueVal);
8064   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8065     if (isa<Constant>(TrueVal))
8066       return ReplaceInstUsesWith(SI, TrueVal);
8067     else
8068       return ReplaceInstUsesWith(SI, FalseVal);
8069   }
8070
8071   if (SI.getType() == Type::Int1Ty) {
8072     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8073       if (C->getZExtValue()) {
8074         // Change: A = select B, true, C --> A = or B, C
8075         return BinaryOperator::CreateOr(CondVal, FalseVal);
8076       } else {
8077         // Change: A = select B, false, C --> A = and !B, C
8078         Value *NotCond =
8079           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8080                                              "not."+CondVal->getName()), SI);
8081         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8082       }
8083     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8084       if (C->getZExtValue() == false) {
8085         // Change: A = select B, C, false --> A = and B, C
8086         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8087       } else {
8088         // Change: A = select B, C, true --> A = or !B, C
8089         Value *NotCond =
8090           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8091                                              "not."+CondVal->getName()), SI);
8092         return BinaryOperator::CreateOr(NotCond, TrueVal);
8093       }
8094     }
8095     
8096     // select a, b, a  -> a&b
8097     // select a, a, b  -> a|b
8098     if (CondVal == TrueVal)
8099       return BinaryOperator::CreateOr(CondVal, FalseVal);
8100     else if (CondVal == FalseVal)
8101       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8102   }
8103
8104   // Selecting between two integer constants?
8105   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8106     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8107       // select C, 1, 0 -> zext C to int
8108       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8109         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8110       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8111         // select C, 0, 1 -> zext !C to int
8112         Value *NotCond =
8113           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8114                                                "not."+CondVal->getName()), SI);
8115         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8116       }
8117       
8118       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8119
8120       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8121
8122         // (x <s 0) ? -1 : 0 -> ashr x, 31
8123         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8124           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8125             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8126               // The comparison constant and the result are not neccessarily the
8127               // same width. Make an all-ones value by inserting a AShr.
8128               Value *X = IC->getOperand(0);
8129               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8130               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8131               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8132                                                         ShAmt, "ones");
8133               InsertNewInstBefore(SRA, SI);
8134               
8135               // Finally, convert to the type of the select RHS.  We figure out
8136               // if this requires a SExt, Trunc or BitCast based on the sizes.
8137               Instruction::CastOps opc = Instruction::BitCast;
8138               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8139               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8140               if (SRASize < SISize)
8141                 opc = Instruction::SExt;
8142               else if (SRASize > SISize)
8143                 opc = Instruction::Trunc;
8144               return CastInst::Create(opc, SRA, SI.getType());
8145             }
8146           }
8147
8148
8149         // If one of the constants is zero (we know they can't both be) and we
8150         // have an icmp instruction with zero, and we have an 'and' with the
8151         // non-constant value, eliminate this whole mess.  This corresponds to
8152         // cases like this: ((X & 27) ? 27 : 0)
8153         if (TrueValC->isZero() || FalseValC->isZero())
8154           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8155               cast<Constant>(IC->getOperand(1))->isNullValue())
8156             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8157               if (ICA->getOpcode() == Instruction::And &&
8158                   isa<ConstantInt>(ICA->getOperand(1)) &&
8159                   (ICA->getOperand(1) == TrueValC ||
8160                    ICA->getOperand(1) == FalseValC) &&
8161                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8162                 // Okay, now we know that everything is set up, we just don't
8163                 // know whether we have a icmp_ne or icmp_eq and whether the 
8164                 // true or false val is the zero.
8165                 bool ShouldNotVal = !TrueValC->isZero();
8166                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8167                 Value *V = ICA;
8168                 if (ShouldNotVal)
8169                   V = InsertNewInstBefore(BinaryOperator::Create(
8170                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8171                 return ReplaceInstUsesWith(SI, V);
8172               }
8173       }
8174     }
8175
8176   // See if we are selecting two values based on a comparison of the two values.
8177   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8178     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8179       // Transform (X == Y) ? X : Y  -> Y
8180       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8181         // This is not safe in general for floating point:  
8182         // consider X== -0, Y== +0.
8183         // It becomes safe if either operand is a nonzero constant.
8184         ConstantFP *CFPt, *CFPf;
8185         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8186               !CFPt->getValueAPF().isZero()) ||
8187             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8188              !CFPf->getValueAPF().isZero()))
8189         return ReplaceInstUsesWith(SI, FalseVal);
8190       }
8191       // Transform (X != Y) ? X : Y  -> X
8192       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8193         return ReplaceInstUsesWith(SI, TrueVal);
8194       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8195
8196     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8197       // Transform (X == Y) ? Y : X  -> X
8198       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8199         // This is not safe in general for floating point:  
8200         // consider X== -0, Y== +0.
8201         // It becomes safe if either operand is a nonzero constant.
8202         ConstantFP *CFPt, *CFPf;
8203         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8204               !CFPt->getValueAPF().isZero()) ||
8205             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8206              !CFPf->getValueAPF().isZero()))
8207           return ReplaceInstUsesWith(SI, FalseVal);
8208       }
8209       // Transform (X != Y) ? Y : X  -> Y
8210       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8211         return ReplaceInstUsesWith(SI, TrueVal);
8212       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8213     }
8214   }
8215
8216   // See if we are selecting two values based on a comparison of the two values.
8217   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8218     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8219       // Transform (X == Y) ? X : Y  -> Y
8220       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8221         return ReplaceInstUsesWith(SI, FalseVal);
8222       // Transform (X != Y) ? X : Y  -> X
8223       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8224         return ReplaceInstUsesWith(SI, TrueVal);
8225       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8226
8227     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8228       // Transform (X == Y) ? Y : X  -> X
8229       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8230         return ReplaceInstUsesWith(SI, FalseVal);
8231       // Transform (X != Y) ? Y : X  -> Y
8232       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8233         return ReplaceInstUsesWith(SI, TrueVal);
8234       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8235     }
8236   }
8237
8238   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8239     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8240       if (TI->hasOneUse() && FI->hasOneUse()) {
8241         Instruction *AddOp = 0, *SubOp = 0;
8242
8243         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8244         if (TI->getOpcode() == FI->getOpcode())
8245           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8246             return IV;
8247
8248         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8249         // even legal for FP.
8250         if (TI->getOpcode() == Instruction::Sub &&
8251             FI->getOpcode() == Instruction::Add) {
8252           AddOp = FI; SubOp = TI;
8253         } else if (FI->getOpcode() == Instruction::Sub &&
8254                    TI->getOpcode() == Instruction::Add) {
8255           AddOp = TI; SubOp = FI;
8256         }
8257
8258         if (AddOp) {
8259           Value *OtherAddOp = 0;
8260           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8261             OtherAddOp = AddOp->getOperand(1);
8262           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8263             OtherAddOp = AddOp->getOperand(0);
8264           }
8265
8266           if (OtherAddOp) {
8267             // So at this point we know we have (Y -> OtherAddOp):
8268             //        select C, (add X, Y), (sub X, Z)
8269             Value *NegVal;  // Compute -Z
8270             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8271               NegVal = ConstantExpr::getNeg(C);
8272             } else {
8273               NegVal = InsertNewInstBefore(
8274                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8275             }
8276
8277             Value *NewTrueOp = OtherAddOp;
8278             Value *NewFalseOp = NegVal;
8279             if (AddOp != TI)
8280               std::swap(NewTrueOp, NewFalseOp);
8281             Instruction *NewSel =
8282               SelectInst::Create(CondVal, NewTrueOp,
8283                                  NewFalseOp, SI.getName() + ".p");
8284
8285             NewSel = InsertNewInstBefore(NewSel, SI);
8286             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8287           }
8288         }
8289       }
8290
8291   // See if we can fold the select into one of our operands.
8292   if (SI.getType()->isInteger()) {
8293     // See the comment above GetSelectFoldableOperands for a description of the
8294     // transformation we are doing here.
8295     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8296       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8297           !isa<Constant>(FalseVal))
8298         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8299           unsigned OpToFold = 0;
8300           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8301             OpToFold = 1;
8302           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8303             OpToFold = 2;
8304           }
8305
8306           if (OpToFold) {
8307             Constant *C = GetSelectFoldableConstant(TVI);
8308             Instruction *NewSel =
8309               SelectInst::Create(SI.getCondition(),
8310                                  TVI->getOperand(2-OpToFold), C);
8311             InsertNewInstBefore(NewSel, SI);
8312             NewSel->takeName(TVI);
8313             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8314               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8315             else {
8316               assert(0 && "Unknown instruction!!");
8317             }
8318           }
8319         }
8320
8321     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8322       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8323           !isa<Constant>(TrueVal))
8324         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8325           unsigned OpToFold = 0;
8326           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8327             OpToFold = 1;
8328           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8329             OpToFold = 2;
8330           }
8331
8332           if (OpToFold) {
8333             Constant *C = GetSelectFoldableConstant(FVI);
8334             Instruction *NewSel =
8335               SelectInst::Create(SI.getCondition(), C,
8336                                  FVI->getOperand(2-OpToFold));
8337             InsertNewInstBefore(NewSel, SI);
8338             NewSel->takeName(FVI);
8339             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8340               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8341             else
8342               assert(0 && "Unknown instruction!!");
8343           }
8344         }
8345   }
8346
8347   if (BinaryOperator::isNot(CondVal)) {
8348     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8349     SI.setOperand(1, FalseVal);
8350     SI.setOperand(2, TrueVal);
8351     return &SI;
8352   }
8353
8354   return 0;
8355 }
8356
8357 /// EnforceKnownAlignment - If the specified pointer points to an object that
8358 /// we control, modify the object's alignment to PrefAlign. This isn't
8359 /// often possible though. If alignment is important, a more reliable approach
8360 /// is to simply align all global variables and allocation instructions to
8361 /// their preferred alignment from the beginning.
8362 ///
8363 static unsigned EnforceKnownAlignment(Value *V,
8364                                       unsigned Align, unsigned PrefAlign) {
8365
8366   User *U = dyn_cast<User>(V);
8367   if (!U) return Align;
8368
8369   switch (getOpcode(U)) {
8370   default: break;
8371   case Instruction::BitCast:
8372     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8373   case Instruction::GetElementPtr: {
8374     // If all indexes are zero, it is just the alignment of the base pointer.
8375     bool AllZeroOperands = true;
8376     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8377       if (!isa<Constant>(*i) ||
8378           !cast<Constant>(*i)->isNullValue()) {
8379         AllZeroOperands = false;
8380         break;
8381       }
8382
8383     if (AllZeroOperands) {
8384       // Treat this like a bitcast.
8385       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8386     }
8387     break;
8388   }
8389   }
8390
8391   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8392     // If there is a large requested alignment and we can, bump up the alignment
8393     // of the global.
8394     if (!GV->isDeclaration()) {
8395       GV->setAlignment(PrefAlign);
8396       Align = PrefAlign;
8397     }
8398   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8399     // If there is a requested alignment and if this is an alloca, round up.  We
8400     // don't do this for malloc, because some systems can't respect the request.
8401     if (isa<AllocaInst>(AI)) {
8402       AI->setAlignment(PrefAlign);
8403       Align = PrefAlign;
8404     }
8405   }
8406
8407   return Align;
8408 }
8409
8410 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8411 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8412 /// and it is more than the alignment of the ultimate object, see if we can
8413 /// increase the alignment of the ultimate object, making this check succeed.
8414 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8415                                                   unsigned PrefAlign) {
8416   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8417                       sizeof(PrefAlign) * CHAR_BIT;
8418   APInt Mask = APInt::getAllOnesValue(BitWidth);
8419   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8420   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8421   unsigned TrailZ = KnownZero.countTrailingOnes();
8422   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8423
8424   if (PrefAlign > Align)
8425     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8426   
8427     // We don't need to make any adjustment.
8428   return Align;
8429 }
8430
8431 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8432   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8433   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8434   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8435   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8436
8437   if (CopyAlign < MinAlign) {
8438     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8439     return MI;
8440   }
8441   
8442   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8443   // load/store.
8444   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8445   if (MemOpLength == 0) return 0;
8446   
8447   // Source and destination pointer types are always "i8*" for intrinsic.  See
8448   // if the size is something we can handle with a single primitive load/store.
8449   // A single load+store correctly handles overlapping memory in the memmove
8450   // case.
8451   unsigned Size = MemOpLength->getZExtValue();
8452   if (Size == 0) return MI;  // Delete this mem transfer.
8453   
8454   if (Size > 8 || (Size&(Size-1)))
8455     return 0;  // If not 1/2/4/8 bytes, exit.
8456   
8457   // Use an integer load+store unless we can find something better.
8458   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8459   
8460   // Memcpy forces the use of i8* for the source and destination.  That means
8461   // that if you're using memcpy to move one double around, you'll get a cast
8462   // from double* to i8*.  We'd much rather use a double load+store rather than
8463   // an i64 load+store, here because this improves the odds that the source or
8464   // dest address will be promotable.  See if we can find a better type than the
8465   // integer datatype.
8466   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8467     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8468     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8469       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8470       // down through these levels if so.
8471       while (!SrcETy->isSingleValueType()) {
8472         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8473           if (STy->getNumElements() == 1)
8474             SrcETy = STy->getElementType(0);
8475           else
8476             break;
8477         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8478           if (ATy->getNumElements() == 1)
8479             SrcETy = ATy->getElementType();
8480           else
8481             break;
8482         } else
8483           break;
8484       }
8485       
8486       if (SrcETy->isSingleValueType())
8487         NewPtrTy = PointerType::getUnqual(SrcETy);
8488     }
8489   }
8490   
8491   
8492   // If the memcpy/memmove provides better alignment info than we can
8493   // infer, use it.
8494   SrcAlign = std::max(SrcAlign, CopyAlign);
8495   DstAlign = std::max(DstAlign, CopyAlign);
8496   
8497   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8498   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8499   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8500   InsertNewInstBefore(L, *MI);
8501   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8502
8503   // Set the size of the copy to 0, it will be deleted on the next iteration.
8504   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8505   return MI;
8506 }
8507
8508 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8509   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8510   if (MI->getAlignment()->getZExtValue() < Alignment) {
8511     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8512     return MI;
8513   }
8514   
8515   // Extract the length and alignment and fill if they are constant.
8516   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8517   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8518   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8519     return 0;
8520   uint64_t Len = LenC->getZExtValue();
8521   Alignment = MI->getAlignment()->getZExtValue();
8522   
8523   // If the length is zero, this is a no-op
8524   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8525   
8526   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8527   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8528     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
8529     
8530     Value *Dest = MI->getDest();
8531     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8532
8533     // Alignment 0 is identity for alignment 1 for memset, but not store.
8534     if (Alignment == 0) Alignment = 1;
8535     
8536     // Extract the fill value and store.
8537     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8538     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8539                                       Alignment), *MI);
8540     
8541     // Set the size of the copy to 0, it will be deleted on the next iteration.
8542     MI->setLength(Constant::getNullValue(LenC->getType()));
8543     return MI;
8544   }
8545
8546   return 0;
8547 }
8548
8549
8550 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8551 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8552 /// the heavy lifting.
8553 ///
8554 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8555   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8556   if (!II) return visitCallSite(&CI);
8557   
8558   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8559   // visitCallSite.
8560   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8561     bool Changed = false;
8562
8563     // memmove/cpy/set of zero bytes is a noop.
8564     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8565       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8566
8567       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8568         if (CI->getZExtValue() == 1) {
8569           // Replace the instruction with just byte operations.  We would
8570           // transform other cases to loads/stores, but we don't know if
8571           // alignment is sufficient.
8572         }
8573     }
8574
8575     // If we have a memmove and the source operation is a constant global,
8576     // then the source and dest pointers can't alias, so we can change this
8577     // into a call to memcpy.
8578     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8579       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8580         if (GVSrc->isConstant()) {
8581           Module *M = CI.getParent()->getParent()->getParent();
8582           Intrinsic::ID MemCpyID;
8583           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8584             MemCpyID = Intrinsic::memcpy_i32;
8585           else
8586             MemCpyID = Intrinsic::memcpy_i64;
8587           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8588           Changed = true;
8589         }
8590
8591       // memmove(x,x,size) -> noop.
8592       if (MMI->getSource() == MMI->getDest())
8593         return EraseInstFromFunction(CI);
8594     }
8595
8596     // If we can determine a pointer alignment that is bigger than currently
8597     // set, update the alignment.
8598     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8599       if (Instruction *I = SimplifyMemTransfer(MI))
8600         return I;
8601     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8602       if (Instruction *I = SimplifyMemSet(MSI))
8603         return I;
8604     }
8605           
8606     if (Changed) return II;
8607   }
8608   
8609   switch (II->getIntrinsicID()) {
8610   default: break;
8611   case Intrinsic::bswap:
8612     // bswap(bswap(x)) -> x
8613     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8614       if (Operand->getIntrinsicID() == Intrinsic::bswap)
8615         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8616     break;
8617   case Intrinsic::ppc_altivec_lvx:
8618   case Intrinsic::ppc_altivec_lvxl:
8619   case Intrinsic::x86_sse_loadu_ps:
8620   case Intrinsic::x86_sse2_loadu_pd:
8621   case Intrinsic::x86_sse2_loadu_dq:
8622     // Turn PPC lvx     -> load if the pointer is known aligned.
8623     // Turn X86 loadups -> load if the pointer is known aligned.
8624     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8625       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8626                                        PointerType::getUnqual(II->getType()),
8627                                        CI);
8628       return new LoadInst(Ptr);
8629     }
8630     break;
8631   case Intrinsic::ppc_altivec_stvx:
8632   case Intrinsic::ppc_altivec_stvxl:
8633     // Turn stvx -> store if the pointer is known aligned.
8634     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8635       const Type *OpPtrTy = 
8636         PointerType::getUnqual(II->getOperand(1)->getType());
8637       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8638       return new StoreInst(II->getOperand(1), Ptr);
8639     }
8640     break;
8641   case Intrinsic::x86_sse_storeu_ps:
8642   case Intrinsic::x86_sse2_storeu_pd:
8643   case Intrinsic::x86_sse2_storeu_dq:
8644   case Intrinsic::x86_sse2_storel_dq:
8645     // Turn X86 storeu -> store if the pointer is known aligned.
8646     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8647       const Type *OpPtrTy = 
8648         PointerType::getUnqual(II->getOperand(2)->getType());
8649       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8650       return new StoreInst(II->getOperand(2), Ptr);
8651     }
8652     break;
8653     
8654   case Intrinsic::x86_sse_cvttss2si: {
8655     // These intrinsics only demands the 0th element of its input vector.  If
8656     // we can simplify the input based on that, do so now.
8657     uint64_t UndefElts;
8658     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8659                                               UndefElts)) {
8660       II->setOperand(1, V);
8661       return II;
8662     }
8663     break;
8664   }
8665     
8666   case Intrinsic::ppc_altivec_vperm:
8667     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8668     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8669       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8670       
8671       // Check that all of the elements are integer constants or undefs.
8672       bool AllEltsOk = true;
8673       for (unsigned i = 0; i != 16; ++i) {
8674         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8675             !isa<UndefValue>(Mask->getOperand(i))) {
8676           AllEltsOk = false;
8677           break;
8678         }
8679       }
8680       
8681       if (AllEltsOk) {
8682         // Cast the input vectors to byte vectors.
8683         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8684         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8685         Value *Result = UndefValue::get(Op0->getType());
8686         
8687         // Only extract each element once.
8688         Value *ExtractedElts[32];
8689         memset(ExtractedElts, 0, sizeof(ExtractedElts));
8690         
8691         for (unsigned i = 0; i != 16; ++i) {
8692           if (isa<UndefValue>(Mask->getOperand(i)))
8693             continue;
8694           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8695           Idx &= 31;  // Match the hardware behavior.
8696           
8697           if (ExtractedElts[Idx] == 0) {
8698             Instruction *Elt = 
8699               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8700             InsertNewInstBefore(Elt, CI);
8701             ExtractedElts[Idx] = Elt;
8702           }
8703         
8704           // Insert this value into the result vector.
8705           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8706                                              i, "tmp");
8707           InsertNewInstBefore(cast<Instruction>(Result), CI);
8708         }
8709         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8710       }
8711     }
8712     break;
8713
8714   case Intrinsic::stackrestore: {
8715     // If the save is right next to the restore, remove the restore.  This can
8716     // happen when variable allocas are DCE'd.
8717     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8718       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8719         BasicBlock::iterator BI = SS;
8720         if (&*++BI == II)
8721           return EraseInstFromFunction(CI);
8722       }
8723     }
8724     
8725     // Scan down this block to see if there is another stack restore in the
8726     // same block without an intervening call/alloca.
8727     BasicBlock::iterator BI = II;
8728     TerminatorInst *TI = II->getParent()->getTerminator();
8729     bool CannotRemove = false;
8730     for (++BI; &*BI != TI; ++BI) {
8731       if (isa<AllocaInst>(BI)) {
8732         CannotRemove = true;
8733         break;
8734       }
8735       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8736         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8737           // If there is a stackrestore below this one, remove this one.
8738           if (II->getIntrinsicID() == Intrinsic::stackrestore)
8739             return EraseInstFromFunction(CI);
8740           // Otherwise, ignore the intrinsic.
8741         } else {
8742           // If we found a non-intrinsic call, we can't remove the stack
8743           // restore.
8744           CannotRemove = true;
8745           break;
8746         }
8747       }
8748     }
8749     
8750     // If the stack restore is in a return/unwind block and if there are no
8751     // allocas or calls between the restore and the return, nuke the restore.
8752     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8753       return EraseInstFromFunction(CI);
8754     break;
8755   }
8756   }
8757
8758   return visitCallSite(II);
8759 }
8760
8761 // InvokeInst simplification
8762 //
8763 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8764   return visitCallSite(&II);
8765 }
8766
8767 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
8768 /// passed through the varargs area, we can eliminate the use of the cast.
8769 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8770                                          const CastInst * const CI,
8771                                          const TargetData * const TD,
8772                                          const int ix) {
8773   if (!CI->isLosslessCast())
8774     return false;
8775
8776   // The size of ByVal arguments is derived from the type, so we
8777   // can't change to a type with a different size.  If the size were
8778   // passed explicitly we could avoid this check.
8779   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8780     return true;
8781
8782   const Type* SrcTy = 
8783             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8784   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8785   if (!SrcTy->isSized() || !DstTy->isSized())
8786     return false;
8787   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8788     return false;
8789   return true;
8790 }
8791
8792 // visitCallSite - Improvements for call and invoke instructions.
8793 //
8794 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8795   bool Changed = false;
8796
8797   // If the callee is a constexpr cast of a function, attempt to move the cast
8798   // to the arguments of the call/invoke.
8799   if (transformConstExprCastCall(CS)) return 0;
8800
8801   Value *Callee = CS.getCalledValue();
8802
8803   if (Function *CalleeF = dyn_cast<Function>(Callee))
8804     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8805       Instruction *OldCall = CS.getInstruction();
8806       // If the call and callee calling conventions don't match, this call must
8807       // be unreachable, as the call is undefined.
8808       new StoreInst(ConstantInt::getTrue(),
8809                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8810                                     OldCall);
8811       if (!OldCall->use_empty())
8812         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8813       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8814         return EraseInstFromFunction(*OldCall);
8815       return 0;
8816     }
8817
8818   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8819     // This instruction is not reachable, just remove it.  We insert a store to
8820     // undef so that we know that this code is not reachable, despite the fact
8821     // that we can't modify the CFG here.
8822     new StoreInst(ConstantInt::getTrue(),
8823                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8824                   CS.getInstruction());
8825
8826     if (!CS.getInstruction()->use_empty())
8827       CS.getInstruction()->
8828         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8829
8830     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8831       // Don't break the CFG, insert a dummy cond branch.
8832       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8833                          ConstantInt::getTrue(), II);
8834     }
8835     return EraseInstFromFunction(*CS.getInstruction());
8836   }
8837
8838   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8839     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8840       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8841         return transformCallThroughTrampoline(CS);
8842
8843   const PointerType *PTy = cast<PointerType>(Callee->getType());
8844   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8845   if (FTy->isVarArg()) {
8846     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8847     // See if we can optimize any arguments passed through the varargs area of
8848     // the call.
8849     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8850            E = CS.arg_end(); I != E; ++I, ++ix) {
8851       CastInst *CI = dyn_cast<CastInst>(*I);
8852       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8853         *I = CI->getOperand(0);
8854         Changed = true;
8855       }
8856     }
8857   }
8858
8859   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8860     // Inline asm calls cannot throw - mark them 'nounwind'.
8861     CS.setDoesNotThrow();
8862     Changed = true;
8863   }
8864
8865   return Changed ? CS.getInstruction() : 0;
8866 }
8867
8868 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8869 // attempt to move the cast to the arguments of the call/invoke.
8870 //
8871 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8872   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8873   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8874   if (CE->getOpcode() != Instruction::BitCast || 
8875       !isa<Function>(CE->getOperand(0)))
8876     return false;
8877   Function *Callee = cast<Function>(CE->getOperand(0));
8878   Instruction *Caller = CS.getInstruction();
8879   const PAListPtr &CallerPAL = CS.getParamAttrs();
8880
8881   // Okay, this is a cast from a function to a different type.  Unless doing so
8882   // would cause a type conversion of one of our arguments, change this call to
8883   // be a direct call with arguments casted to the appropriate types.
8884   //
8885   const FunctionType *FT = Callee->getFunctionType();
8886   const Type *OldRetTy = Caller->getType();
8887   const Type *NewRetTy = FT->getReturnType();
8888
8889   if (isa<StructType>(NewRetTy))
8890     return false; // TODO: Handle multiple return values.
8891
8892   // Check to see if we are changing the return type...
8893   if (OldRetTy != NewRetTy) {
8894     if (Callee->isDeclaration() &&
8895         // Conversion is ok if changing from one pointer type to another or from
8896         // a pointer to an integer of the same size.
8897         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8898           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
8899       return false;   // Cannot transform this return value.
8900
8901     if (!Caller->use_empty() &&
8902         // void -> non-void is handled specially
8903         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8904       return false;   // Cannot transform this return value.
8905
8906     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8907       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8908       if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8909         return false;   // Attribute not compatible with transformed value.
8910     }
8911
8912     // If the callsite is an invoke instruction, and the return value is used by
8913     // a PHI node in a successor, we cannot change the return type of the call
8914     // because there is no place to put the cast instruction (without breaking
8915     // the critical edge).  Bail out in this case.
8916     if (!Caller->use_empty())
8917       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8918         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8919              UI != E; ++UI)
8920           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8921             if (PN->getParent() == II->getNormalDest() ||
8922                 PN->getParent() == II->getUnwindDest())
8923               return false;
8924   }
8925
8926   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8927   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8928
8929   CallSite::arg_iterator AI = CS.arg_begin();
8930   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8931     const Type *ParamTy = FT->getParamType(i);
8932     const Type *ActTy = (*AI)->getType();
8933
8934     if (!CastInst::isCastable(ActTy, ParamTy))
8935       return false;   // Cannot transform this parameter value.
8936
8937     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8938       return false;   // Attribute not compatible with transformed value.
8939
8940     // Converting from one pointer type to another or between a pointer and an
8941     // integer of the same size is safe even if we do not have a body.
8942     bool isConvertible = ActTy == ParamTy ||
8943       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8944        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8945     if (Callee->isDeclaration() && !isConvertible) return false;
8946   }
8947
8948   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8949       Callee->isDeclaration())
8950     return false;   // Do not delete arguments unless we have a function body.
8951
8952   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8953       !CallerPAL.isEmpty())
8954     // In this case we have more arguments than the new function type, but we
8955     // won't be dropping them.  Check that these extra arguments have attributes
8956     // that are compatible with being a vararg call argument.
8957     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8958       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8959         break;
8960       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8961       if (PAttrs & ParamAttr::VarArgsIncompatible)
8962         return false;
8963     }
8964
8965   // Okay, we decided that this is a safe thing to do: go ahead and start
8966   // inserting cast instructions as necessary...
8967   std::vector<Value*> Args;
8968   Args.reserve(NumActualArgs);
8969   SmallVector<ParamAttrsWithIndex, 8> attrVec;
8970   attrVec.reserve(NumCommonArgs);
8971
8972   // Get any return attributes.
8973   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8974
8975   // If the return value is not being used, the type may not be compatible
8976   // with the existing attributes.  Wipe out any problematic attributes.
8977   RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
8978
8979   // Add the new return attributes.
8980   if (RAttrs)
8981     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8982
8983   AI = CS.arg_begin();
8984   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8985     const Type *ParamTy = FT->getParamType(i);
8986     if ((*AI)->getType() == ParamTy) {
8987       Args.push_back(*AI);
8988     } else {
8989       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8990           false, ParamTy, false);
8991       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
8992       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8993     }
8994
8995     // Add any parameter attributes.
8996     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8997       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8998   }
8999
9000   // If the function takes more arguments than the call was taking, add them
9001   // now...
9002   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9003     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9004
9005   // If we are removing arguments to the function, emit an obnoxious warning...
9006   if (FT->getNumParams() < NumActualArgs) {
9007     if (!FT->isVarArg()) {
9008       cerr << "WARNING: While resolving call to function '"
9009            << Callee->getName() << "' arguments were dropped!\n";
9010     } else {
9011       // Add all of the arguments in their promoted form to the arg list...
9012       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9013         const Type *PTy = getPromotedType((*AI)->getType());
9014         if (PTy != (*AI)->getType()) {
9015           // Must promote to pass through va_arg area!
9016           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9017                                                                 PTy, false);
9018           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9019           InsertNewInstBefore(Cast, *Caller);
9020           Args.push_back(Cast);
9021         } else {
9022           Args.push_back(*AI);
9023         }
9024
9025         // Add any parameter attributes.
9026         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9027           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9028       }
9029     }
9030   }
9031
9032   if (NewRetTy == Type::VoidTy)
9033     Caller->setName("");   // Void type should not have a name.
9034
9035   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9036
9037   Instruction *NC;
9038   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9039     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9040                             Args.begin(), Args.end(),
9041                             Caller->getName(), Caller);
9042     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9043     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9044   } else {
9045     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9046                           Caller->getName(), Caller);
9047     CallInst *CI = cast<CallInst>(Caller);
9048     if (CI->isTailCall())
9049       cast<CallInst>(NC)->setTailCall();
9050     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9051     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9052   }
9053
9054   // Insert a cast of the return type as necessary.
9055   Value *NV = NC;
9056   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9057     if (NV->getType() != Type::VoidTy) {
9058       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9059                                                             OldRetTy, false);
9060       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9061
9062       // If this is an invoke instruction, we should insert it after the first
9063       // non-phi, instruction in the normal successor block.
9064       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9065         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9066         InsertNewInstBefore(NC, *I);
9067       } else {
9068         // Otherwise, it's a call, just insert cast right after the call instr
9069         InsertNewInstBefore(NC, *Caller);
9070       }
9071       AddUsersToWorkList(*Caller);
9072     } else {
9073       NV = UndefValue::get(Caller->getType());
9074     }
9075   }
9076
9077   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9078     Caller->replaceAllUsesWith(NV);
9079   Caller->eraseFromParent();
9080   RemoveFromWorkList(Caller);
9081   return true;
9082 }
9083
9084 // transformCallThroughTrampoline - Turn a call to a function created by the
9085 // init_trampoline intrinsic into a direct call to the underlying function.
9086 //
9087 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9088   Value *Callee = CS.getCalledValue();
9089   const PointerType *PTy = cast<PointerType>(Callee->getType());
9090   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9091   const PAListPtr &Attrs = CS.getParamAttrs();
9092
9093   // If the call already has the 'nest' attribute somewhere then give up -
9094   // otherwise 'nest' would occur twice after splicing in the chain.
9095   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9096     return 0;
9097
9098   IntrinsicInst *Tramp =
9099     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9100
9101   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9102   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9103   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9104
9105   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9106   if (!NestAttrs.isEmpty()) {
9107     unsigned NestIdx = 1;
9108     const Type *NestTy = 0;
9109     ParameterAttributes NestAttr = ParamAttr::None;
9110
9111     // Look for a parameter marked with the 'nest' attribute.
9112     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9113          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9114       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9115         // Record the parameter type and any other attributes.
9116         NestTy = *I;
9117         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9118         break;
9119       }
9120
9121     if (NestTy) {
9122       Instruction *Caller = CS.getInstruction();
9123       std::vector<Value*> NewArgs;
9124       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9125
9126       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9127       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9128
9129       // Insert the nest argument into the call argument list, which may
9130       // mean appending it.  Likewise for attributes.
9131
9132       // Add any function result attributes.
9133       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9134         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9135
9136       {
9137         unsigned Idx = 1;
9138         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9139         do {
9140           if (Idx == NestIdx) {
9141             // Add the chain argument and attributes.
9142             Value *NestVal = Tramp->getOperand(3);
9143             if (NestVal->getType() != NestTy)
9144               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9145             NewArgs.push_back(NestVal);
9146             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9147           }
9148
9149           if (I == E)
9150             break;
9151
9152           // Add the original argument and attributes.
9153           NewArgs.push_back(*I);
9154           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9155             NewAttrs.push_back
9156               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9157
9158           ++Idx, ++I;
9159         } while (1);
9160       }
9161
9162       // The trampoline may have been bitcast to a bogus type (FTy).
9163       // Handle this by synthesizing a new function type, equal to FTy
9164       // with the chain parameter inserted.
9165
9166       std::vector<const Type*> NewTypes;
9167       NewTypes.reserve(FTy->getNumParams()+1);
9168
9169       // Insert the chain's type into the list of parameter types, which may
9170       // mean appending it.
9171       {
9172         unsigned Idx = 1;
9173         FunctionType::param_iterator I = FTy->param_begin(),
9174           E = FTy->param_end();
9175
9176         do {
9177           if (Idx == NestIdx)
9178             // Add the chain's type.
9179             NewTypes.push_back(NestTy);
9180
9181           if (I == E)
9182             break;
9183
9184           // Add the original type.
9185           NewTypes.push_back(*I);
9186
9187           ++Idx, ++I;
9188         } while (1);
9189       }
9190
9191       // Replace the trampoline call with a direct call.  Let the generic
9192       // code sort out any function type mismatches.
9193       FunctionType *NewFTy =
9194         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9195       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9196         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9197       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9198
9199       Instruction *NewCaller;
9200       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9201         NewCaller = InvokeInst::Create(NewCallee,
9202                                        II->getNormalDest(), II->getUnwindDest(),
9203                                        NewArgs.begin(), NewArgs.end(),
9204                                        Caller->getName(), Caller);
9205         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9206         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9207       } else {
9208         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9209                                      Caller->getName(), Caller);
9210         if (cast<CallInst>(Caller)->isTailCall())
9211           cast<CallInst>(NewCaller)->setTailCall();
9212         cast<CallInst>(NewCaller)->
9213           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9214         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9215       }
9216       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9217         Caller->replaceAllUsesWith(NewCaller);
9218       Caller->eraseFromParent();
9219       RemoveFromWorkList(Caller);
9220       return 0;
9221     }
9222   }
9223
9224   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9225   // parameter, there is no need to adjust the argument list.  Let the generic
9226   // code sort out any function type mismatches.
9227   Constant *NewCallee =
9228     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9229   CS.setCalledFunction(NewCallee);
9230   return CS.getInstruction();
9231 }
9232
9233 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9234 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9235 /// and a single binop.
9236 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9237   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9238   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9239          isa<CmpInst>(FirstInst));
9240   unsigned Opc = FirstInst->getOpcode();
9241   Value *LHSVal = FirstInst->getOperand(0);
9242   Value *RHSVal = FirstInst->getOperand(1);
9243     
9244   const Type *LHSType = LHSVal->getType();
9245   const Type *RHSType = RHSVal->getType();
9246   
9247   // Scan to see if all operands are the same opcode, all have one use, and all
9248   // kill their operands (i.e. the operands have one use).
9249   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9250     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9251     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9252         // Verify type of the LHS matches so we don't fold cmp's of different
9253         // types or GEP's with different index types.
9254         I->getOperand(0)->getType() != LHSType ||
9255         I->getOperand(1)->getType() != RHSType)
9256       return 0;
9257
9258     // If they are CmpInst instructions, check their predicates
9259     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9260       if (cast<CmpInst>(I)->getPredicate() !=
9261           cast<CmpInst>(FirstInst)->getPredicate())
9262         return 0;
9263     
9264     // Keep track of which operand needs a phi node.
9265     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9266     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9267   }
9268   
9269   // Otherwise, this is safe to transform, determine if it is profitable.
9270
9271   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9272   // Indexes are often folded into load/store instructions, so we don't want to
9273   // hide them behind a phi.
9274   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9275     return 0;
9276   
9277   Value *InLHS = FirstInst->getOperand(0);
9278   Value *InRHS = FirstInst->getOperand(1);
9279   PHINode *NewLHS = 0, *NewRHS = 0;
9280   if (LHSVal == 0) {
9281     NewLHS = PHINode::Create(LHSType,
9282                              FirstInst->getOperand(0)->getName() + ".pn");
9283     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9284     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9285     InsertNewInstBefore(NewLHS, PN);
9286     LHSVal = NewLHS;
9287   }
9288   
9289   if (RHSVal == 0) {
9290     NewRHS = PHINode::Create(RHSType,
9291                              FirstInst->getOperand(1)->getName() + ".pn");
9292     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9293     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9294     InsertNewInstBefore(NewRHS, PN);
9295     RHSVal = NewRHS;
9296   }
9297   
9298   // Add all operands to the new PHIs.
9299   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9300     if (NewLHS) {
9301       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9302       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9303     }
9304     if (NewRHS) {
9305       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9306       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9307     }
9308   }
9309     
9310   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9311     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9312   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9313     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9314                            RHSVal);
9315   else {
9316     assert(isa<GetElementPtrInst>(FirstInst));
9317     return GetElementPtrInst::Create(LHSVal, RHSVal);
9318   }
9319 }
9320
9321 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9322 /// of the block that defines it.  This means that it must be obvious the value
9323 /// of the load is not changed from the point of the load to the end of the
9324 /// block it is in.
9325 ///
9326 /// Finally, it is safe, but not profitable, to sink a load targetting a
9327 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9328 /// to a register.
9329 static bool isSafeToSinkLoad(LoadInst *L) {
9330   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9331   
9332   for (++BBI; BBI != E; ++BBI)
9333     if (BBI->mayWriteToMemory())
9334       return false;
9335   
9336   // Check for non-address taken alloca.  If not address-taken already, it isn't
9337   // profitable to do this xform.
9338   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9339     bool isAddressTaken = false;
9340     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9341          UI != E; ++UI) {
9342       if (isa<LoadInst>(UI)) continue;
9343       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9344         // If storing TO the alloca, then the address isn't taken.
9345         if (SI->getOperand(1) == AI) continue;
9346       }
9347       isAddressTaken = true;
9348       break;
9349     }
9350     
9351     if (!isAddressTaken)
9352       return false;
9353   }
9354   
9355   return true;
9356 }
9357
9358
9359 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9360 // operator and they all are only used by the PHI, PHI together their
9361 // inputs, and do the operation once, to the result of the PHI.
9362 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9363   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9364
9365   // Scan the instruction, looking for input operations that can be folded away.
9366   // If all input operands to the phi are the same instruction (e.g. a cast from
9367   // the same type or "+42") we can pull the operation through the PHI, reducing
9368   // code size and simplifying code.
9369   Constant *ConstantOp = 0;
9370   const Type *CastSrcTy = 0;
9371   bool isVolatile = false;
9372   if (isa<CastInst>(FirstInst)) {
9373     CastSrcTy = FirstInst->getOperand(0)->getType();
9374   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9375     // Can fold binop, compare or shift here if the RHS is a constant, 
9376     // otherwise call FoldPHIArgBinOpIntoPHI.
9377     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9378     if (ConstantOp == 0)
9379       return FoldPHIArgBinOpIntoPHI(PN);
9380   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9381     isVolatile = LI->isVolatile();
9382     // We can't sink the load if the loaded value could be modified between the
9383     // load and the PHI.
9384     if (LI->getParent() != PN.getIncomingBlock(0) ||
9385         !isSafeToSinkLoad(LI))
9386       return 0;
9387     
9388     // If the PHI is of volatile loads and the load block has multiple
9389     // successors, sinking it would remove a load of the volatile value from
9390     // the path through the other successor.
9391     if (isVolatile &&
9392         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9393       return 0;
9394     
9395   } else if (isa<GetElementPtrInst>(FirstInst)) {
9396     if (FirstInst->getNumOperands() == 2)
9397       return FoldPHIArgBinOpIntoPHI(PN);
9398     // Can't handle general GEPs yet.
9399     return 0;
9400   } else {
9401     return 0;  // Cannot fold this operation.
9402   }
9403
9404   // Check to see if all arguments are the same operation.
9405   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9406     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9407     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9408     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9409       return 0;
9410     if (CastSrcTy) {
9411       if (I->getOperand(0)->getType() != CastSrcTy)
9412         return 0;  // Cast operation must match.
9413     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9414       // We can't sink the load if the loaded value could be modified between 
9415       // the load and the PHI.
9416       if (LI->isVolatile() != isVolatile ||
9417           LI->getParent() != PN.getIncomingBlock(i) ||
9418           !isSafeToSinkLoad(LI))
9419         return 0;
9420       
9421       // If the PHI is of volatile loads and the load block has multiple
9422       // successors, sinking it would remove a load of the volatile value from
9423       // the path through the other successor.
9424       if (isVolatile &&
9425           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9426         return 0;
9427
9428       
9429     } else if (I->getOperand(1) != ConstantOp) {
9430       return 0;
9431     }
9432   }
9433
9434   // Okay, they are all the same operation.  Create a new PHI node of the
9435   // correct type, and PHI together all of the LHS's of the instructions.
9436   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9437                                    PN.getName()+".in");
9438   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9439
9440   Value *InVal = FirstInst->getOperand(0);
9441   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9442
9443   // Add all operands to the new PHI.
9444   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9445     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9446     if (NewInVal != InVal)
9447       InVal = 0;
9448     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9449   }
9450
9451   Value *PhiVal;
9452   if (InVal) {
9453     // The new PHI unions all of the same values together.  This is really
9454     // common, so we handle it intelligently here for compile-time speed.
9455     PhiVal = InVal;
9456     delete NewPN;
9457   } else {
9458     InsertNewInstBefore(NewPN, PN);
9459     PhiVal = NewPN;
9460   }
9461
9462   // Insert and return the new operation.
9463   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9464     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9465   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9466     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9467   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9468     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9469                            PhiVal, ConstantOp);
9470   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9471   
9472   // If this was a volatile load that we are merging, make sure to loop through
9473   // and mark all the input loads as non-volatile.  If we don't do this, we will
9474   // insert a new volatile load and the old ones will not be deletable.
9475   if (isVolatile)
9476     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9477       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9478   
9479   return new LoadInst(PhiVal, "", isVolatile);
9480 }
9481
9482 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9483 /// that is dead.
9484 static bool DeadPHICycle(PHINode *PN,
9485                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9486   if (PN->use_empty()) return true;
9487   if (!PN->hasOneUse()) return false;
9488
9489   // Remember this node, and if we find the cycle, return.
9490   if (!PotentiallyDeadPHIs.insert(PN))
9491     return true;
9492   
9493   // Don't scan crazily complex things.
9494   if (PotentiallyDeadPHIs.size() == 16)
9495     return false;
9496
9497   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9498     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9499
9500   return false;
9501 }
9502
9503 /// PHIsEqualValue - Return true if this phi node is always equal to
9504 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9505 ///   z = some value; x = phi (y, z); y = phi (x, z)
9506 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9507                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9508   // See if we already saw this PHI node.
9509   if (!ValueEqualPHIs.insert(PN))
9510     return true;
9511   
9512   // Don't scan crazily complex things.
9513   if (ValueEqualPHIs.size() == 16)
9514     return false;
9515  
9516   // Scan the operands to see if they are either phi nodes or are equal to
9517   // the value.
9518   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9519     Value *Op = PN->getIncomingValue(i);
9520     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9521       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9522         return false;
9523     } else if (Op != NonPhiInVal)
9524       return false;
9525   }
9526   
9527   return true;
9528 }
9529
9530
9531 // PHINode simplification
9532 //
9533 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9534   // If LCSSA is around, don't mess with Phi nodes
9535   if (MustPreserveLCSSA) return 0;
9536   
9537   if (Value *V = PN.hasConstantValue())
9538     return ReplaceInstUsesWith(PN, V);
9539
9540   // If all PHI operands are the same operation, pull them through the PHI,
9541   // reducing code size.
9542   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9543       PN.getIncomingValue(0)->hasOneUse())
9544     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9545       return Result;
9546
9547   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9548   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9549   // PHI)... break the cycle.
9550   if (PN.hasOneUse()) {
9551     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9552     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9553       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9554       PotentiallyDeadPHIs.insert(&PN);
9555       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9556         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9557     }
9558    
9559     // If this phi has a single use, and if that use just computes a value for
9560     // the next iteration of a loop, delete the phi.  This occurs with unused
9561     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9562     // common case here is good because the only other things that catch this
9563     // are induction variable analysis (sometimes) and ADCE, which is only run
9564     // late.
9565     if (PHIUser->hasOneUse() &&
9566         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9567         PHIUser->use_back() == &PN) {
9568       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9569     }
9570   }
9571
9572   // We sometimes end up with phi cycles that non-obviously end up being the
9573   // same value, for example:
9574   //   z = some value; x = phi (y, z); y = phi (x, z)
9575   // where the phi nodes don't necessarily need to be in the same block.  Do a
9576   // quick check to see if the PHI node only contains a single non-phi value, if
9577   // so, scan to see if the phi cycle is actually equal to that value.
9578   {
9579     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9580     // Scan for the first non-phi operand.
9581     while (InValNo != NumOperandVals && 
9582            isa<PHINode>(PN.getIncomingValue(InValNo)))
9583       ++InValNo;
9584
9585     if (InValNo != NumOperandVals) {
9586       Value *NonPhiInVal = PN.getOperand(InValNo);
9587       
9588       // Scan the rest of the operands to see if there are any conflicts, if so
9589       // there is no need to recursively scan other phis.
9590       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9591         Value *OpVal = PN.getIncomingValue(InValNo);
9592         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9593           break;
9594       }
9595       
9596       // If we scanned over all operands, then we have one unique value plus
9597       // phi values.  Scan PHI nodes to see if they all merge in each other or
9598       // the value.
9599       if (InValNo == NumOperandVals) {
9600         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9601         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9602           return ReplaceInstUsesWith(PN, NonPhiInVal);
9603       }
9604     }
9605   }
9606   return 0;
9607 }
9608
9609 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9610                                    Instruction *InsertPoint,
9611                                    InstCombiner *IC) {
9612   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9613   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9614   // We must cast correctly to the pointer type. Ensure that we
9615   // sign extend the integer value if it is smaller as this is
9616   // used for address computation.
9617   Instruction::CastOps opcode = 
9618      (VTySize < PtrSize ? Instruction::SExt :
9619       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9620   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9621 }
9622
9623
9624 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9625   Value *PtrOp = GEP.getOperand(0);
9626   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9627   // If so, eliminate the noop.
9628   if (GEP.getNumOperands() == 1)
9629     return ReplaceInstUsesWith(GEP, PtrOp);
9630
9631   if (isa<UndefValue>(GEP.getOperand(0)))
9632     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9633
9634   bool HasZeroPointerIndex = false;
9635   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9636     HasZeroPointerIndex = C->isNullValue();
9637
9638   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9639     return ReplaceInstUsesWith(GEP, PtrOp);
9640
9641   // Eliminate unneeded casts for indices.
9642   bool MadeChange = false;
9643   
9644   gep_type_iterator GTI = gep_type_begin(GEP);
9645   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9646        i != e; ++i, ++GTI) {
9647     if (isa<SequentialType>(*GTI)) {
9648       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9649         if (CI->getOpcode() == Instruction::ZExt ||
9650             CI->getOpcode() == Instruction::SExt) {
9651           const Type *SrcTy = CI->getOperand(0)->getType();
9652           // We can eliminate a cast from i32 to i64 iff the target 
9653           // is a 32-bit pointer target.
9654           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9655             MadeChange = true;
9656             *i = CI->getOperand(0);
9657           }
9658         }
9659       }
9660       // If we are using a wider index than needed for this platform, shrink it
9661       // to what we need.  If the incoming value needs a cast instruction,
9662       // insert it.  This explicit cast can make subsequent optimizations more
9663       // obvious.
9664       Value *Op = *i;
9665       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9666         if (Constant *C = dyn_cast<Constant>(Op)) {
9667           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9668           MadeChange = true;
9669         } else {
9670           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9671                                 GEP);
9672           *i = Op;
9673           MadeChange = true;
9674         }
9675       }
9676     }
9677   }
9678   if (MadeChange) return &GEP;
9679
9680   // If this GEP instruction doesn't move the pointer, and if the input operand
9681   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9682   // real input to the dest type.
9683   if (GEP.hasAllZeroIndices()) {
9684     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9685       // If the bitcast is of an allocation, and the allocation will be
9686       // converted to match the type of the cast, don't touch this.
9687       if (isa<AllocationInst>(BCI->getOperand(0))) {
9688         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9689         if (Instruction *I = visitBitCast(*BCI)) {
9690           if (I != BCI) {
9691             I->takeName(BCI);
9692             BCI->getParent()->getInstList().insert(BCI, I);
9693             ReplaceInstUsesWith(*BCI, I);
9694           }
9695           return &GEP;
9696         }
9697       }
9698       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9699     }
9700   }
9701   
9702   // Combine Indices - If the source pointer to this getelementptr instruction
9703   // is a getelementptr instruction, combine the indices of the two
9704   // getelementptr instructions into a single instruction.
9705   //
9706   SmallVector<Value*, 8> SrcGEPOperands;
9707   if (User *Src = dyn_castGetElementPtr(PtrOp))
9708     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9709
9710   if (!SrcGEPOperands.empty()) {
9711     // Note that if our source is a gep chain itself that we wait for that
9712     // chain to be resolved before we perform this transformation.  This
9713     // avoids us creating a TON of code in some cases.
9714     //
9715     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9716         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9717       return 0;   // Wait until our source is folded to completion.
9718
9719     SmallVector<Value*, 8> Indices;
9720
9721     // Find out whether the last index in the source GEP is a sequential idx.
9722     bool EndsWithSequential = false;
9723     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9724            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9725       EndsWithSequential = !isa<StructType>(*I);
9726
9727     // Can we combine the two pointer arithmetics offsets?
9728     if (EndsWithSequential) {
9729       // Replace: gep (gep %P, long B), long A, ...
9730       // With:    T = long A+B; gep %P, T, ...
9731       //
9732       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9733       if (SO1 == Constant::getNullValue(SO1->getType())) {
9734         Sum = GO1;
9735       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9736         Sum = SO1;
9737       } else {
9738         // If they aren't the same type, convert both to an integer of the
9739         // target's pointer size.
9740         if (SO1->getType() != GO1->getType()) {
9741           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9742             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9743           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9744             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9745           } else {
9746             unsigned PS = TD->getPointerSizeInBits();
9747             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9748               // Convert GO1 to SO1's type.
9749               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9750
9751             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9752               // Convert SO1 to GO1's type.
9753               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9754             } else {
9755               const Type *PT = TD->getIntPtrType();
9756               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9757               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9758             }
9759           }
9760         }
9761         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9762           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9763         else {
9764           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9765           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9766         }
9767       }
9768
9769       // Recycle the GEP we already have if possible.
9770       if (SrcGEPOperands.size() == 2) {
9771         GEP.setOperand(0, SrcGEPOperands[0]);
9772         GEP.setOperand(1, Sum);
9773         return &GEP;
9774       } else {
9775         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9776                        SrcGEPOperands.end()-1);
9777         Indices.push_back(Sum);
9778         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9779       }
9780     } else if (isa<Constant>(*GEP.idx_begin()) &&
9781                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9782                SrcGEPOperands.size() != 1) {
9783       // Otherwise we can do the fold if the first index of the GEP is a zero
9784       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9785                      SrcGEPOperands.end());
9786       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9787     }
9788
9789     if (!Indices.empty())
9790       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9791                                        Indices.end(), GEP.getName());
9792
9793   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9794     // GEP of global variable.  If all of the indices for this GEP are
9795     // constants, we can promote this to a constexpr instead of an instruction.
9796
9797     // Scan for nonconstants...
9798     SmallVector<Constant*, 8> Indices;
9799     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9800     for (; I != E && isa<Constant>(*I); ++I)
9801       Indices.push_back(cast<Constant>(*I));
9802
9803     if (I == E) {  // If they are all constants...
9804       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9805                                                     &Indices[0],Indices.size());
9806
9807       // Replace all uses of the GEP with the new constexpr...
9808       return ReplaceInstUsesWith(GEP, CE);
9809     }
9810   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9811     if (!isa<PointerType>(X->getType())) {
9812       // Not interesting.  Source pointer must be a cast from pointer.
9813     } else if (HasZeroPointerIndex) {
9814       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9815       // into     : GEP [10 x i8]* X, i32 0, ...
9816       //
9817       // This occurs when the program declares an array extern like "int X[];"
9818       //
9819       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9820       const PointerType *XTy = cast<PointerType>(X->getType());
9821       if (const ArrayType *XATy =
9822           dyn_cast<ArrayType>(XTy->getElementType()))
9823         if (const ArrayType *CATy =
9824             dyn_cast<ArrayType>(CPTy->getElementType()))
9825           if (CATy->getElementType() == XATy->getElementType()) {
9826             // At this point, we know that the cast source type is a pointer
9827             // to an array of the same type as the destination pointer
9828             // array.  Because the array type is never stepped over (there
9829             // is a leading zero) we can fold the cast into this GEP.
9830             GEP.setOperand(0, X);
9831             return &GEP;
9832           }
9833     } else if (GEP.getNumOperands() == 2) {
9834       // Transform things like:
9835       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9836       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9837       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9838       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9839       if (isa<ArrayType>(SrcElTy) &&
9840           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9841           TD->getABITypeSize(ResElTy)) {
9842         Value *Idx[2];
9843         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9844         Idx[1] = GEP.getOperand(1);
9845         Value *V = InsertNewInstBefore(
9846                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9847         // V and GEP are both pointer types --> BitCast
9848         return new BitCastInst(V, GEP.getType());
9849       }
9850       
9851       // Transform things like:
9852       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9853       //   (where tmp = 8*tmp2) into:
9854       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9855       
9856       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9857         uint64_t ArrayEltSize =
9858             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9859         
9860         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9861         // allow either a mul, shift, or constant here.
9862         Value *NewIdx = 0;
9863         ConstantInt *Scale = 0;
9864         if (ArrayEltSize == 1) {
9865           NewIdx = GEP.getOperand(1);
9866           Scale = ConstantInt::get(NewIdx->getType(), 1);
9867         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9868           NewIdx = ConstantInt::get(CI->getType(), 1);
9869           Scale = CI;
9870         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9871           if (Inst->getOpcode() == Instruction::Shl &&
9872               isa<ConstantInt>(Inst->getOperand(1))) {
9873             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9874             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9875             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9876             NewIdx = Inst->getOperand(0);
9877           } else if (Inst->getOpcode() == Instruction::Mul &&
9878                      isa<ConstantInt>(Inst->getOperand(1))) {
9879             Scale = cast<ConstantInt>(Inst->getOperand(1));
9880             NewIdx = Inst->getOperand(0);
9881           }
9882         }
9883         
9884         // If the index will be to exactly the right offset with the scale taken
9885         // out, perform the transformation. Note, we don't know whether Scale is
9886         // signed or not. We'll use unsigned version of division/modulo
9887         // operation after making sure Scale doesn't have the sign bit set.
9888         if (Scale && Scale->getSExtValue() >= 0LL &&
9889             Scale->getZExtValue() % ArrayEltSize == 0) {
9890           Scale = ConstantInt::get(Scale->getType(),
9891                                    Scale->getZExtValue() / ArrayEltSize);
9892           if (Scale->getZExtValue() != 1) {
9893             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9894                                                        false /*ZExt*/);
9895             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9896             NewIdx = InsertNewInstBefore(Sc, GEP);
9897           }
9898
9899           // Insert the new GEP instruction.
9900           Value *Idx[2];
9901           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9902           Idx[1] = NewIdx;
9903           Instruction *NewGEP =
9904             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9905           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9906           // The NewGEP must be pointer typed, so must the old one -> BitCast
9907           return new BitCastInst(NewGEP, GEP.getType());
9908         }
9909       }
9910     }
9911   }
9912
9913   return 0;
9914 }
9915
9916 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9917   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9918   if (AI.isArrayAllocation()) {  // Check C != 1
9919     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9920       const Type *NewTy = 
9921         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9922       AllocationInst *New = 0;
9923
9924       // Create and insert the replacement instruction...
9925       if (isa<MallocInst>(AI))
9926         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9927       else {
9928         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9929         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9930       }
9931
9932       InsertNewInstBefore(New, AI);
9933
9934       // Scan to the end of the allocation instructions, to skip over a block of
9935       // allocas if possible...
9936       //
9937       BasicBlock::iterator It = New;
9938       while (isa<AllocationInst>(*It)) ++It;
9939
9940       // Now that I is pointing to the first non-allocation-inst in the block,
9941       // insert our getelementptr instruction...
9942       //
9943       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9944       Value *Idx[2];
9945       Idx[0] = NullIdx;
9946       Idx[1] = NullIdx;
9947       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9948                                            New->getName()+".sub", It);
9949
9950       // Now make everything use the getelementptr instead of the original
9951       // allocation.
9952       return ReplaceInstUsesWith(AI, V);
9953     } else if (isa<UndefValue>(AI.getArraySize())) {
9954       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9955     }
9956   }
9957
9958   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9959   // Note that we only do this for alloca's, because malloc should allocate and
9960   // return a unique pointer, even for a zero byte allocation.
9961   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9962       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9963     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9964
9965   return 0;
9966 }
9967
9968 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9969   Value *Op = FI.getOperand(0);
9970
9971   // free undef -> unreachable.
9972   if (isa<UndefValue>(Op)) {
9973     // Insert a new store to null because we cannot modify the CFG here.
9974     new StoreInst(ConstantInt::getTrue(),
9975                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9976     return EraseInstFromFunction(FI);
9977   }
9978   
9979   // If we have 'free null' delete the instruction.  This can happen in stl code
9980   // when lots of inlining happens.
9981   if (isa<ConstantPointerNull>(Op))
9982     return EraseInstFromFunction(FI);
9983   
9984   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9985   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9986     FI.setOperand(0, CI->getOperand(0));
9987     return &FI;
9988   }
9989   
9990   // Change free (gep X, 0,0,0,0) into free(X)
9991   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9992     if (GEPI->hasAllZeroIndices()) {
9993       AddToWorkList(GEPI);
9994       FI.setOperand(0, GEPI->getOperand(0));
9995       return &FI;
9996     }
9997   }
9998   
9999   // Change free(malloc) into nothing, if the malloc has a single use.
10000   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10001     if (MI->hasOneUse()) {
10002       EraseInstFromFunction(FI);
10003       return EraseInstFromFunction(*MI);
10004     }
10005
10006   return 0;
10007 }
10008
10009
10010 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10011 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10012                                         const TargetData *TD) {
10013   User *CI = cast<User>(LI.getOperand(0));
10014   Value *CastOp = CI->getOperand(0);
10015
10016   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10017     // Instead of loading constant c string, use corresponding integer value
10018     // directly if string length is small enough.
10019     std::string Str;
10020     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10021       unsigned len = Str.length();
10022       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10023       unsigned numBits = Ty->getPrimitiveSizeInBits();
10024       // Replace LI with immediate integer store.
10025       if ((numBits >> 3) == len + 1) {
10026         APInt StrVal(numBits, 0);
10027         APInt SingleChar(numBits, 0);
10028         if (TD->isLittleEndian()) {
10029           for (signed i = len-1; i >= 0; i--) {
10030             SingleChar = (uint64_t) Str[i];
10031             StrVal = (StrVal << 8) | SingleChar;
10032           }
10033         } else {
10034           for (unsigned i = 0; i < len; i++) {
10035             SingleChar = (uint64_t) Str[i];
10036             StrVal = (StrVal << 8) | SingleChar;
10037           }
10038           // Append NULL at the end.
10039           SingleChar = 0;
10040           StrVal = (StrVal << 8) | SingleChar;
10041         }
10042         Value *NL = ConstantInt::get(StrVal);
10043         return IC.ReplaceInstUsesWith(LI, NL);
10044       }
10045     }
10046   }
10047
10048   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10049   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10050     const Type *SrcPTy = SrcTy->getElementType();
10051
10052     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10053          isa<VectorType>(DestPTy)) {
10054       // If the source is an array, the code below will not succeed.  Check to
10055       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10056       // constants.
10057       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10058         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10059           if (ASrcTy->getNumElements() != 0) {
10060             Value *Idxs[2];
10061             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10062             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10063             SrcTy = cast<PointerType>(CastOp->getType());
10064             SrcPTy = SrcTy->getElementType();
10065           }
10066
10067       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10068             isa<VectorType>(SrcPTy)) &&
10069           // Do not allow turning this into a load of an integer, which is then
10070           // casted to a pointer, this pessimizes pointer analysis a lot.
10071           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10072           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10073                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10074
10075         // Okay, we are casting from one integer or pointer type to another of
10076         // the same size.  Instead of casting the pointer before the load, cast
10077         // the result of the loaded value.
10078         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10079                                                              CI->getName(),
10080                                                          LI.isVolatile()),LI);
10081         // Now cast the result of the load.
10082         return new BitCastInst(NewLoad, LI.getType());
10083       }
10084     }
10085   }
10086   return 0;
10087 }
10088
10089 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10090 /// from this value cannot trap.  If it is not obviously safe to load from the
10091 /// specified pointer, we do a quick local scan of the basic block containing
10092 /// ScanFrom, to determine if the address is already accessed.
10093 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10094   // If it is an alloca it is always safe to load from.
10095   if (isa<AllocaInst>(V)) return true;
10096
10097   // If it is a global variable it is mostly safe to load from.
10098   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10099     // Don't try to evaluate aliases.  External weak GV can be null.
10100     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10101
10102   // Otherwise, be a little bit agressive by scanning the local block where we
10103   // want to check to see if the pointer is already being loaded or stored
10104   // from/to.  If so, the previous load or store would have already trapped,
10105   // so there is no harm doing an extra load (also, CSE will later eliminate
10106   // the load entirely).
10107   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10108
10109   while (BBI != E) {
10110     --BBI;
10111
10112     // If we see a free or a call (which might do a free) the pointer could be
10113     // marked invalid.
10114     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10115       return false;
10116     
10117     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10118       if (LI->getOperand(0) == V) return true;
10119     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10120       if (SI->getOperand(1) == V) return true;
10121     }
10122
10123   }
10124   return false;
10125 }
10126
10127 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10128 /// until we find the underlying object a pointer is referring to or something
10129 /// we don't understand.  Note that the returned pointer may be offset from the
10130 /// input, because we ignore GEP indices.
10131 static Value *GetUnderlyingObject(Value *Ptr) {
10132   while (1) {
10133     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10134       if (CE->getOpcode() == Instruction::BitCast ||
10135           CE->getOpcode() == Instruction::GetElementPtr)
10136         Ptr = CE->getOperand(0);
10137       else
10138         return Ptr;
10139     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10140       Ptr = BCI->getOperand(0);
10141     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10142       Ptr = GEP->getOperand(0);
10143     } else {
10144       return Ptr;
10145     }
10146   }
10147 }
10148
10149 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10150   Value *Op = LI.getOperand(0);
10151
10152   // Attempt to improve the alignment.
10153   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10154   if (KnownAlign >
10155       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10156                                 LI.getAlignment()))
10157     LI.setAlignment(KnownAlign);
10158
10159   // load (cast X) --> cast (load X) iff safe
10160   if (isa<CastInst>(Op))
10161     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10162       return Res;
10163
10164   // None of the following transforms are legal for volatile loads.
10165   if (LI.isVolatile()) return 0;
10166   
10167   if (&LI.getParent()->front() != &LI) {
10168     BasicBlock::iterator BBI = &LI; --BBI;
10169     // If the instruction immediately before this is a store to the same
10170     // address, do a simple form of store->load forwarding.
10171     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10172       if (SI->getOperand(1) == LI.getOperand(0))
10173         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10174     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10175       if (LIB->getOperand(0) == LI.getOperand(0))
10176         return ReplaceInstUsesWith(LI, LIB);
10177   }
10178
10179   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10180     const Value *GEPI0 = GEPI->getOperand(0);
10181     // TODO: Consider a target hook for valid address spaces for this xform.
10182     if (isa<ConstantPointerNull>(GEPI0) &&
10183         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10184       // Insert a new store to null instruction before the load to indicate
10185       // that this code is not reachable.  We do this instead of inserting
10186       // an unreachable instruction directly because we cannot modify the
10187       // CFG.
10188       new StoreInst(UndefValue::get(LI.getType()),
10189                     Constant::getNullValue(Op->getType()), &LI);
10190       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10191     }
10192   } 
10193
10194   if (Constant *C = dyn_cast<Constant>(Op)) {
10195     // load null/undef -> undef
10196     // TODO: Consider a target hook for valid address spaces for this xform.
10197     if (isa<UndefValue>(C) || (C->isNullValue() && 
10198         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10199       // Insert a new store to null instruction before the load to indicate that
10200       // this code is not reachable.  We do this instead of inserting an
10201       // unreachable instruction directly because we cannot modify the CFG.
10202       new StoreInst(UndefValue::get(LI.getType()),
10203                     Constant::getNullValue(Op->getType()), &LI);
10204       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10205     }
10206
10207     // Instcombine load (constant global) into the value loaded.
10208     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10209       if (GV->isConstant() && !GV->isDeclaration())
10210         return ReplaceInstUsesWith(LI, GV->getInitializer());
10211
10212     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10213     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10214       if (CE->getOpcode() == Instruction::GetElementPtr) {
10215         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10216           if (GV->isConstant() && !GV->isDeclaration())
10217             if (Constant *V = 
10218                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10219               return ReplaceInstUsesWith(LI, V);
10220         if (CE->getOperand(0)->isNullValue()) {
10221           // Insert a new store to null instruction before the load to indicate
10222           // that this code is not reachable.  We do this instead of inserting
10223           // an unreachable instruction directly because we cannot modify the
10224           // CFG.
10225           new StoreInst(UndefValue::get(LI.getType()),
10226                         Constant::getNullValue(Op->getType()), &LI);
10227           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10228         }
10229
10230       } else if (CE->isCast()) {
10231         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10232           return Res;
10233       }
10234     }
10235   }
10236     
10237   // If this load comes from anywhere in a constant global, and if the global
10238   // is all undef or zero, we know what it loads.
10239   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10240     if (GV->isConstant() && GV->hasInitializer()) {
10241       if (GV->getInitializer()->isNullValue())
10242         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10243       else if (isa<UndefValue>(GV->getInitializer()))
10244         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10245     }
10246   }
10247
10248   if (Op->hasOneUse()) {
10249     // Change select and PHI nodes to select values instead of addresses: this
10250     // helps alias analysis out a lot, allows many others simplifications, and
10251     // exposes redundancy in the code.
10252     //
10253     // Note that we cannot do the transformation unless we know that the
10254     // introduced loads cannot trap!  Something like this is valid as long as
10255     // the condition is always false: load (select bool %C, int* null, int* %G),
10256     // but it would not be valid if we transformed it to load from null
10257     // unconditionally.
10258     //
10259     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10260       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10261       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10262           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10263         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10264                                      SI->getOperand(1)->getName()+".val"), LI);
10265         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10266                                      SI->getOperand(2)->getName()+".val"), LI);
10267         return SelectInst::Create(SI->getCondition(), V1, V2);
10268       }
10269
10270       // load (select (cond, null, P)) -> load P
10271       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10272         if (C->isNullValue()) {
10273           LI.setOperand(0, SI->getOperand(2));
10274           return &LI;
10275         }
10276
10277       // load (select (cond, P, null)) -> load P
10278       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10279         if (C->isNullValue()) {
10280           LI.setOperand(0, SI->getOperand(1));
10281           return &LI;
10282         }
10283     }
10284   }
10285   return 0;
10286 }
10287
10288 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10289 /// when possible.
10290 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10291   User *CI = cast<User>(SI.getOperand(1));
10292   Value *CastOp = CI->getOperand(0);
10293
10294   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10295   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10296     const Type *SrcPTy = SrcTy->getElementType();
10297
10298     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10299       // If the source is an array, the code below will not succeed.  Check to
10300       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10301       // constants.
10302       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10303         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10304           if (ASrcTy->getNumElements() != 0) {
10305             Value* Idxs[2];
10306             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10307             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10308             SrcTy = cast<PointerType>(CastOp->getType());
10309             SrcPTy = SrcTy->getElementType();
10310           }
10311
10312       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10313           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10314                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10315
10316         // Okay, we are casting from one integer or pointer type to another of
10317         // the same size.  Instead of casting the pointer before 
10318         // the store, cast the value to be stored.
10319         Value *NewCast;
10320         Value *SIOp0 = SI.getOperand(0);
10321         Instruction::CastOps opcode = Instruction::BitCast;
10322         const Type* CastSrcTy = SIOp0->getType();
10323         const Type* CastDstTy = SrcPTy;
10324         if (isa<PointerType>(CastDstTy)) {
10325           if (CastSrcTy->isInteger())
10326             opcode = Instruction::IntToPtr;
10327         } else if (isa<IntegerType>(CastDstTy)) {
10328           if (isa<PointerType>(SIOp0->getType()))
10329             opcode = Instruction::PtrToInt;
10330         }
10331         if (Constant *C = dyn_cast<Constant>(SIOp0))
10332           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10333         else
10334           NewCast = IC.InsertNewInstBefore(
10335             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10336             SI);
10337         return new StoreInst(NewCast, CastOp);
10338       }
10339     }
10340   }
10341   return 0;
10342 }
10343
10344 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10345   Value *Val = SI.getOperand(0);
10346   Value *Ptr = SI.getOperand(1);
10347
10348   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10349     EraseInstFromFunction(SI);
10350     ++NumCombined;
10351     return 0;
10352   }
10353   
10354   // If the RHS is an alloca with a single use, zapify the store, making the
10355   // alloca dead.
10356   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10357     if (isa<AllocaInst>(Ptr)) {
10358       EraseInstFromFunction(SI);
10359       ++NumCombined;
10360       return 0;
10361     }
10362     
10363     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10364       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10365           GEP->getOperand(0)->hasOneUse()) {
10366         EraseInstFromFunction(SI);
10367         ++NumCombined;
10368         return 0;
10369       }
10370   }
10371
10372   // Attempt to improve the alignment.
10373   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10374   if (KnownAlign >
10375       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10376                                 SI.getAlignment()))
10377     SI.setAlignment(KnownAlign);
10378
10379   // Do really simple DSE, to catch cases where there are several consequtive
10380   // stores to the same location, separated by a few arithmetic operations. This
10381   // situation often occurs with bitfield accesses.
10382   BasicBlock::iterator BBI = &SI;
10383   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10384        --ScanInsts) {
10385     --BBI;
10386     
10387     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10388       // Prev store isn't volatile, and stores to the same location?
10389       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10390         ++NumDeadStore;
10391         ++BBI;
10392         EraseInstFromFunction(*PrevSI);
10393         continue;
10394       }
10395       break;
10396     }
10397     
10398     // If this is a load, we have to stop.  However, if the loaded value is from
10399     // the pointer we're loading and is producing the pointer we're storing,
10400     // then *this* store is dead (X = load P; store X -> P).
10401     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10402       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10403         EraseInstFromFunction(SI);
10404         ++NumCombined;
10405         return 0;
10406       }
10407       // Otherwise, this is a load from some other location.  Stores before it
10408       // may not be dead.
10409       break;
10410     }
10411     
10412     // Don't skip over loads or things that can modify memory.
10413     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10414       break;
10415   }
10416   
10417   
10418   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10419
10420   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10421   if (isa<ConstantPointerNull>(Ptr)) {
10422     if (!isa<UndefValue>(Val)) {
10423       SI.setOperand(0, UndefValue::get(Val->getType()));
10424       if (Instruction *U = dyn_cast<Instruction>(Val))
10425         AddToWorkList(U);  // Dropped a use.
10426       ++NumCombined;
10427     }
10428     return 0;  // Do not modify these!
10429   }
10430
10431   // store undef, Ptr -> noop
10432   if (isa<UndefValue>(Val)) {
10433     EraseInstFromFunction(SI);
10434     ++NumCombined;
10435     return 0;
10436   }
10437
10438   // If the pointer destination is a cast, see if we can fold the cast into the
10439   // source instead.
10440   if (isa<CastInst>(Ptr))
10441     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10442       return Res;
10443   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10444     if (CE->isCast())
10445       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10446         return Res;
10447
10448   
10449   // If this store is the last instruction in the basic block, and if the block
10450   // ends with an unconditional branch, try to move it to the successor block.
10451   BBI = &SI; ++BBI;
10452   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10453     if (BI->isUnconditional())
10454       if (SimplifyStoreAtEndOfBlock(SI))
10455         return 0;  // xform done!
10456   
10457   return 0;
10458 }
10459
10460 /// SimplifyStoreAtEndOfBlock - Turn things like:
10461 ///   if () { *P = v1; } else { *P = v2 }
10462 /// into a phi node with a store in the successor.
10463 ///
10464 /// Simplify things like:
10465 ///   *P = v1; if () { *P = v2; }
10466 /// into a phi node with a store in the successor.
10467 ///
10468 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10469   BasicBlock *StoreBB = SI.getParent();
10470   
10471   // Check to see if the successor block has exactly two incoming edges.  If
10472   // so, see if the other predecessor contains a store to the same location.
10473   // if so, insert a PHI node (if needed) and move the stores down.
10474   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10475   
10476   // Determine whether Dest has exactly two predecessors and, if so, compute
10477   // the other predecessor.
10478   pred_iterator PI = pred_begin(DestBB);
10479   BasicBlock *OtherBB = 0;
10480   if (*PI != StoreBB)
10481     OtherBB = *PI;
10482   ++PI;
10483   if (PI == pred_end(DestBB))
10484     return false;
10485   
10486   if (*PI != StoreBB) {
10487     if (OtherBB)
10488       return false;
10489     OtherBB = *PI;
10490   }
10491   if (++PI != pred_end(DestBB))
10492     return false;
10493
10494   // Bail out if all the relevant blocks aren't distinct (this can happen,
10495   // for example, if SI is in an infinite loop)
10496   if (StoreBB == DestBB || OtherBB == DestBB)
10497     return false;
10498
10499   // Verify that the other block ends in a branch and is not otherwise empty.
10500   BasicBlock::iterator BBI = OtherBB->getTerminator();
10501   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10502   if (!OtherBr || BBI == OtherBB->begin())
10503     return false;
10504   
10505   // If the other block ends in an unconditional branch, check for the 'if then
10506   // else' case.  there is an instruction before the branch.
10507   StoreInst *OtherStore = 0;
10508   if (OtherBr->isUnconditional()) {
10509     // If this isn't a store, or isn't a store to the same location, bail out.
10510     --BBI;
10511     OtherStore = dyn_cast<StoreInst>(BBI);
10512     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10513       return false;
10514   } else {
10515     // Otherwise, the other block ended with a conditional branch. If one of the
10516     // destinations is StoreBB, then we have the if/then case.
10517     if (OtherBr->getSuccessor(0) != StoreBB && 
10518         OtherBr->getSuccessor(1) != StoreBB)
10519       return false;
10520     
10521     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10522     // if/then triangle.  See if there is a store to the same ptr as SI that
10523     // lives in OtherBB.
10524     for (;; --BBI) {
10525       // Check to see if we find the matching store.
10526       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10527         if (OtherStore->getOperand(1) != SI.getOperand(1))
10528           return false;
10529         break;
10530       }
10531       // If we find something that may be using or overwriting the stored
10532       // value, or if we run out of instructions, we can't do the xform.
10533       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10534           BBI == OtherBB->begin())
10535         return false;
10536     }
10537     
10538     // In order to eliminate the store in OtherBr, we have to
10539     // make sure nothing reads or overwrites the stored value in
10540     // StoreBB.
10541     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10542       // FIXME: This should really be AA driven.
10543       if (I->mayReadFromMemory() || I->mayWriteToMemory())
10544         return false;
10545     }
10546   }
10547   
10548   // Insert a PHI node now if we need it.
10549   Value *MergedVal = OtherStore->getOperand(0);
10550   if (MergedVal != SI.getOperand(0)) {
10551     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10552     PN->reserveOperandSpace(2);
10553     PN->addIncoming(SI.getOperand(0), SI.getParent());
10554     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10555     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10556   }
10557   
10558   // Advance to a place where it is safe to insert the new store and
10559   // insert it.
10560   BBI = DestBB->getFirstNonPHI();
10561   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10562                                     OtherStore->isVolatile()), *BBI);
10563   
10564   // Nuke the old stores.
10565   EraseInstFromFunction(SI);
10566   EraseInstFromFunction(*OtherStore);
10567   ++NumCombined;
10568   return true;
10569 }
10570
10571
10572 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10573   // Change br (not X), label True, label False to: br X, label False, True
10574   Value *X = 0;
10575   BasicBlock *TrueDest;
10576   BasicBlock *FalseDest;
10577   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10578       !isa<Constant>(X)) {
10579     // Swap Destinations and condition...
10580     BI.setCondition(X);
10581     BI.setSuccessor(0, FalseDest);
10582     BI.setSuccessor(1, TrueDest);
10583     return &BI;
10584   }
10585
10586   // Cannonicalize fcmp_one -> fcmp_oeq
10587   FCmpInst::Predicate FPred; Value *Y;
10588   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10589                              TrueDest, FalseDest)))
10590     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10591          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10592       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10593       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10594       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10595       NewSCC->takeName(I);
10596       // Swap Destinations and condition...
10597       BI.setCondition(NewSCC);
10598       BI.setSuccessor(0, FalseDest);
10599       BI.setSuccessor(1, TrueDest);
10600       RemoveFromWorkList(I);
10601       I->eraseFromParent();
10602       AddToWorkList(NewSCC);
10603       return &BI;
10604     }
10605
10606   // Cannonicalize icmp_ne -> icmp_eq
10607   ICmpInst::Predicate IPred;
10608   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10609                       TrueDest, FalseDest)))
10610     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10611          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10612          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10613       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10614       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10615       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10616       NewSCC->takeName(I);
10617       // Swap Destinations and condition...
10618       BI.setCondition(NewSCC);
10619       BI.setSuccessor(0, FalseDest);
10620       BI.setSuccessor(1, TrueDest);
10621       RemoveFromWorkList(I);
10622       I->eraseFromParent();;
10623       AddToWorkList(NewSCC);
10624       return &BI;
10625     }
10626
10627   return 0;
10628 }
10629
10630 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10631   Value *Cond = SI.getCondition();
10632   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10633     if (I->getOpcode() == Instruction::Add)
10634       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10635         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10636         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10637           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10638                                                 AddRHS));
10639         SI.setOperand(0, I->getOperand(0));
10640         AddToWorkList(I);
10641         return &SI;
10642       }
10643   }
10644   return 0;
10645 }
10646
10647 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10648   // See if we are trying to extract a known value. If so, use that instead.
10649   if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
10650                                      EV.idx_end(), &EV))
10651     return ReplaceInstUsesWith(EV, Elt);
10652
10653   // No changes
10654   return 0;
10655 }
10656
10657 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10658 /// is to leave as a vector operation.
10659 static bool CheapToScalarize(Value *V, bool isConstant) {
10660   if (isa<ConstantAggregateZero>(V)) 
10661     return true;
10662   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10663     if (isConstant) return true;
10664     // If all elts are the same, we can extract.
10665     Constant *Op0 = C->getOperand(0);
10666     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10667       if (C->getOperand(i) != Op0)
10668         return false;
10669     return true;
10670   }
10671   Instruction *I = dyn_cast<Instruction>(V);
10672   if (!I) return false;
10673   
10674   // Insert element gets simplified to the inserted element or is deleted if
10675   // this is constant idx extract element and its a constant idx insertelt.
10676   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10677       isa<ConstantInt>(I->getOperand(2)))
10678     return true;
10679   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10680     return true;
10681   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10682     if (BO->hasOneUse() &&
10683         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10684          CheapToScalarize(BO->getOperand(1), isConstant)))
10685       return true;
10686   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10687     if (CI->hasOneUse() &&
10688         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10689          CheapToScalarize(CI->getOperand(1), isConstant)))
10690       return true;
10691   
10692   return false;
10693 }
10694
10695 /// Read and decode a shufflevector mask.
10696 ///
10697 /// It turns undef elements into values that are larger than the number of
10698 /// elements in the input.
10699 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10700   unsigned NElts = SVI->getType()->getNumElements();
10701   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10702     return std::vector<unsigned>(NElts, 0);
10703   if (isa<UndefValue>(SVI->getOperand(2)))
10704     return std::vector<unsigned>(NElts, 2*NElts);
10705
10706   std::vector<unsigned> Result;
10707   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10708   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10709     if (isa<UndefValue>(*i))
10710       Result.push_back(NElts*2);  // undef -> 8
10711     else
10712       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10713   return Result;
10714 }
10715
10716 /// FindScalarElement - Given a vector and an element number, see if the scalar
10717 /// value is already around as a register, for example if it were inserted then
10718 /// extracted from the vector.
10719 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10720   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10721   const VectorType *PTy = cast<VectorType>(V->getType());
10722   unsigned Width = PTy->getNumElements();
10723   if (EltNo >= Width)  // Out of range access.
10724     return UndefValue::get(PTy->getElementType());
10725   
10726   if (isa<UndefValue>(V))
10727     return UndefValue::get(PTy->getElementType());
10728   else if (isa<ConstantAggregateZero>(V))
10729     return Constant::getNullValue(PTy->getElementType());
10730   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10731     return CP->getOperand(EltNo);
10732   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10733     // If this is an insert to a variable element, we don't know what it is.
10734     if (!isa<ConstantInt>(III->getOperand(2))) 
10735       return 0;
10736     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10737     
10738     // If this is an insert to the element we are looking for, return the
10739     // inserted value.
10740     if (EltNo == IIElt) 
10741       return III->getOperand(1);
10742     
10743     // Otherwise, the insertelement doesn't modify the value, recurse on its
10744     // vector input.
10745     return FindScalarElement(III->getOperand(0), EltNo);
10746   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10747     unsigned InEl = getShuffleMask(SVI)[EltNo];
10748     if (InEl < Width)
10749       return FindScalarElement(SVI->getOperand(0), InEl);
10750     else if (InEl < Width*2)
10751       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10752     else
10753       return UndefValue::get(PTy->getElementType());
10754   }
10755   
10756   // Otherwise, we don't know.
10757   return 0;
10758 }
10759
10760 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10761   // If vector val is undef, replace extract with scalar undef.
10762   if (isa<UndefValue>(EI.getOperand(0)))
10763     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10764
10765   // If vector val is constant 0, replace extract with scalar 0.
10766   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10767     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10768   
10769   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10770     // If vector val is constant with all elements the same, replace EI with
10771     // that element. When the elements are not identical, we cannot replace yet
10772     // (we do that below, but only when the index is constant).
10773     Constant *op0 = C->getOperand(0);
10774     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10775       if (C->getOperand(i) != op0) {
10776         op0 = 0; 
10777         break;
10778       }
10779     if (op0)
10780       return ReplaceInstUsesWith(EI, op0);
10781   }
10782   
10783   // If extracting a specified index from the vector, see if we can recursively
10784   // find a previously computed scalar that was inserted into the vector.
10785   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10786     unsigned IndexVal = IdxC->getZExtValue();
10787     unsigned VectorWidth = 
10788       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10789       
10790     // If this is extracting an invalid index, turn this into undef, to avoid
10791     // crashing the code below.
10792     if (IndexVal >= VectorWidth)
10793       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10794     
10795     // This instruction only demands the single element from the input vector.
10796     // If the input vector has a single use, simplify it based on this use
10797     // property.
10798     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10799       uint64_t UndefElts;
10800       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10801                                                 1 << IndexVal,
10802                                                 UndefElts)) {
10803         EI.setOperand(0, V);
10804         return &EI;
10805       }
10806     }
10807     
10808     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10809       return ReplaceInstUsesWith(EI, Elt);
10810     
10811     // If the this extractelement is directly using a bitcast from a vector of
10812     // the same number of elements, see if we can find the source element from
10813     // it.  In this case, we will end up needing to bitcast the scalars.
10814     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10815       if (const VectorType *VT = 
10816               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10817         if (VT->getNumElements() == VectorWidth)
10818           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10819             return new BitCastInst(Elt, EI.getType());
10820     }
10821   }
10822   
10823   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10824     if (I->hasOneUse()) {
10825       // Push extractelement into predecessor operation if legal and
10826       // profitable to do so
10827       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10828         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10829         if (CheapToScalarize(BO, isConstantElt)) {
10830           ExtractElementInst *newEI0 = 
10831             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10832                                    EI.getName()+".lhs");
10833           ExtractElementInst *newEI1 =
10834             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10835                                    EI.getName()+".rhs");
10836           InsertNewInstBefore(newEI0, EI);
10837           InsertNewInstBefore(newEI1, EI);
10838           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10839         }
10840       } else if (isa<LoadInst>(I)) {
10841         unsigned AS = 
10842           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10843         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10844                                          PointerType::get(EI.getType(), AS),EI);
10845         GetElementPtrInst *GEP =
10846           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10847         InsertNewInstBefore(GEP, EI);
10848         return new LoadInst(GEP);
10849       }
10850     }
10851     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10852       // Extracting the inserted element?
10853       if (IE->getOperand(2) == EI.getOperand(1))
10854         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10855       // If the inserted and extracted elements are constants, they must not
10856       // be the same value, extract from the pre-inserted value instead.
10857       if (isa<Constant>(IE->getOperand(2)) &&
10858           isa<Constant>(EI.getOperand(1))) {
10859         AddUsesToWorkList(EI);
10860         EI.setOperand(0, IE->getOperand(0));
10861         return &EI;
10862       }
10863     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10864       // If this is extracting an element from a shufflevector, figure out where
10865       // it came from and extract from the appropriate input element instead.
10866       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10867         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10868         Value *Src;
10869         if (SrcIdx < SVI->getType()->getNumElements())
10870           Src = SVI->getOperand(0);
10871         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10872           SrcIdx -= SVI->getType()->getNumElements();
10873           Src = SVI->getOperand(1);
10874         } else {
10875           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10876         }
10877         return new ExtractElementInst(Src, SrcIdx);
10878       }
10879     }
10880   }
10881   return 0;
10882 }
10883
10884 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10885 /// elements from either LHS or RHS, return the shuffle mask and true. 
10886 /// Otherwise, return false.
10887 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10888                                          std::vector<Constant*> &Mask) {
10889   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10890          "Invalid CollectSingleShuffleElements");
10891   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10892
10893   if (isa<UndefValue>(V)) {
10894     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10895     return true;
10896   } else if (V == LHS) {
10897     for (unsigned i = 0; i != NumElts; ++i)
10898       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10899     return true;
10900   } else if (V == RHS) {
10901     for (unsigned i = 0; i != NumElts; ++i)
10902       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10903     return true;
10904   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10905     // If this is an insert of an extract from some other vector, include it.
10906     Value *VecOp    = IEI->getOperand(0);
10907     Value *ScalarOp = IEI->getOperand(1);
10908     Value *IdxOp    = IEI->getOperand(2);
10909     
10910     if (!isa<ConstantInt>(IdxOp))
10911       return false;
10912     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10913     
10914     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10915       // Okay, we can handle this if the vector we are insertinting into is
10916       // transitively ok.
10917       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10918         // If so, update the mask to reflect the inserted undef.
10919         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10920         return true;
10921       }      
10922     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10923       if (isa<ConstantInt>(EI->getOperand(1)) &&
10924           EI->getOperand(0)->getType() == V->getType()) {
10925         unsigned ExtractedIdx =
10926           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10927         
10928         // This must be extracting from either LHS or RHS.
10929         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10930           // Okay, we can handle this if the vector we are insertinting into is
10931           // transitively ok.
10932           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10933             // If so, update the mask to reflect the inserted value.
10934             if (EI->getOperand(0) == LHS) {
10935               Mask[InsertedIdx & (NumElts-1)] = 
10936                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10937             } else {
10938               assert(EI->getOperand(0) == RHS);
10939               Mask[InsertedIdx & (NumElts-1)] = 
10940                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10941               
10942             }
10943             return true;
10944           }
10945         }
10946       }
10947     }
10948   }
10949   // TODO: Handle shufflevector here!
10950   
10951   return false;
10952 }
10953
10954 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10955 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10956 /// that computes V and the LHS value of the shuffle.
10957 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10958                                      Value *&RHS) {
10959   assert(isa<VectorType>(V->getType()) && 
10960          (RHS == 0 || V->getType() == RHS->getType()) &&
10961          "Invalid shuffle!");
10962   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10963
10964   if (isa<UndefValue>(V)) {
10965     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10966     return V;
10967   } else if (isa<ConstantAggregateZero>(V)) {
10968     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10969     return V;
10970   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10971     // If this is an insert of an extract from some other vector, include it.
10972     Value *VecOp    = IEI->getOperand(0);
10973     Value *ScalarOp = IEI->getOperand(1);
10974     Value *IdxOp    = IEI->getOperand(2);
10975     
10976     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10977       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10978           EI->getOperand(0)->getType() == V->getType()) {
10979         unsigned ExtractedIdx =
10980           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10981         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10982         
10983         // Either the extracted from or inserted into vector must be RHSVec,
10984         // otherwise we'd end up with a shuffle of three inputs.
10985         if (EI->getOperand(0) == RHS || RHS == 0) {
10986           RHS = EI->getOperand(0);
10987           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10988           Mask[InsertedIdx & (NumElts-1)] = 
10989             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10990           return V;
10991         }
10992         
10993         if (VecOp == RHS) {
10994           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10995           // Everything but the extracted element is replaced with the RHS.
10996           for (unsigned i = 0; i != NumElts; ++i) {
10997             if (i != InsertedIdx)
10998               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10999           }
11000           return V;
11001         }
11002         
11003         // If this insertelement is a chain that comes from exactly these two
11004         // vectors, return the vector and the effective shuffle.
11005         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11006           return EI->getOperand(0);
11007         
11008       }
11009     }
11010   }
11011   // TODO: Handle shufflevector here!
11012   
11013   // Otherwise, can't do anything fancy.  Return an identity vector.
11014   for (unsigned i = 0; i != NumElts; ++i)
11015     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11016   return V;
11017 }
11018
11019 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11020   Value *VecOp    = IE.getOperand(0);
11021   Value *ScalarOp = IE.getOperand(1);
11022   Value *IdxOp    = IE.getOperand(2);
11023   
11024   // Inserting an undef or into an undefined place, remove this.
11025   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11026     ReplaceInstUsesWith(IE, VecOp);
11027   
11028   // If the inserted element was extracted from some other vector, and if the 
11029   // indexes are constant, try to turn this into a shufflevector operation.
11030   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11031     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11032         EI->getOperand(0)->getType() == IE.getType()) {
11033       unsigned NumVectorElts = IE.getType()->getNumElements();
11034       unsigned ExtractedIdx =
11035         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11036       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11037       
11038       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11039         return ReplaceInstUsesWith(IE, VecOp);
11040       
11041       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11042         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11043       
11044       // If we are extracting a value from a vector, then inserting it right
11045       // back into the same place, just use the input vector.
11046       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11047         return ReplaceInstUsesWith(IE, VecOp);      
11048       
11049       // We could theoretically do this for ANY input.  However, doing so could
11050       // turn chains of insertelement instructions into a chain of shufflevector
11051       // instructions, and right now we do not merge shufflevectors.  As such,
11052       // only do this in a situation where it is clear that there is benefit.
11053       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11054         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11055         // the values of VecOp, except then one read from EIOp0.
11056         // Build a new shuffle mask.
11057         std::vector<Constant*> Mask;
11058         if (isa<UndefValue>(VecOp))
11059           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11060         else {
11061           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11062           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11063                                                        NumVectorElts));
11064         } 
11065         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11066         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11067                                      ConstantVector::get(Mask));
11068       }
11069       
11070       // If this insertelement isn't used by some other insertelement, turn it
11071       // (and any insertelements it points to), into one big shuffle.
11072       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11073         std::vector<Constant*> Mask;
11074         Value *RHS = 0;
11075         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11076         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11077         // We now have a shuffle of LHS, RHS, Mask.
11078         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11079       }
11080     }
11081   }
11082
11083   return 0;
11084 }
11085
11086
11087 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11088   Value *LHS = SVI.getOperand(0);
11089   Value *RHS = SVI.getOperand(1);
11090   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11091
11092   bool MadeChange = false;
11093   
11094   // Undefined shuffle mask -> undefined value.
11095   if (isa<UndefValue>(SVI.getOperand(2)))
11096     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11097   
11098   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11099   // the undef, change them to undefs.
11100   if (isa<UndefValue>(SVI.getOperand(1))) {
11101     // Scan to see if there are any references to the RHS.  If so, replace them
11102     // with undef element refs and set MadeChange to true.
11103     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11104       if (Mask[i] >= e && Mask[i] != 2*e) {
11105         Mask[i] = 2*e;
11106         MadeChange = true;
11107       }
11108     }
11109     
11110     if (MadeChange) {
11111       // Remap any references to RHS to use LHS.
11112       std::vector<Constant*> Elts;
11113       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11114         if (Mask[i] == 2*e)
11115           Elts.push_back(UndefValue::get(Type::Int32Ty));
11116         else
11117           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11118       }
11119       SVI.setOperand(2, ConstantVector::get(Elts));
11120     }
11121   }
11122   
11123   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11124   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11125   if (LHS == RHS || isa<UndefValue>(LHS)) {
11126     if (isa<UndefValue>(LHS) && LHS == RHS) {
11127       // shuffle(undef,undef,mask) -> undef.
11128       return ReplaceInstUsesWith(SVI, LHS);
11129     }
11130     
11131     // Remap any references to RHS to use LHS.
11132     std::vector<Constant*> Elts;
11133     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11134       if (Mask[i] >= 2*e)
11135         Elts.push_back(UndefValue::get(Type::Int32Ty));
11136       else {
11137         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11138             (Mask[i] <  e && isa<UndefValue>(LHS)))
11139           Mask[i] = 2*e;     // Turn into undef.
11140         else
11141           Mask[i] &= (e-1);  // Force to LHS.
11142         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11143       }
11144     }
11145     SVI.setOperand(0, SVI.getOperand(1));
11146     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11147     SVI.setOperand(2, ConstantVector::get(Elts));
11148     LHS = SVI.getOperand(0);
11149     RHS = SVI.getOperand(1);
11150     MadeChange = true;
11151   }
11152   
11153   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11154   bool isLHSID = true, isRHSID = true;
11155     
11156   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11157     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11158     // Is this an identity shuffle of the LHS value?
11159     isLHSID &= (Mask[i] == i);
11160       
11161     // Is this an identity shuffle of the RHS value?
11162     isRHSID &= (Mask[i]-e == i);
11163   }
11164
11165   // Eliminate identity shuffles.
11166   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11167   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11168   
11169   // If the LHS is a shufflevector itself, see if we can combine it with this
11170   // one without producing an unusual shuffle.  Here we are really conservative:
11171   // we are absolutely afraid of producing a shuffle mask not in the input
11172   // program, because the code gen may not be smart enough to turn a merged
11173   // shuffle into two specific shuffles: it may produce worse code.  As such,
11174   // we only merge two shuffles if the result is one of the two input shuffle
11175   // masks.  In this case, merging the shuffles just removes one instruction,
11176   // which we know is safe.  This is good for things like turning:
11177   // (splat(splat)) -> splat.
11178   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11179     if (isa<UndefValue>(RHS)) {
11180       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11181
11182       std::vector<unsigned> NewMask;
11183       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11184         if (Mask[i] >= 2*e)
11185           NewMask.push_back(2*e);
11186         else
11187           NewMask.push_back(LHSMask[Mask[i]]);
11188       
11189       // If the result mask is equal to the src shuffle or this shuffle mask, do
11190       // the replacement.
11191       if (NewMask == LHSMask || NewMask == Mask) {
11192         std::vector<Constant*> Elts;
11193         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11194           if (NewMask[i] >= e*2) {
11195             Elts.push_back(UndefValue::get(Type::Int32Ty));
11196           } else {
11197             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11198           }
11199         }
11200         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11201                                      LHSSVI->getOperand(1),
11202                                      ConstantVector::get(Elts));
11203       }
11204     }
11205   }
11206
11207   return MadeChange ? &SVI : 0;
11208 }
11209
11210
11211
11212
11213 /// TryToSinkInstruction - Try to move the specified instruction from its
11214 /// current block into the beginning of DestBlock, which can only happen if it's
11215 /// safe to move the instruction past all of the instructions between it and the
11216 /// end of its block.
11217 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11218   assert(I->hasOneUse() && "Invariants didn't hold!");
11219
11220   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11221   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11222     return false;
11223
11224   // Do not sink alloca instructions out of the entry block.
11225   if (isa<AllocaInst>(I) && I->getParent() ==
11226         &DestBlock->getParent()->getEntryBlock())
11227     return false;
11228
11229   // We can only sink load instructions if there is nothing between the load and
11230   // the end of block that could change the value.
11231   if (I->mayReadFromMemory()) {
11232     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11233          Scan != E; ++Scan)
11234       if (Scan->mayWriteToMemory())
11235         return false;
11236   }
11237
11238   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11239
11240   I->moveBefore(InsertPos);
11241   ++NumSunkInst;
11242   return true;
11243 }
11244
11245
11246 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11247 /// all reachable code to the worklist.
11248 ///
11249 /// This has a couple of tricks to make the code faster and more powerful.  In
11250 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11251 /// them to the worklist (this significantly speeds up instcombine on code where
11252 /// many instructions are dead or constant).  Additionally, if we find a branch
11253 /// whose condition is a known constant, we only visit the reachable successors.
11254 ///
11255 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11256                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11257                                        InstCombiner &IC,
11258                                        const TargetData *TD) {
11259   std::vector<BasicBlock*> Worklist;
11260   Worklist.push_back(BB);
11261
11262   while (!Worklist.empty()) {
11263     BB = Worklist.back();
11264     Worklist.pop_back();
11265     
11266     // We have now visited this block!  If we've already been here, ignore it.
11267     if (!Visited.insert(BB)) continue;
11268     
11269     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11270       Instruction *Inst = BBI++;
11271       
11272       // DCE instruction if trivially dead.
11273       if (isInstructionTriviallyDead(Inst)) {
11274         ++NumDeadInst;
11275         DOUT << "IC: DCE: " << *Inst;
11276         Inst->eraseFromParent();
11277         continue;
11278       }
11279       
11280       // ConstantProp instruction if trivially constant.
11281       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11282         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11283         Inst->replaceAllUsesWith(C);
11284         ++NumConstProp;
11285         Inst->eraseFromParent();
11286         continue;
11287       }
11288      
11289       IC.AddToWorkList(Inst);
11290     }
11291
11292     // Recursively visit successors.  If this is a branch or switch on a
11293     // constant, only visit the reachable successor.
11294     TerminatorInst *TI = BB->getTerminator();
11295     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11296       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11297         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11298         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11299         Worklist.push_back(ReachableBB);
11300         continue;
11301       }
11302     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11303       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11304         // See if this is an explicit destination.
11305         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11306           if (SI->getCaseValue(i) == Cond) {
11307             BasicBlock *ReachableBB = SI->getSuccessor(i);
11308             Worklist.push_back(ReachableBB);
11309             continue;
11310           }
11311         
11312         // Otherwise it is the default destination.
11313         Worklist.push_back(SI->getSuccessor(0));
11314         continue;
11315       }
11316     }
11317     
11318     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11319       Worklist.push_back(TI->getSuccessor(i));
11320   }
11321 }
11322
11323 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11324   bool Changed = false;
11325   TD = &getAnalysis<TargetData>();
11326   
11327   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11328              << F.getNameStr() << "\n");
11329
11330   {
11331     // Do a depth-first traversal of the function, populate the worklist with
11332     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11333     // track of which blocks we visit.
11334     SmallPtrSet<BasicBlock*, 64> Visited;
11335     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11336
11337     // Do a quick scan over the function.  If we find any blocks that are
11338     // unreachable, remove any instructions inside of them.  This prevents
11339     // the instcombine code from having to deal with some bad special cases.
11340     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11341       if (!Visited.count(BB)) {
11342         Instruction *Term = BB->getTerminator();
11343         while (Term != BB->begin()) {   // Remove instrs bottom-up
11344           BasicBlock::iterator I = Term; --I;
11345
11346           DOUT << "IC: DCE: " << *I;
11347           ++NumDeadInst;
11348
11349           if (!I->use_empty())
11350             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11351           I->eraseFromParent();
11352         }
11353       }
11354   }
11355
11356   while (!Worklist.empty()) {
11357     Instruction *I = RemoveOneFromWorkList();
11358     if (I == 0) continue;  // skip null values.
11359
11360     // Check to see if we can DCE the instruction.
11361     if (isInstructionTriviallyDead(I)) {
11362       // Add operands to the worklist.
11363       if (I->getNumOperands() < 4)
11364         AddUsesToWorkList(*I);
11365       ++NumDeadInst;
11366
11367       DOUT << "IC: DCE: " << *I;
11368
11369       I->eraseFromParent();
11370       RemoveFromWorkList(I);
11371       continue;
11372     }
11373
11374     // Instruction isn't dead, see if we can constant propagate it.
11375     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11376       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11377
11378       // Add operands to the worklist.
11379       AddUsesToWorkList(*I);
11380       ReplaceInstUsesWith(*I, C);
11381
11382       ++NumConstProp;
11383       I->eraseFromParent();
11384       RemoveFromWorkList(I);
11385       continue;
11386     }
11387
11388     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11389       // See if we can constant fold its operands.
11390       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11391         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11392           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11393             i->set(NewC);
11394         }
11395       }
11396     }
11397
11398     // See if we can trivially sink this instruction to a successor basic block.
11399     // FIXME: Remove GetResultInst test when first class support for aggregates
11400     // is implemented.
11401     if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11402       BasicBlock *BB = I->getParent();
11403       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11404       if (UserParent != BB) {
11405         bool UserIsSuccessor = false;
11406         // See if the user is one of our successors.
11407         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11408           if (*SI == UserParent) {
11409             UserIsSuccessor = true;
11410             break;
11411           }
11412
11413         // If the user is one of our immediate successors, and if that successor
11414         // only has us as a predecessors (we'd have to split the critical edge
11415         // otherwise), we can keep going.
11416         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11417             next(pred_begin(UserParent)) == pred_end(UserParent))
11418           // Okay, the CFG is simple enough, try to sink this instruction.
11419           Changed |= TryToSinkInstruction(I, UserParent);
11420       }
11421     }
11422
11423     // Now that we have an instruction, try combining it to simplify it...
11424 #ifndef NDEBUG
11425     std::string OrigI;
11426 #endif
11427     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11428     if (Instruction *Result = visit(*I)) {
11429       ++NumCombined;
11430       // Should we replace the old instruction with a new one?
11431       if (Result != I) {
11432         DOUT << "IC: Old = " << *I
11433              << "    New = " << *Result;
11434
11435         // Everything uses the new instruction now.
11436         I->replaceAllUsesWith(Result);
11437
11438         // Push the new instruction and any users onto the worklist.
11439         AddToWorkList(Result);
11440         AddUsersToWorkList(*Result);
11441
11442         // Move the name to the new instruction first.
11443         Result->takeName(I);
11444
11445         // Insert the new instruction into the basic block...
11446         BasicBlock *InstParent = I->getParent();
11447         BasicBlock::iterator InsertPos = I;
11448
11449         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11450           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11451             ++InsertPos;
11452
11453         InstParent->getInstList().insert(InsertPos, Result);
11454
11455         // Make sure that we reprocess all operands now that we reduced their
11456         // use counts.
11457         AddUsesToWorkList(*I);
11458
11459         // Instructions can end up on the worklist more than once.  Make sure
11460         // we do not process an instruction that has been deleted.
11461         RemoveFromWorkList(I);
11462
11463         // Erase the old instruction.
11464         InstParent->getInstList().erase(I);
11465       } else {
11466 #ifndef NDEBUG
11467         DOUT << "IC: Mod = " << OrigI
11468              << "    New = " << *I;
11469 #endif
11470
11471         // If the instruction was modified, it's possible that it is now dead.
11472         // if so, remove it.
11473         if (isInstructionTriviallyDead(I)) {
11474           // Make sure we process all operands now that we are reducing their
11475           // use counts.
11476           AddUsesToWorkList(*I);
11477
11478           // Instructions may end up in the worklist more than once.  Erase all
11479           // occurrences of this instruction.
11480           RemoveFromWorkList(I);
11481           I->eraseFromParent();
11482         } else {
11483           AddToWorkList(I);
11484           AddUsersToWorkList(*I);
11485         }
11486       }
11487       Changed = true;
11488     }
11489   }
11490
11491   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11492     
11493   // Do an explicit clear, this shrinks the map if needed.
11494   WorklistMap.clear();
11495   return Changed;
11496 }
11497
11498
11499 bool InstCombiner::runOnFunction(Function &F) {
11500   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11501   
11502   bool EverMadeChange = false;
11503
11504   // Iterate while there is work to do.
11505   unsigned Iteration = 0;
11506   while (DoOneIteration(F, Iteration++))
11507     EverMadeChange = true;
11508   return EverMadeChange;
11509 }
11510
11511 FunctionPass *llvm::createInstructionCombiningPass() {
11512   return new InstCombiner();
11513 }
11514