Constant integer vectors may also be negated.
[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/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/ConstantRange.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/GetElementPtrTypeIterator.h"
50 #include "llvm/Support/InstVisitor.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/PatternMatch.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/ADT/DenseMap.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/ADT/STLExtras.h"
59 #include <algorithm>
60 #include <climits>
61 #include <sstream>
62 using namespace llvm;
63 using namespace llvm::PatternMatch;
64
65 STATISTIC(NumCombined , "Number of insts combined");
66 STATISTIC(NumConstProp, "Number of constant folds");
67 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69 STATISTIC(NumSunkInst , "Number of instructions sunk");
70
71 namespace {
72   class VISIBILITY_HIDDEN InstCombiner
73     : public FunctionPass,
74       public InstVisitor<InstCombiner, Instruction*> {
75     // Worklist of all of the instructions that need to be simplified.
76     std::vector<Instruction*> Worklist;
77     DenseMap<Instruction*, unsigned> WorklistMap;
78     TargetData *TD;
79     bool MustPreserveLCSSA;
80   public:
81     static char ID; // Pass identification, replacement for typeid
82     InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
84     /// AddToWorkList - Add the specified instruction to the worklist if it
85     /// isn't already in it.
86     void AddToWorkList(Instruction *I) {
87       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88         Worklist.push_back(I);
89     }
90     
91     // RemoveFromWorkList - remove I from the worklist if it exists.
92     void RemoveFromWorkList(Instruction *I) {
93       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94       if (It == WorklistMap.end()) return; // Not in worklist.
95       
96       // Don't bother moving everything down, just null out the slot.
97       Worklist[It->second] = 0;
98       
99       WorklistMap.erase(It);
100     }
101     
102     Instruction *RemoveOneFromWorkList() {
103       Instruction *I = Worklist.back();
104       Worklist.pop_back();
105       WorklistMap.erase(I);
106       return I;
107     }
108
109     
110     /// AddUsersToWorkList - When an instruction is simplified, add all users of
111     /// the instruction to the work lists because they might get more simplified
112     /// now.
113     ///
114     void AddUsersToWorkList(Value &I) {
115       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
116            UI != UE; ++UI)
117         AddToWorkList(cast<Instruction>(*UI));
118     }
119
120     /// AddUsesToWorkList - When an instruction is simplified, add operands to
121     /// the work lists because they might get more simplified now.
122     ///
123     void AddUsesToWorkList(Instruction &I) {
124       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
126           AddToWorkList(Op);
127     }
128     
129     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130     /// dead.  Add all of its operands to the worklist, turning them into
131     /// undef's to reduce the number of uses of those instructions.
132     ///
133     /// Return the specified operand before it is turned into an undef.
134     ///
135     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136       Value *R = I.getOperand(op);
137       
138       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
140           AddToWorkList(Op);
141           // Set the operand to undef to drop the use.
142           I.setOperand(i, UndefValue::get(Op->getType()));
143         }
144       
145       return R;
146     }
147
148   public:
149     virtual bool runOnFunction(Function &F);
150     
151     bool DoOneIteration(Function &F, unsigned ItNum);
152
153     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154       AU.addRequired<TargetData>();
155       AU.addPreservedID(LCSSAID);
156       AU.setPreservesCFG();
157     }
158
159     TargetData &getTargetData() const { return *TD; }
160
161     // Visitation implementation - Implement instruction combining for different
162     // instruction types.  The semantics are as follows:
163     // Return Value:
164     //    null        - No change was made
165     //     I          - Change was made, I is still valid, I may be dead though
166     //   otherwise    - Change was made, replace I with returned instruction
167     //
168     Instruction *visitAdd(BinaryOperator &I);
169     Instruction *visitSub(BinaryOperator &I);
170     Instruction *visitMul(BinaryOperator &I);
171     Instruction *visitURem(BinaryOperator &I);
172     Instruction *visitSRem(BinaryOperator &I);
173     Instruction *visitFRem(BinaryOperator &I);
174     Instruction *commonRemTransforms(BinaryOperator &I);
175     Instruction *commonIRemTransforms(BinaryOperator &I);
176     Instruction *commonDivTransforms(BinaryOperator &I);
177     Instruction *commonIDivTransforms(BinaryOperator &I);
178     Instruction *visitUDiv(BinaryOperator &I);
179     Instruction *visitSDiv(BinaryOperator &I);
180     Instruction *visitFDiv(BinaryOperator &I);
181     Instruction *visitAnd(BinaryOperator &I);
182     Instruction *visitOr (BinaryOperator &I);
183     Instruction *visitXor(BinaryOperator &I);
184     Instruction *visitShl(BinaryOperator &I);
185     Instruction *visitAShr(BinaryOperator &I);
186     Instruction *visitLShr(BinaryOperator &I);
187     Instruction *commonShiftTransforms(BinaryOperator &I);
188     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
189                                       Constant *RHSC);
190     Instruction *visitFCmpInst(FCmpInst &I);
191     Instruction *visitICmpInst(ICmpInst &I);
192     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
193     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
194                                                 Instruction *LHS,
195                                                 ConstantInt *RHS);
196     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
197                                 ConstantInt *DivRHS);
198
199     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
200                              ICmpInst::Predicate Cond, Instruction &I);
201     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
202                                      BinaryOperator &I);
203     Instruction *commonCastTransforms(CastInst &CI);
204     Instruction *commonIntCastTransforms(CastInst &CI);
205     Instruction *commonPointerCastTransforms(CastInst &CI);
206     Instruction *visitTrunc(TruncInst &CI);
207     Instruction *visitZExt(ZExtInst &CI);
208     Instruction *visitSExt(SExtInst &CI);
209     Instruction *visitFPTrunc(FPTruncInst &CI);
210     Instruction *visitFPExt(CastInst &CI);
211     Instruction *visitFPToUI(FPToUIInst &FI);
212     Instruction *visitFPToSI(FPToSIInst &FI);
213     Instruction *visitUIToFP(CastInst &CI);
214     Instruction *visitSIToFP(CastInst &CI);
215     Instruction *visitPtrToInt(CastInst &CI);
216     Instruction *visitIntToPtr(IntToPtrInst &CI);
217     Instruction *visitBitCast(BitCastInst &CI);
218     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
219                                 Instruction *FI);
220     Instruction *visitSelectInst(SelectInst &CI);
221     Instruction *visitCallInst(CallInst &CI);
222     Instruction *visitInvokeInst(InvokeInst &II);
223     Instruction *visitPHINode(PHINode &PN);
224     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
225     Instruction *visitAllocationInst(AllocationInst &AI);
226     Instruction *visitFreeInst(FreeInst &FI);
227     Instruction *visitLoadInst(LoadInst &LI);
228     Instruction *visitStoreInst(StoreInst &SI);
229     Instruction *visitBranchInst(BranchInst &BI);
230     Instruction *visitSwitchInst(SwitchInst &SI);
231     Instruction *visitInsertElementInst(InsertElementInst &IE);
232     Instruction *visitExtractElementInst(ExtractElementInst &EI);
233     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
234
235     // visitInstruction - Specify what to return for unhandled instructions...
236     Instruction *visitInstruction(Instruction &I) { return 0; }
237
238   private:
239     Instruction *visitCallSite(CallSite CS);
240     bool transformConstExprCastCall(CallSite CS);
241     Instruction *transformCallThroughTrampoline(CallSite CS);
242     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
243                                    bool DoXform = true);
244     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
245
246   public:
247     // InsertNewInstBefore - insert an instruction New before instruction Old
248     // in the program.  Add the new instruction to the worklist.
249     //
250     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
251       assert(New && New->getParent() == 0 &&
252              "New instruction already inserted into a basic block!");
253       BasicBlock *BB = Old.getParent();
254       BB->getInstList().insert(&Old, New);  // Insert inst
255       AddToWorkList(New);
256       return New;
257     }
258
259     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
260     /// This also adds the cast to the worklist.  Finally, this returns the
261     /// cast.
262     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
263                             Instruction &Pos) {
264       if (V->getType() == Ty) return V;
265
266       if (Constant *CV = dyn_cast<Constant>(V))
267         return ConstantExpr::getCast(opc, CV, Ty);
268       
269       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
270       AddToWorkList(C);
271       return C;
272     }
273         
274     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
275       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
276     }
277
278
279     // ReplaceInstUsesWith - This method is to be used when an instruction is
280     // found to be dead, replacable with another preexisting expression.  Here
281     // we add all uses of I to the worklist, replace all uses of I with the new
282     // value, then return I, so that the inst combiner will know that I was
283     // modified.
284     //
285     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
286       AddUsersToWorkList(I);         // Add all modified instrs to worklist
287       if (&I != V) {
288         I.replaceAllUsesWith(V);
289         return &I;
290       } else {
291         // If we are replacing the instruction with itself, this must be in a
292         // segment of unreachable code, so just clobber the instruction.
293         I.replaceAllUsesWith(UndefValue::get(I.getType()));
294         return &I;
295       }
296     }
297
298     // UpdateValueUsesWith - This method is to be used when an value is
299     // found to be replacable with another preexisting expression or was
300     // updated.  Here we add all uses of I to the worklist, replace all uses of
301     // I with the new value (unless the instruction was just updated), then
302     // return true, so that the inst combiner will know that I was modified.
303     //
304     bool UpdateValueUsesWith(Value *Old, Value *New) {
305       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
306       if (Old != New)
307         Old->replaceAllUsesWith(New);
308       if (Instruction *I = dyn_cast<Instruction>(Old))
309         AddToWorkList(I);
310       if (Instruction *I = dyn_cast<Instruction>(New))
311         AddToWorkList(I);
312       return true;
313     }
314     
315     // EraseInstFromFunction - When dealing with an instruction that has side
316     // effects or produces a void value, we can't rely on DCE to delete the
317     // instruction.  Instead, visit methods should return the value returned by
318     // this function.
319     Instruction *EraseInstFromFunction(Instruction &I) {
320       assert(I.use_empty() && "Cannot erase instruction that is used!");
321       AddUsesToWorkList(I);
322       RemoveFromWorkList(&I);
323       I.eraseFromParent();
324       return 0;  // Don't do anything with FI
325     }
326
327   private:
328     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
329     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
330     /// casts that are known to not do anything...
331     ///
332     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
333                                    Value *V, const Type *DestTy,
334                                    Instruction *InsertBefore);
335
336     /// SimplifyCommutative - This performs a few simplifications for 
337     /// commutative operators.
338     bool SimplifyCommutative(BinaryOperator &I);
339
340     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341     /// most-complex to least-complex order.
342     bool SimplifyCompare(CmpInst &I);
343
344     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
345     /// on the demanded bits.
346     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
347                               APInt& KnownZero, APInt& KnownOne,
348                               unsigned Depth = 0);
349
350     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
351                                       uint64_t &UndefElts, unsigned Depth = 0);
352       
353     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
354     // PHI node as operand #0, see if we can fold the instruction into the PHI
355     // (which is only possible if all operands to the PHI are constants).
356     Instruction *FoldOpIntoPhi(Instruction &I);
357
358     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
359     // operator and they all are only used by the PHI, PHI together their
360     // inputs, and do the operation once, to the result of the PHI.
361     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
362     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
363     
364     
365     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
366                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
367     
368     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
369                               bool isSub, Instruction &I);
370     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
371                                  bool isSigned, bool Inside, Instruction &IB);
372     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
373     Instruction *MatchBSwap(BinaryOperator &I);
374     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
375     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
376     Instruction *SimplifyMemSet(MemSetInst *MI);
377
378
379     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
380
381     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
382                            APInt& KnownOne, unsigned Depth = 0) const;
383     bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
384     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const;
385     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
386                                     unsigned CastOpc,
387                                     int &NumCastsRemoved);
388     unsigned GetOrEnforceKnownAlignment(Value *V,
389                                         unsigned PrefAlign = 0);
390   };
391 }
392
393 char InstCombiner::ID = 0;
394 static RegisterPass<InstCombiner>
395 X("instcombine", "Combine redundant instructions");
396
397 // getComplexity:  Assign a complexity or rank value to LLVM Values...
398 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
399 static unsigned getComplexity(Value *V) {
400   if (isa<Instruction>(V)) {
401     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
402       return 3;
403     return 4;
404   }
405   if (isa<Argument>(V)) return 3;
406   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
407 }
408
409 // isOnlyUse - Return true if this instruction will be deleted if we stop using
410 // it.
411 static bool isOnlyUse(Value *V) {
412   return V->hasOneUse() || isa<Constant>(V);
413 }
414
415 // getPromotedType - Return the specified type promoted as it would be to pass
416 // though a va_arg area...
417 static const Type *getPromotedType(const Type *Ty) {
418   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
419     if (ITy->getBitWidth() < 32)
420       return Type::Int32Ty;
421   }
422   return Ty;
423 }
424
425 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
426 /// expression bitcast,  return the operand value, otherwise return null.
427 static Value *getBitCastOperand(Value *V) {
428   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
429     return I->getOperand(0);
430   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
431     if (CE->getOpcode() == Instruction::BitCast)
432       return CE->getOperand(0);
433   return 0;
434 }
435
436 /// This function is a wrapper around CastInst::isEliminableCastPair. It
437 /// simply extracts arguments and returns what that function returns.
438 static Instruction::CastOps 
439 isEliminableCastPair(
440   const CastInst *CI, ///< The first cast instruction
441   unsigned opcode,       ///< The opcode of the second cast instruction
442   const Type *DstTy,     ///< The target type for the second cast instruction
443   TargetData *TD         ///< The target data for pointer size
444 ) {
445   
446   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
447   const Type *MidTy = CI->getType();                  // B from above
448
449   // Get the opcodes of the two Cast instructions
450   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
451   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
452
453   return Instruction::CastOps(
454       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
455                                      DstTy, TD->getIntPtrType()));
456 }
457
458 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
459 /// in any code being generated.  It does not require codegen if V is simple
460 /// enough or if the cast can be folded into other casts.
461 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
462                               const Type *Ty, TargetData *TD) {
463   if (V->getType() == Ty || isa<Constant>(V)) return false;
464   
465   // If this is another cast that can be eliminated, it isn't codegen either.
466   if (const CastInst *CI = dyn_cast<CastInst>(V))
467     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
468       return false;
469   return true;
470 }
471
472 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
473 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
474 /// casts that are known to not do anything...
475 ///
476 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
477                                              Value *V, const Type *DestTy,
478                                              Instruction *InsertBefore) {
479   if (V->getType() == DestTy) return V;
480   if (Constant *C = dyn_cast<Constant>(V))
481     return ConstantExpr::getCast(opcode, C, DestTy);
482   
483   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
484 }
485
486 // SimplifyCommutative - This performs a few simplifications for commutative
487 // operators:
488 //
489 //  1. Order operands such that they are listed from right (least complex) to
490 //     left (most complex).  This puts constants before unary operators before
491 //     binary operators.
492 //
493 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
494 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
495 //
496 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
497   bool Changed = false;
498   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
499     Changed = !I.swapOperands();
500
501   if (!I.isAssociative()) return Changed;
502   Instruction::BinaryOps Opcode = I.getOpcode();
503   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
504     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
505       if (isa<Constant>(I.getOperand(1))) {
506         Constant *Folded = ConstantExpr::get(I.getOpcode(),
507                                              cast<Constant>(I.getOperand(1)),
508                                              cast<Constant>(Op->getOperand(1)));
509         I.setOperand(0, Op->getOperand(0));
510         I.setOperand(1, Folded);
511         return true;
512       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
513         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
514             isOnlyUse(Op) && isOnlyUse(Op1)) {
515           Constant *C1 = cast<Constant>(Op->getOperand(1));
516           Constant *C2 = cast<Constant>(Op1->getOperand(1));
517
518           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
519           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
520           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
521                                                     Op1->getOperand(0),
522                                                     Op1->getName(), &I);
523           AddToWorkList(New);
524           I.setOperand(0, New);
525           I.setOperand(1, Folded);
526           return true;
527         }
528     }
529   return Changed;
530 }
531
532 /// SimplifyCompare - For a CmpInst this function just orders the operands
533 /// so that theyare listed from right (least complex) to left (most complex).
534 /// This puts constants before unary operators before binary operators.
535 bool InstCombiner::SimplifyCompare(CmpInst &I) {
536   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
537     return false;
538   I.swapOperands();
539   // Compare instructions are not associative so there's nothing else we can do.
540   return true;
541 }
542
543 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
544 // if the LHS is a constant zero (which is the 'negate' form).
545 //
546 static inline Value *dyn_castNegVal(Value *V) {
547   if (BinaryOperator::isNeg(V))
548     return BinaryOperator::getNegArgument(V);
549
550   // Constants can be considered to be negated values if they can be folded.
551   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
552     return ConstantExpr::getNeg(C);
553
554   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
555     if (C->getType()->getElementType()->isInteger())
556       return ConstantExpr::getNeg(C);
557
558   return 0;
559 }
560
561 static inline Value *dyn_castNotVal(Value *V) {
562   if (BinaryOperator::isNot(V))
563     return BinaryOperator::getNotArgument(V);
564
565   // Constants can be considered to be not'ed values...
566   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
567     return ConstantInt::get(~C->getValue());
568   return 0;
569 }
570
571 // dyn_castFoldableMul - If this value is a multiply that can be folded into
572 // other computations (because it has a constant operand), return the
573 // non-constant operand of the multiply, and set CST to point to the multiplier.
574 // Otherwise, return null.
575 //
576 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
577   if (V->hasOneUse() && V->getType()->isInteger())
578     if (Instruction *I = dyn_cast<Instruction>(V)) {
579       if (I->getOpcode() == Instruction::Mul)
580         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
581           return I->getOperand(0);
582       if (I->getOpcode() == Instruction::Shl)
583         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
584           // The multiplier is really 1 << CST.
585           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
586           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
587           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
588           return I->getOperand(0);
589         }
590     }
591   return 0;
592 }
593
594 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
595 /// expression, return it.
596 static User *dyn_castGetElementPtr(Value *V) {
597   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
598   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
599     if (CE->getOpcode() == Instruction::GetElementPtr)
600       return cast<User>(V);
601   return false;
602 }
603
604 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
605 /// opcode value. Otherwise return UserOp1.
606 static unsigned getOpcode(Value *V) {
607   if (Instruction *I = dyn_cast<Instruction>(V))
608     return I->getOpcode();
609   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
610     return CE->getOpcode();
611   // Use UserOp1 to mean there's no opcode.
612   return Instruction::UserOp1;
613 }
614
615 /// AddOne - Add one to a ConstantInt
616 static ConstantInt *AddOne(ConstantInt *C) {
617   APInt Val(C->getValue());
618   return ConstantInt::get(++Val);
619 }
620 /// SubOne - Subtract one from a ConstantInt
621 static ConstantInt *SubOne(ConstantInt *C) {
622   APInt Val(C->getValue());
623   return ConstantInt::get(--Val);
624 }
625 /// Add - Add two ConstantInts together
626 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
627   return ConstantInt::get(C1->getValue() + C2->getValue());
628 }
629 /// And - Bitwise AND two ConstantInts together
630 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
631   return ConstantInt::get(C1->getValue() & C2->getValue());
632 }
633 /// Subtract - Subtract one ConstantInt from another
634 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
635   return ConstantInt::get(C1->getValue() - C2->getValue());
636 }
637 /// Multiply - Multiply two ConstantInts together
638 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
639   return ConstantInt::get(C1->getValue() * C2->getValue());
640 }
641 /// MultiplyOverflows - True if the multiply can not be expressed in an int
642 /// this size.
643 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
644   uint32_t W = C1->getBitWidth();
645   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646   if (sign) {
647     LHSExt.sext(W * 2);
648     RHSExt.sext(W * 2);
649   } else {
650     LHSExt.zext(W * 2);
651     RHSExt.zext(W * 2);
652   }
653
654   APInt MulExt = LHSExt * RHSExt;
655
656   if (sign) {
657     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659     return MulExt.slt(Min) || MulExt.sgt(Max);
660   } else 
661     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662 }
663
664 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
665 /// known to be either zero or one and return them in the KnownZero/KnownOne
666 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
667 /// processing.
668 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
669 /// we cannot optimize based on the assumption that it is zero without changing
670 /// it to be an explicit zero.  If we don't change it to zero, other code could
671 /// optimized based on the contradictory assumption that it is non-zero.
672 /// Because instcombine aggressively folds operations with undef args anyway,
673 /// this won't lose us code quality.
674 void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
675                                      APInt& KnownZero, APInt& KnownOne,
676                                      unsigned Depth) const {
677   assert(V && "No Value?");
678   assert(Depth <= 6 && "Limit Search Depth");
679   uint32_t BitWidth = Mask.getBitWidth();
680   assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
681          "Not integer or pointer type!");
682   assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
683          (!isa<IntegerType>(V->getType()) ||
684           V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
685          KnownZero.getBitWidth() == BitWidth && 
686          KnownOne.getBitWidth() == BitWidth &&
687          "V, Mask, KnownOne and KnownZero should have same BitWidth");
688
689   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
690     // We know all of the bits for a constant!
691     KnownOne = CI->getValue() & Mask;
692     KnownZero = ~KnownOne & Mask;
693     return;
694   }
695   // Null is all-zeros.
696   if (isa<ConstantPointerNull>(V)) {
697     KnownOne.clear();
698     KnownZero = Mask;
699     return;
700   }
701   // The address of an aligned GlobalValue has trailing zeros.
702   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
703     unsigned Align = GV->getAlignment();
704     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
705       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
706     if (Align > 0)
707       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
708                                               CountTrailingZeros_32(Align));
709     else
710       KnownZero.clear();
711     KnownOne.clear();
712     return;
713   }
714
715   KnownZero.clear(); KnownOne.clear();   // Start out not knowing anything.
716
717   if (Depth == 6 || Mask == 0)
718     return;  // Limit search depth.
719
720   User *I = dyn_cast<User>(V);
721   if (!I) return;
722
723   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
724   switch (getOpcode(I)) {
725   default: break;
726   case Instruction::And: {
727     // If either the LHS or the RHS are Zero, the result is zero.
728     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
729     APInt Mask2(Mask & ~KnownZero);
730     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
731     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
732     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
733     
734     // Output known-1 bits are only known if set in both the LHS & RHS.
735     KnownOne &= KnownOne2;
736     // Output known-0 are known to be clear if zero in either the LHS | RHS.
737     KnownZero |= KnownZero2;
738     return;
739   }
740   case Instruction::Or: {
741     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
742     APInt Mask2(Mask & ~KnownOne);
743     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
744     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
745     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
746     
747     // Output known-0 bits are only known if clear in both the LHS & RHS.
748     KnownZero &= KnownZero2;
749     // Output known-1 are known to be set if set in either the LHS | RHS.
750     KnownOne |= KnownOne2;
751     return;
752   }
753   case Instruction::Xor: {
754     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
755     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
756     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
757     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
758     
759     // Output known-0 bits are known if clear or set in both the LHS & RHS.
760     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
761     // Output known-1 are known to be set if set in only one of the LHS, RHS.
762     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
763     KnownZero = KnownZeroOut;
764     return;
765   }
766   case Instruction::Mul: {
767     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
768     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
769     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
770     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
771     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
772     
773     // If low bits are zero in either operand, output low known-0 bits.
774     // Also compute a conserative estimate for high known-0 bits.
775     // More trickiness is possible, but this is sufficient for the
776     // interesting case of alignment computation.
777     KnownOne.clear();
778     unsigned TrailZ = KnownZero.countTrailingOnes() +
779                       KnownZero2.countTrailingOnes();
780     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
781                                KnownZero2.countLeadingOnes(),
782                                BitWidth) - BitWidth;
783
784     TrailZ = std::min(TrailZ, BitWidth);
785     LeadZ = std::min(LeadZ, BitWidth);
786     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
787                 APInt::getHighBitsSet(BitWidth, LeadZ);
788     KnownZero &= Mask;
789     return;
790   }
791   case Instruction::UDiv: {
792     // For the purposes of computing leading zeros we can conservatively
793     // treat a udiv as a logical right shift by the power of 2 known to
794     // be less than the denominator.
795     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
796     ComputeMaskedBits(I->getOperand(0),
797                       AllOnes, KnownZero2, KnownOne2, Depth+1);
798     unsigned LeadZ = KnownZero2.countLeadingOnes();
799
800     KnownOne2.clear();
801     KnownZero2.clear();
802     ComputeMaskedBits(I->getOperand(1),
803                       AllOnes, KnownZero2, KnownOne2, Depth+1);
804     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
805     if (RHSUnknownLeadingOnes != BitWidth)
806       LeadZ = std::min(BitWidth,
807                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
808
809     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
810     return;
811   }
812   case Instruction::Select:
813     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
814     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
815     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
816     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
817
818     // Only known if known in both the LHS and RHS.
819     KnownOne &= KnownOne2;
820     KnownZero &= KnownZero2;
821     return;
822   case Instruction::FPTrunc:
823   case Instruction::FPExt:
824   case Instruction::FPToUI:
825   case Instruction::FPToSI:
826   case Instruction::SIToFP:
827   case Instruction::UIToFP:
828     return; // Can't work with floating point.
829   case Instruction::PtrToInt:
830   case Instruction::IntToPtr:
831     // We can't handle these if we don't know the pointer size.
832     if (!TD) return;
833     // FALL THROUGH and handle them the same as zext/trunc.
834   case Instruction::ZExt:
835   case Instruction::Trunc: {
836     // Note that we handle pointer operands here because of inttoptr/ptrtoint
837     // which fall through here.
838     const Type *SrcTy = I->getOperand(0)->getType();
839     uint32_t SrcBitWidth = TD ?
840       TD->getTypeSizeInBits(SrcTy) :
841       SrcTy->getPrimitiveSizeInBits();
842     APInt MaskIn(Mask);
843     MaskIn.zextOrTrunc(SrcBitWidth);
844     KnownZero.zextOrTrunc(SrcBitWidth);
845     KnownOne.zextOrTrunc(SrcBitWidth);
846     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
847     KnownZero.zextOrTrunc(BitWidth);
848     KnownOne.zextOrTrunc(BitWidth);
849     // Any top bits are known to be zero.
850     if (BitWidth > SrcBitWidth)
851       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
852     return;
853   }
854   case Instruction::BitCast: {
855     const Type *SrcTy = I->getOperand(0)->getType();
856     if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
857       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
858       return;
859     }
860     break;
861   }
862   case Instruction::SExt: {
863     // Compute the bits in the result that are not present in the input.
864     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
865     uint32_t SrcBitWidth = SrcTy->getBitWidth();
866       
867     APInt MaskIn(Mask); 
868     MaskIn.trunc(SrcBitWidth);
869     KnownZero.trunc(SrcBitWidth);
870     KnownOne.trunc(SrcBitWidth);
871     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
872     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
873     KnownZero.zext(BitWidth);
874     KnownOne.zext(BitWidth);
875
876     // If the sign bit of the input is known set or clear, then we know the
877     // top bits of the result.
878     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
879       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
880     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
881       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
882     return;
883   }
884   case Instruction::Shl:
885     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
886     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
887       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
888       APInt Mask2(Mask.lshr(ShiftAmt));
889       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
890       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
891       KnownZero <<= ShiftAmt;
892       KnownOne  <<= ShiftAmt;
893       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
894       return;
895     }
896     break;
897   case Instruction::LShr:
898     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
899     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
900       // Compute the new bits that are at the top now.
901       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
902       
903       // Unsigned shift right.
904       APInt Mask2(Mask.shl(ShiftAmt));
905       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
906       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
907       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
908       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
909       // high bits known zero.
910       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
911       return;
912     }
913     break;
914   case Instruction::AShr:
915     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
916     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
917       // Compute the new bits that are at the top now.
918       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
919       
920       // Signed shift right.
921       APInt Mask2(Mask.shl(ShiftAmt));
922       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
923       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
924       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
925       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
926         
927       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
928       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
929         KnownZero |= HighBits;
930       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
931         KnownOne |= HighBits;
932       return;
933     }
934     break;
935   case Instruction::Sub: {
936     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
937       // We know that the top bits of C-X are clear if X contains less bits
938       // than C (i.e. no wrap-around can happen).  For example, 20-X is
939       // positive if we can prove that X is >= 0 and < 16.
940       if (!CLHS->getValue().isNegative()) {
941         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
942         // NLZ can't be BitWidth with no sign bit
943         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
944         ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
945                           Depth+1);
946     
947         // If all of the MaskV bits are known to be zero, then we know the
948         // output top bits are zero, because we now know that the output is
949         // from [0-C].
950         if ((KnownZero2 & MaskV) == MaskV) {
951           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
952           // Top bits known zero.
953           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
954         }
955       }        
956     }
957   }
958   // fall through
959   case Instruction::Add: {
960     // Output known-0 bits are known if clear or set in both the low clear bits
961     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
962     // low 3 bits clear.
963     APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
964     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
965     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
966     unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
967
968     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
969     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
970     KnownZeroOut = std::min(KnownZeroOut, 
971                             KnownZero2.countTrailingOnes());
972
973     KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
974     return;
975   }
976   case Instruction::SRem:
977     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
978       APInt RA = Rem->getValue();
979       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
980         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
981         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
982         ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
983
984         // The sign of a remainder is equal to the sign of the first
985         // operand (zero being positive).
986         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
987           KnownZero2 |= ~LowBits;
988         else if (KnownOne2[BitWidth-1])
989           KnownOne2 |= ~LowBits;
990
991         KnownZero |= KnownZero2 & Mask;
992         KnownOne |= KnownOne2 & Mask;
993
994         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
995       }
996     }
997     break;
998   case Instruction::URem: {
999     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1000       APInt RA = Rem->getValue();
1001       if (RA.isPowerOf2()) {
1002         APInt LowBits = (RA - 1);
1003         APInt Mask2 = LowBits & Mask;
1004         KnownZero |= ~LowBits & Mask;
1005         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1006         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1007         break;
1008       }
1009     }
1010
1011     // Since the result is less than or equal to either operand, any leading
1012     // zero bits in either operand must also exist in the result.
1013     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1014     ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1015                       Depth+1);
1016     ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1017                       Depth+1);
1018
1019     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1020                                 KnownZero2.countLeadingOnes());
1021     KnownOne.clear();
1022     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1023     break;
1024   }
1025
1026   case Instruction::Alloca:
1027   case Instruction::Malloc: {
1028     AllocationInst *AI = cast<AllocationInst>(V);
1029     unsigned Align = AI->getAlignment();
1030     if (Align == 0 && TD) {
1031       if (isa<AllocaInst>(AI))
1032         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1033       else if (isa<MallocInst>(AI)) {
1034         // Malloc returns maximally aligned memory.
1035         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1036         Align =
1037           std::max(Align,
1038                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1039         Align =
1040           std::max(Align,
1041                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1042       }
1043     }
1044     
1045     if (Align > 0)
1046       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1047                                               CountTrailingZeros_32(Align));
1048     break;
1049   }
1050   case Instruction::GetElementPtr: {
1051     // Analyze all of the subscripts of this getelementptr instruction
1052     // to determine if we can prove known low zero bits.
1053     APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1054     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1055     ComputeMaskedBits(I->getOperand(0), LocalMask,
1056                       LocalKnownZero, LocalKnownOne, Depth+1);
1057     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1058
1059     gep_type_iterator GTI = gep_type_begin(I);
1060     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1061       Value *Index = I->getOperand(i);
1062       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1063         // Handle struct member offset arithmetic.
1064         if (!TD) return;
1065         const StructLayout *SL = TD->getStructLayout(STy);
1066         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1067         uint64_t Offset = SL->getElementOffset(Idx);
1068         TrailZ = std::min(TrailZ,
1069                           CountTrailingZeros_64(Offset));
1070       } else {
1071         // Handle array index arithmetic.
1072         const Type *IndexedTy = GTI.getIndexedType();
1073         if (!IndexedTy->isSized()) return;
1074         unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1075         uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1076         LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1077         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1078         ComputeMaskedBits(Index, LocalMask,
1079                           LocalKnownZero, LocalKnownOne, Depth+1);
1080         TrailZ = std::min(TrailZ,
1081                           CountTrailingZeros_64(TypeSize) +
1082                             LocalKnownZero.countTrailingOnes());
1083       }
1084     }
1085     
1086     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1087     break;
1088   }
1089   case Instruction::PHI: {
1090     PHINode *P = cast<PHINode>(I);
1091     // Handle the case of a simple two-predecessor recurrence PHI.
1092     // There's a lot more that could theoretically be done here, but
1093     // this is sufficient to catch some interesting cases.
1094     if (P->getNumIncomingValues() == 2) {
1095       for (unsigned i = 0; i != 2; ++i) {
1096         Value *L = P->getIncomingValue(i);
1097         Value *R = P->getIncomingValue(!i);
1098         User *LU = dyn_cast<User>(L);
1099         unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1100         // Check for operations that have the property that if
1101         // both their operands have low zero bits, the result
1102         // will have low zero bits.
1103         if (Opcode == Instruction::Add ||
1104             Opcode == Instruction::Sub ||
1105             Opcode == Instruction::And ||
1106             Opcode == Instruction::Or ||
1107             Opcode == Instruction::Mul) {
1108           Value *LL = LU->getOperand(0);
1109           Value *LR = LU->getOperand(1);
1110           // Find a recurrence.
1111           if (LL == I)
1112             L = LR;
1113           else if (LR == I)
1114             L = LL;
1115           else
1116             break;
1117           // Ok, we have a PHI of the form L op= R. Check for low
1118           // zero bits.
1119           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1120           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1121           Mask2 = APInt::getLowBitsSet(BitWidth,
1122                                        KnownZero2.countTrailingOnes());
1123           KnownOne2.clear();
1124           KnownZero2.clear();
1125           ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1126           KnownZero = Mask &
1127                       APInt::getLowBitsSet(BitWidth,
1128                                            KnownZero2.countTrailingOnes());
1129           break;
1130         }
1131       }
1132     }
1133     break;
1134   }
1135   case Instruction::Call:
1136     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1137       switch (II->getIntrinsicID()) {
1138       default: break;
1139       case Intrinsic::ctpop:
1140       case Intrinsic::ctlz:
1141       case Intrinsic::cttz: {
1142         unsigned LowBits = Log2_32(BitWidth)+1;
1143         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1144         break;
1145       }
1146       }
1147     }
1148     break;
1149   }
1150 }
1151
1152 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1153 /// this predicate to simplify operations downstream.  Mask is known to be zero
1154 /// for bits that V cannot have.
1155 bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1156                                      unsigned Depth) {
1157   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1158   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1159   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1160   return (KnownZero & Mask) == Mask;
1161 }
1162
1163 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
1164 /// specified instruction is a constant integer.  If so, check to see if there
1165 /// are any bits set in the constant that are not demanded.  If so, shrink the
1166 /// constant and return true.
1167 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
1168                                    APInt Demanded) {
1169   assert(I && "No instruction?");
1170   assert(OpNo < I->getNumOperands() && "Operand index too large");
1171
1172   // If the operand is not a constant integer, nothing to do.
1173   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1174   if (!OpC) return false;
1175
1176   // If there are no bits set that aren't demanded, nothing to do.
1177   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1178   if ((~Demanded & OpC->getValue()) == 0)
1179     return false;
1180
1181   // This instruction is producing bits that are not demanded. Shrink the RHS.
1182   Demanded &= OpC->getValue();
1183   I->setOperand(OpNo, ConstantInt::get(Demanded));
1184   return true;
1185 }
1186
1187 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
1188 // set of known zero and one bits, compute the maximum and minimum values that
1189 // could have the specified known zero and known one bits, returning them in
1190 // min/max.
1191 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1192                                                    const APInt& KnownZero,
1193                                                    const APInt& KnownOne,
1194                                                    APInt& Min, APInt& Max) {
1195   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1196   assert(KnownZero.getBitWidth() == BitWidth && 
1197          KnownOne.getBitWidth() == BitWidth &&
1198          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1199          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1200   APInt UnknownBits = ~(KnownZero|KnownOne);
1201
1202   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1203   // bit if it is unknown.
1204   Min = KnownOne;
1205   Max = KnownOne|UnknownBits;
1206   
1207   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1208     Min.set(BitWidth-1);
1209     Max.clear(BitWidth-1);
1210   }
1211 }
1212
1213 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1214 // a set of known zero and one bits, compute the maximum and minimum values that
1215 // could have the specified known zero and known one bits, returning them in
1216 // min/max.
1217 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1218                                                      const APInt &KnownZero,
1219                                                      const APInt &KnownOne,
1220                                                      APInt &Min, APInt &Max) {
1221   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
1222   assert(KnownZero.getBitWidth() == BitWidth && 
1223          KnownOne.getBitWidth() == BitWidth &&
1224          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1225          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1226   APInt UnknownBits = ~(KnownZero|KnownOne);
1227   
1228   // The minimum value is when the unknown bits are all zeros.
1229   Min = KnownOne;
1230   // The maximum value is when the unknown bits are all ones.
1231   Max = KnownOne|UnknownBits;
1232 }
1233
1234 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
1235 /// value based on the demanded bits. When this function is called, it is known
1236 /// that only the bits set in DemandedMask of the result of V are ever used
1237 /// downstream. Consequently, depending on the mask and V, it may be possible
1238 /// to replace V with a constant or one of its operands. In such cases, this
1239 /// function does the replacement and returns true. In all other cases, it
1240 /// returns false after analyzing the expression and setting KnownOne and known
1241 /// to be one in the expression. KnownZero contains all the bits that are known
1242 /// to be zero in the expression. These are provided to potentially allow the
1243 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1244 /// the expression. KnownOne and KnownZero always follow the invariant that 
1245 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1246 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
1247 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1248 /// and KnownOne must all be the same.
1249 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1250                                         APInt& KnownZero, APInt& KnownOne,
1251                                         unsigned Depth) {
1252   assert(V != 0 && "Null pointer of Value???");
1253   assert(Depth <= 6 && "Limit Search Depth");
1254   uint32_t BitWidth = DemandedMask.getBitWidth();
1255   const IntegerType *VTy = cast<IntegerType>(V->getType());
1256   assert(VTy->getBitWidth() == BitWidth && 
1257          KnownZero.getBitWidth() == BitWidth && 
1258          KnownOne.getBitWidth() == BitWidth &&
1259          "Value *V, DemandedMask, KnownZero and KnownOne \
1260           must have same BitWidth");
1261   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1262     // We know all of the bits for a constant!
1263     KnownOne = CI->getValue() & DemandedMask;
1264     KnownZero = ~KnownOne & DemandedMask;
1265     return false;
1266   }
1267   
1268   KnownZero.clear(); 
1269   KnownOne.clear();
1270   if (!V->hasOneUse()) {    // Other users may use these bits.
1271     if (Depth != 0) {       // Not at the root.
1272       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1273       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1274       return false;
1275     }
1276     // If this is the root being simplified, allow it to have multiple uses,
1277     // just set the DemandedMask to all bits.
1278     DemandedMask = APInt::getAllOnesValue(BitWidth);
1279   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
1280     if (V != UndefValue::get(VTy))
1281       return UpdateValueUsesWith(V, UndefValue::get(VTy));
1282     return false;
1283   } else if (Depth == 6) {        // Limit search depth.
1284     return false;
1285   }
1286   
1287   Instruction *I = dyn_cast<Instruction>(V);
1288   if (!I) return false;        // Only analyze instructions.
1289
1290   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1291   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1292   switch (I->getOpcode()) {
1293   default:
1294     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1295     break;
1296   case Instruction::And:
1297     // If either the LHS or the RHS are Zero, the result is zero.
1298     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1299                              RHSKnownZero, RHSKnownOne, Depth+1))
1300       return true;
1301     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1302            "Bits known to be one AND zero?"); 
1303
1304     // If something is known zero on the RHS, the bits aren't demanded on the
1305     // LHS.
1306     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1307                              LHSKnownZero, LHSKnownOne, Depth+1))
1308       return true;
1309     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1310            "Bits known to be one AND zero?"); 
1311
1312     // If all of the demanded bits are known 1 on one side, return the other.
1313     // These bits cannot contribute to the result of the 'and'.
1314     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1315         (DemandedMask & ~LHSKnownZero))
1316       return UpdateValueUsesWith(I, I->getOperand(0));
1317     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1318         (DemandedMask & ~RHSKnownZero))
1319       return UpdateValueUsesWith(I, I->getOperand(1));
1320     
1321     // If all of the demanded bits in the inputs are known zeros, return zero.
1322     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1323       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1324       
1325     // If the RHS is a constant, see if we can simplify it.
1326     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1327       return UpdateValueUsesWith(I, I);
1328       
1329     // Output known-1 bits are only known if set in both the LHS & RHS.
1330     RHSKnownOne &= LHSKnownOne;
1331     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1332     RHSKnownZero |= LHSKnownZero;
1333     break;
1334   case Instruction::Or:
1335     // If either the LHS or the RHS are One, the result is One.
1336     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1337                              RHSKnownZero, RHSKnownOne, Depth+1))
1338       return true;
1339     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1340            "Bits known to be one AND zero?"); 
1341     // If something is known one on the RHS, the bits aren't demanded on the
1342     // LHS.
1343     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1344                              LHSKnownZero, LHSKnownOne, Depth+1))
1345       return true;
1346     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1347            "Bits known to be one AND zero?"); 
1348     
1349     // If all of the demanded bits are known zero on one side, return the other.
1350     // These bits cannot contribute to the result of the 'or'.
1351     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1352         (DemandedMask & ~LHSKnownOne))
1353       return UpdateValueUsesWith(I, I->getOperand(0));
1354     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1355         (DemandedMask & ~RHSKnownOne))
1356       return UpdateValueUsesWith(I, I->getOperand(1));
1357
1358     // If all of the potentially set bits on one side are known to be set on
1359     // the other side, just use the 'other' side.
1360     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1361         (DemandedMask & (~RHSKnownZero)))
1362       return UpdateValueUsesWith(I, I->getOperand(0));
1363     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1364         (DemandedMask & (~LHSKnownZero)))
1365       return UpdateValueUsesWith(I, I->getOperand(1));
1366         
1367     // If the RHS is a constant, see if we can simplify it.
1368     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1369       return UpdateValueUsesWith(I, I);
1370           
1371     // Output known-0 bits are only known if clear in both the LHS & RHS.
1372     RHSKnownZero &= LHSKnownZero;
1373     // Output known-1 are known to be set if set in either the LHS | RHS.
1374     RHSKnownOne |= LHSKnownOne;
1375     break;
1376   case Instruction::Xor: {
1377     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1378                              RHSKnownZero, RHSKnownOne, Depth+1))
1379       return true;
1380     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1381            "Bits known to be one AND zero?"); 
1382     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1383                              LHSKnownZero, LHSKnownOne, Depth+1))
1384       return true;
1385     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1386            "Bits known to be one AND zero?"); 
1387     
1388     // If all of the demanded bits are known zero on one side, return the other.
1389     // These bits cannot contribute to the result of the 'xor'.
1390     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1391       return UpdateValueUsesWith(I, I->getOperand(0));
1392     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1393       return UpdateValueUsesWith(I, I->getOperand(1));
1394     
1395     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1396     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1397                          (RHSKnownOne & LHSKnownOne);
1398     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1399     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1400                         (RHSKnownOne & LHSKnownZero);
1401     
1402     // If all of the demanded bits are known to be zero on one side or the
1403     // other, turn this into an *inclusive* or.
1404     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1405     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1406       Instruction *Or =
1407         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1408                                  I->getName());
1409       InsertNewInstBefore(Or, *I);
1410       return UpdateValueUsesWith(I, Or);
1411     }
1412     
1413     // If all of the demanded bits on one side are known, and all of the set
1414     // bits on that side are also known to be set on the other side, turn this
1415     // into an AND, as we know the bits will be cleared.
1416     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1417     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1418       // all known
1419       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1420         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1421         Instruction *And = 
1422           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1423         InsertNewInstBefore(And, *I);
1424         return UpdateValueUsesWith(I, And);
1425       }
1426     }
1427     
1428     // If the RHS is a constant, see if we can simplify it.
1429     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1430     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1431       return UpdateValueUsesWith(I, I);
1432     
1433     RHSKnownZero = KnownZeroOut;
1434     RHSKnownOne  = KnownOneOut;
1435     break;
1436   }
1437   case Instruction::Select:
1438     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1439                              RHSKnownZero, RHSKnownOne, Depth+1))
1440       return true;
1441     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1442                              LHSKnownZero, LHSKnownOne, Depth+1))
1443       return true;
1444     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1445            "Bits known to be one AND zero?"); 
1446     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1447            "Bits known to be one AND zero?"); 
1448     
1449     // If the operands are constants, see if we can simplify them.
1450     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1451       return UpdateValueUsesWith(I, I);
1452     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1453       return UpdateValueUsesWith(I, I);
1454     
1455     // Only known if known in both the LHS and RHS.
1456     RHSKnownOne &= LHSKnownOne;
1457     RHSKnownZero &= LHSKnownZero;
1458     break;
1459   case Instruction::Trunc: {
1460     uint32_t truncBf = 
1461       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1462     DemandedMask.zext(truncBf);
1463     RHSKnownZero.zext(truncBf);
1464     RHSKnownOne.zext(truncBf);
1465     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1466                              RHSKnownZero, RHSKnownOne, Depth+1))
1467       return true;
1468     DemandedMask.trunc(BitWidth);
1469     RHSKnownZero.trunc(BitWidth);
1470     RHSKnownOne.trunc(BitWidth);
1471     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1472            "Bits known to be one AND zero?"); 
1473     break;
1474   }
1475   case Instruction::BitCast:
1476     if (!I->getOperand(0)->getType()->isInteger())
1477       return false;
1478       
1479     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1480                              RHSKnownZero, RHSKnownOne, Depth+1))
1481       return true;
1482     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1483            "Bits known to be one AND zero?"); 
1484     break;
1485   case Instruction::ZExt: {
1486     // Compute the bits in the result that are not present in the input.
1487     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1488     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1489     
1490     DemandedMask.trunc(SrcBitWidth);
1491     RHSKnownZero.trunc(SrcBitWidth);
1492     RHSKnownOne.trunc(SrcBitWidth);
1493     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1494                              RHSKnownZero, RHSKnownOne, Depth+1))
1495       return true;
1496     DemandedMask.zext(BitWidth);
1497     RHSKnownZero.zext(BitWidth);
1498     RHSKnownOne.zext(BitWidth);
1499     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1500            "Bits known to be one AND zero?"); 
1501     // The top bits are known to be zero.
1502     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1503     break;
1504   }
1505   case Instruction::SExt: {
1506     // Compute the bits in the result that are not present in the input.
1507     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1508     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1509     
1510     APInt InputDemandedBits = DemandedMask & 
1511                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1512
1513     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1514     // If any of the sign extended bits are demanded, we know that the sign
1515     // bit is demanded.
1516     if ((NewBits & DemandedMask) != 0)
1517       InputDemandedBits.set(SrcBitWidth-1);
1518       
1519     InputDemandedBits.trunc(SrcBitWidth);
1520     RHSKnownZero.trunc(SrcBitWidth);
1521     RHSKnownOne.trunc(SrcBitWidth);
1522     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1523                              RHSKnownZero, RHSKnownOne, Depth+1))
1524       return true;
1525     InputDemandedBits.zext(BitWidth);
1526     RHSKnownZero.zext(BitWidth);
1527     RHSKnownOne.zext(BitWidth);
1528     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1529            "Bits known to be one AND zero?"); 
1530       
1531     // If the sign bit of the input is known set or clear, then we know the
1532     // top bits of the result.
1533
1534     // If the input sign bit is known zero, or if the NewBits are not demanded
1535     // convert this into a zero extension.
1536     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1537     {
1538       // Convert to ZExt cast
1539       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1540       return UpdateValueUsesWith(I, NewCast);
1541     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1542       RHSKnownOne |= NewBits;
1543     }
1544     break;
1545   }
1546   case Instruction::Add: {
1547     // Figure out what the input bits are.  If the top bits of the and result
1548     // are not demanded, then the add doesn't demand them from its input
1549     // either.
1550     uint32_t NLZ = DemandedMask.countLeadingZeros();
1551       
1552     // If there is a constant on the RHS, there are a variety of xformations
1553     // we can do.
1554     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1555       // If null, this should be simplified elsewhere.  Some of the xforms here
1556       // won't work if the RHS is zero.
1557       if (RHS->isZero())
1558         break;
1559       
1560       // If the top bit of the output is demanded, demand everything from the
1561       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1562       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1563
1564       // Find information about known zero/one bits in the input.
1565       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1566                                LHSKnownZero, LHSKnownOne, Depth+1))
1567         return true;
1568
1569       // If the RHS of the add has bits set that can't affect the input, reduce
1570       // the constant.
1571       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1572         return UpdateValueUsesWith(I, I);
1573       
1574       // Avoid excess work.
1575       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1576         break;
1577       
1578       // Turn it into OR if input bits are zero.
1579       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1580         Instruction *Or =
1581           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1582                                    I->getName());
1583         InsertNewInstBefore(Or, *I);
1584         return UpdateValueUsesWith(I, Or);
1585       }
1586       
1587       // We can say something about the output known-zero and known-one bits,
1588       // depending on potential carries from the input constant and the
1589       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1590       // bits set and the RHS constant is 0x01001, then we know we have a known
1591       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1592       
1593       // To compute this, we first compute the potential carry bits.  These are
1594       // the bits which may be modified.  I'm not aware of a better way to do
1595       // this scan.
1596       const APInt& RHSVal = RHS->getValue();
1597       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1598       
1599       // Now that we know which bits have carries, compute the known-1/0 sets.
1600       
1601       // Bits are known one if they are known zero in one operand and one in the
1602       // other, and there is no input carry.
1603       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1604                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1605       
1606       // Bits are known zero if they are known zero in both operands and there
1607       // is no input carry.
1608       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1609     } else {
1610       // If the high-bits of this ADD are not demanded, then it does not demand
1611       // the high bits of its LHS or RHS.
1612       if (DemandedMask[BitWidth-1] == 0) {
1613         // Right fill the mask of bits for this ADD to demand the most
1614         // significant bit and all those below it.
1615         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1616         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1617                                  LHSKnownZero, LHSKnownOne, Depth+1))
1618           return true;
1619         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1620                                  LHSKnownZero, LHSKnownOne, Depth+1))
1621           return true;
1622       }
1623     }
1624     break;
1625   }
1626   case Instruction::Sub:
1627     // If the high-bits of this SUB are not demanded, then it does not demand
1628     // the high bits of its LHS or RHS.
1629     if (DemandedMask[BitWidth-1] == 0) {
1630       // Right fill the mask of bits for this SUB to demand the most
1631       // significant bit and all those below it.
1632       uint32_t NLZ = DemandedMask.countLeadingZeros();
1633       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1634       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1635                                LHSKnownZero, LHSKnownOne, Depth+1))
1636         return true;
1637       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1638                                LHSKnownZero, LHSKnownOne, Depth+1))
1639         return true;
1640     }
1641     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1642     // the known zeros and ones.
1643     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1644     break;
1645   case Instruction::Shl:
1646     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1647       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1648       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1649       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1650                                RHSKnownZero, RHSKnownOne, Depth+1))
1651         return true;
1652       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1653              "Bits known to be one AND zero?"); 
1654       RHSKnownZero <<= ShiftAmt;
1655       RHSKnownOne  <<= ShiftAmt;
1656       // low bits known zero.
1657       if (ShiftAmt)
1658         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1659     }
1660     break;
1661   case Instruction::LShr:
1662     // For a logical shift right
1663     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1664       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1665       
1666       // Unsigned shift right.
1667       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1668       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1669                                RHSKnownZero, RHSKnownOne, Depth+1))
1670         return true;
1671       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1672              "Bits known to be one AND zero?"); 
1673       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1674       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1675       if (ShiftAmt) {
1676         // Compute the new bits that are at the top now.
1677         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1678         RHSKnownZero |= HighBits;  // high bits known zero.
1679       }
1680     }
1681     break;
1682   case Instruction::AShr:
1683     // If this is an arithmetic shift right and only the low-bit is set, we can
1684     // always convert this into a logical shr, even if the shift amount is
1685     // variable.  The low bit of the shift cannot be an input sign bit unless
1686     // the shift amount is >= the size of the datatype, which is undefined.
1687     if (DemandedMask == 1) {
1688       // Perform the logical shift right.
1689       Value *NewVal = BinaryOperator::CreateLShr(
1690                         I->getOperand(0), I->getOperand(1), I->getName());
1691       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1692       return UpdateValueUsesWith(I, NewVal);
1693     }    
1694
1695     // If the sign bit is the only bit demanded by this ashr, then there is no
1696     // need to do it, the shift doesn't change the high bit.
1697     if (DemandedMask.isSignBit())
1698       return UpdateValueUsesWith(I, I->getOperand(0));
1699     
1700     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1701       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1702       
1703       // Signed shift right.
1704       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1705       // If any of the "high bits" are demanded, we should set the sign bit as
1706       // demanded.
1707       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1708         DemandedMaskIn.set(BitWidth-1);
1709       if (SimplifyDemandedBits(I->getOperand(0),
1710                                DemandedMaskIn,
1711                                RHSKnownZero, RHSKnownOne, Depth+1))
1712         return true;
1713       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1714              "Bits known to be one AND zero?"); 
1715       // Compute the new bits that are at the top now.
1716       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1717       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1718       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1719         
1720       // Handle the sign bits.
1721       APInt SignBit(APInt::getSignBit(BitWidth));
1722       // Adjust to where it is now in the mask.
1723       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1724         
1725       // If the input sign bit is known to be zero, or if none of the top bits
1726       // are demanded, turn this into an unsigned shift right.
1727       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1728           (HighBits & ~DemandedMask) == HighBits) {
1729         // Perform the logical shift right.
1730         Value *NewVal = BinaryOperator::CreateLShr(
1731                           I->getOperand(0), SA, I->getName());
1732         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1733         return UpdateValueUsesWith(I, NewVal);
1734       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1735         RHSKnownOne |= HighBits;
1736       }
1737     }
1738     break;
1739   case Instruction::SRem:
1740     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1741       APInt RA = Rem->getValue();
1742       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1743         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1744         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1745         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1746                                  LHSKnownZero, LHSKnownOne, Depth+1))
1747           return true;
1748
1749         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1750           LHSKnownZero |= ~LowBits;
1751         else if (LHSKnownOne[BitWidth-1])
1752           LHSKnownOne |= ~LowBits;
1753
1754         KnownZero |= LHSKnownZero & DemandedMask;
1755         KnownOne |= LHSKnownOne & DemandedMask;
1756
1757         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1758       }
1759     }
1760     break;
1761   case Instruction::URem: {
1762     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1763       APInt RA = Rem->getValue();
1764       if (RA.isPowerOf2()) {
1765         APInt LowBits = (RA - 1);
1766         APInt Mask2 = LowBits & DemandedMask;
1767         KnownZero |= ~LowBits & DemandedMask;
1768         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1769                                  KnownZero, KnownOne, Depth+1))
1770           return true;
1771
1772         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1773         break;
1774       }
1775     }
1776
1777     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1778     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1779     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1780                              KnownZero2, KnownOne2, Depth+1))
1781       return true;
1782
1783     uint32_t Leaders = KnownZero2.countLeadingOnes();
1784     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1785                              KnownZero2, KnownOne2, Depth+1))
1786       return true;
1787
1788     Leaders = std::max(Leaders,
1789                        KnownZero2.countLeadingOnes());
1790     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1791     break;
1792   }
1793   }
1794   
1795   // If the client is only demanding bits that we know, return the known
1796   // constant.
1797   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1798     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1799   return false;
1800 }
1801
1802
1803 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1804 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1805 /// actually used by the caller.  This method analyzes which elements of the
1806 /// operand are undef and returns that information in UndefElts.
1807 ///
1808 /// If the information about demanded elements can be used to simplify the
1809 /// operation, the operation is simplified, then the resultant value is
1810 /// returned.  This returns null if no change was made.
1811 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1812                                                 uint64_t &UndefElts,
1813                                                 unsigned Depth) {
1814   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1815   assert(VWidth <= 64 && "Vector too wide to analyze!");
1816   uint64_t EltMask = ~0ULL >> (64-VWidth);
1817   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1818          "Invalid DemandedElts!");
1819
1820   if (isa<UndefValue>(V)) {
1821     // If the entire vector is undefined, just return this info.
1822     UndefElts = EltMask;
1823     return 0;
1824   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1825     UndefElts = EltMask;
1826     return UndefValue::get(V->getType());
1827   }
1828   
1829   UndefElts = 0;
1830   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1831     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1832     Constant *Undef = UndefValue::get(EltTy);
1833
1834     std::vector<Constant*> Elts;
1835     for (unsigned i = 0; i != VWidth; ++i)
1836       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1837         Elts.push_back(Undef);
1838         UndefElts |= (1ULL << i);
1839       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1840         Elts.push_back(Undef);
1841         UndefElts |= (1ULL << i);
1842       } else {                               // Otherwise, defined.
1843         Elts.push_back(CP->getOperand(i));
1844       }
1845         
1846     // If we changed the constant, return it.
1847     Constant *NewCP = ConstantVector::get(Elts);
1848     return NewCP != CP ? NewCP : 0;
1849   } else if (isa<ConstantAggregateZero>(V)) {
1850     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1851     // set to undef.
1852     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1853     Constant *Zero = Constant::getNullValue(EltTy);
1854     Constant *Undef = UndefValue::get(EltTy);
1855     std::vector<Constant*> Elts;
1856     for (unsigned i = 0; i != VWidth; ++i)
1857       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1858     UndefElts = DemandedElts ^ EltMask;
1859     return ConstantVector::get(Elts);
1860   }
1861   
1862   if (!V->hasOneUse()) {    // Other users may use these bits.
1863     if (Depth != 0) {       // Not at the root.
1864       // TODO: Just compute the UndefElts information recursively.
1865       return false;
1866     }
1867     return false;
1868   } else if (Depth == 10) {        // Limit search depth.
1869     return false;
1870   }
1871   
1872   Instruction *I = dyn_cast<Instruction>(V);
1873   if (!I) return false;        // Only analyze instructions.
1874   
1875   bool MadeChange = false;
1876   uint64_t UndefElts2;
1877   Value *TmpV;
1878   switch (I->getOpcode()) {
1879   default: break;
1880     
1881   case Instruction::InsertElement: {
1882     // If this is a variable index, we don't know which element it overwrites.
1883     // demand exactly the same input as we produce.
1884     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1885     if (Idx == 0) {
1886       // Note that we can't propagate undef elt info, because we don't know
1887       // which elt is getting updated.
1888       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1889                                         UndefElts2, Depth+1);
1890       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1891       break;
1892     }
1893     
1894     // If this is inserting an element that isn't demanded, remove this
1895     // insertelement.
1896     unsigned IdxNo = Idx->getZExtValue();
1897     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1898       return AddSoonDeadInstToWorklist(*I, 0);
1899     
1900     // Otherwise, the element inserted overwrites whatever was there, so the
1901     // input demanded set is simpler than the output set.
1902     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1903                                       DemandedElts & ~(1ULL << IdxNo),
1904                                       UndefElts, Depth+1);
1905     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1906
1907     // The inserted element is defined.
1908     UndefElts |= 1ULL << IdxNo;
1909     break;
1910   }
1911   case Instruction::BitCast: {
1912     // Vector->vector casts only.
1913     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1914     if (!VTy) break;
1915     unsigned InVWidth = VTy->getNumElements();
1916     uint64_t InputDemandedElts = 0;
1917     unsigned Ratio;
1918
1919     if (VWidth == InVWidth) {
1920       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1921       // elements as are demanded of us.
1922       Ratio = 1;
1923       InputDemandedElts = DemandedElts;
1924     } else if (VWidth > InVWidth) {
1925       // Untested so far.
1926       break;
1927       
1928       // If there are more elements in the result than there are in the source,
1929       // then an input element is live if any of the corresponding output
1930       // elements are live.
1931       Ratio = VWidth/InVWidth;
1932       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1933         if (DemandedElts & (1ULL << OutIdx))
1934           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1935       }
1936     } else {
1937       // Untested so far.
1938       break;
1939       
1940       // If there are more elements in the source than there are in the result,
1941       // then an input element is live if the corresponding output element is
1942       // live.
1943       Ratio = InVWidth/VWidth;
1944       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1945         if (DemandedElts & (1ULL << InIdx/Ratio))
1946           InputDemandedElts |= 1ULL << InIdx;
1947     }
1948     
1949     // div/rem demand all inputs, because they don't want divide by zero.
1950     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1951                                       UndefElts2, Depth+1);
1952     if (TmpV) {
1953       I->setOperand(0, TmpV);
1954       MadeChange = true;
1955     }
1956     
1957     UndefElts = UndefElts2;
1958     if (VWidth > InVWidth) {
1959       assert(0 && "Unimp");
1960       // If there are more elements in the result than there are in the source,
1961       // then an output element is undef if the corresponding input element is
1962       // undef.
1963       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1964         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1965           UndefElts |= 1ULL << OutIdx;
1966     } else if (VWidth < InVWidth) {
1967       assert(0 && "Unimp");
1968       // If there are more elements in the source than there are in the result,
1969       // then a result element is undef if all of the corresponding input
1970       // elements are undef.
1971       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1972       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1973         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1974           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1975     }
1976     break;
1977   }
1978   case Instruction::And:
1979   case Instruction::Or:
1980   case Instruction::Xor:
1981   case Instruction::Add:
1982   case Instruction::Sub:
1983   case Instruction::Mul:
1984     // div/rem demand all inputs, because they don't want divide by zero.
1985     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1986                                       UndefElts, Depth+1);
1987     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1988     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1989                                       UndefElts2, Depth+1);
1990     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1991       
1992     // Output elements are undefined if both are undefined.  Consider things
1993     // like undef&0.  The result is known zero, not undef.
1994     UndefElts &= UndefElts2;
1995     break;
1996     
1997   case Instruction::Call: {
1998     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1999     if (!II) break;
2000     switch (II->getIntrinsicID()) {
2001     default: break;
2002       
2003     // Binary vector operations that work column-wise.  A dest element is a
2004     // function of the corresponding input elements from the two inputs.
2005     case Intrinsic::x86_sse_sub_ss:
2006     case Intrinsic::x86_sse_mul_ss:
2007     case Intrinsic::x86_sse_min_ss:
2008     case Intrinsic::x86_sse_max_ss:
2009     case Intrinsic::x86_sse2_sub_sd:
2010     case Intrinsic::x86_sse2_mul_sd:
2011     case Intrinsic::x86_sse2_min_sd:
2012     case Intrinsic::x86_sse2_max_sd:
2013       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2014                                         UndefElts, Depth+1);
2015       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2016       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2017                                         UndefElts2, Depth+1);
2018       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2019
2020       // If only the low elt is demanded and this is a scalarizable intrinsic,
2021       // scalarize it now.
2022       if (DemandedElts == 1) {
2023         switch (II->getIntrinsicID()) {
2024         default: break;
2025         case Intrinsic::x86_sse_sub_ss:
2026         case Intrinsic::x86_sse_mul_ss:
2027         case Intrinsic::x86_sse2_sub_sd:
2028         case Intrinsic::x86_sse2_mul_sd:
2029           // TODO: Lower MIN/MAX/ABS/etc
2030           Value *LHS = II->getOperand(1);
2031           Value *RHS = II->getOperand(2);
2032           // Extract the element as scalars.
2033           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2034           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2035           
2036           switch (II->getIntrinsicID()) {
2037           default: assert(0 && "Case stmts out of sync!");
2038           case Intrinsic::x86_sse_sub_ss:
2039           case Intrinsic::x86_sse2_sub_sd:
2040             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
2041                                                         II->getName()), *II);
2042             break;
2043           case Intrinsic::x86_sse_mul_ss:
2044           case Intrinsic::x86_sse2_mul_sd:
2045             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
2046                                                          II->getName()), *II);
2047             break;
2048           }
2049           
2050           Instruction *New =
2051             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2052                                       II->getName());
2053           InsertNewInstBefore(New, *II);
2054           AddSoonDeadInstToWorklist(*II, 0);
2055           return New;
2056         }            
2057       }
2058         
2059       // Output elements are undefined if both are undefined.  Consider things
2060       // like undef&0.  The result is known zero, not undef.
2061       UndefElts &= UndefElts2;
2062       break;
2063     }
2064     break;
2065   }
2066   }
2067   return MadeChange ? I : 0;
2068 }
2069
2070 /// ComputeNumSignBits - Return the number of times the sign bit of the
2071 /// register is replicated into the other bits.  We know that at least 1 bit
2072 /// is always equal to the sign bit (itself), but other cases can give us
2073 /// information.  For example, immediately after an "ashr X, 2", we know that
2074 /// the top 3 bits are all equal to each other, so we return 3.
2075 ///
2076 unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2077   const IntegerType *Ty = cast<IntegerType>(V->getType());
2078   unsigned TyBits = Ty->getBitWidth();
2079   unsigned Tmp, Tmp2;
2080   unsigned FirstAnswer = 1;
2081
2082   if (Depth == 6)
2083     return 1;  // Limit search depth.
2084
2085   User *U = dyn_cast<User>(V);
2086   switch (getOpcode(V)) {
2087   default: break;
2088   case Instruction::SExt:
2089     Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2090     return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2091     
2092   case Instruction::AShr:
2093     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2094     // ashr X, C   -> adds C sign bits.
2095     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2096       Tmp += C->getZExtValue();
2097       if (Tmp > TyBits) Tmp = TyBits;
2098     }
2099     return Tmp;
2100   case Instruction::Shl:
2101     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2102       // shl destroys sign bits.
2103       Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2104       if (C->getZExtValue() >= TyBits ||      // Bad shift.
2105           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
2106       return Tmp - C->getZExtValue();
2107     }
2108     break;
2109   case Instruction::And:
2110   case Instruction::Or:
2111   case Instruction::Xor:    // NOT is handled here.
2112     // Logical binary ops preserve the number of sign bits at the worst.
2113     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2114     if (Tmp != 1) {
2115       Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2116       FirstAnswer = std::min(Tmp, Tmp2);
2117       // We computed what we know about the sign bits as our first
2118       // answer. Now proceed to the generic code that uses
2119       // ComputeMaskedBits, and pick whichever answer is better.
2120     }
2121     break;
2122
2123   case Instruction::Select:
2124     Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
2125     if (Tmp == 1) return 1;  // Early out.
2126     Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
2127     return std::min(Tmp, Tmp2);
2128     
2129   case Instruction::Add:
2130     // Add can have at most one carry bit.  Thus we know that the output
2131     // is, at worst, one more bit than the inputs.
2132     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2133     if (Tmp == 1) return 1;  // Early out.
2134       
2135     // Special case decrementing a value (ADD X, -1):
2136     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2137       if (CRHS->isAllOnesValue()) {
2138         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2139         APInt Mask = APInt::getAllOnesValue(TyBits);
2140         ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2141         
2142         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2143         // sign bits set.
2144         if ((KnownZero | APInt(TyBits, 1)) == Mask)
2145           return TyBits;
2146         
2147         // If we are subtracting one from a positive number, there is no carry
2148         // out of the result.
2149         if (KnownZero.isNegative())
2150           return Tmp;
2151       }
2152       
2153     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2154     if (Tmp2 == 1) return 1;
2155       return std::min(Tmp, Tmp2)-1;
2156     break;
2157     
2158   case Instruction::Sub:
2159     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2160     if (Tmp2 == 1) return 1;
2161       
2162     // Handle NEG.
2163     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2164       if (CLHS->isNullValue()) {
2165         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2166         APInt Mask = APInt::getAllOnesValue(TyBits);
2167         ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2168         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2169         // sign bits set.
2170         if ((KnownZero | APInt(TyBits, 1)) == Mask)
2171           return TyBits;
2172         
2173         // If the input is known to be positive (the sign bit is known clear),
2174         // the output of the NEG has the same number of sign bits as the input.
2175         if (KnownZero.isNegative())
2176           return Tmp2;
2177         
2178         // Otherwise, we treat this like a SUB.
2179       }
2180     
2181     // Sub can have at most one carry bit.  Thus we know that the output
2182     // is, at worst, one more bit than the inputs.
2183     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2184     if (Tmp == 1) return 1;  // Early out.
2185       return std::min(Tmp, Tmp2)-1;
2186     break;
2187   case Instruction::Trunc:
2188     // FIXME: it's tricky to do anything useful for this, but it is an important
2189     // case for targets like X86.
2190     break;
2191   }
2192   
2193   // Finally, if we can prove that the top bits of the result are 0's or 1's,
2194   // use this information.
2195   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2196   APInt Mask = APInt::getAllOnesValue(TyBits);
2197   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2198   
2199   if (KnownZero.isNegative()) {        // sign bit is 0
2200     Mask = KnownZero;
2201   } else if (KnownOne.isNegative()) {  // sign bit is 1;
2202     Mask = KnownOne;
2203   } else {
2204     // Nothing known.
2205     return FirstAnswer;
2206   }
2207   
2208   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
2209   // the number of identical bits in the top of the input value.
2210   Mask = ~Mask;
2211   Mask <<= Mask.getBitWidth()-TyBits;
2212   // Return # leading zeros.  We use 'min' here in case Val was zero before
2213   // shifting.  We don't want to return '64' as for an i32 "0".
2214   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2215 }
2216
2217
2218 /// AssociativeOpt - Perform an optimization on an associative operator.  This
2219 /// function is designed to check a chain of associative operators for a
2220 /// potential to apply a certain optimization.  Since the optimization may be
2221 /// applicable if the expression was reassociated, this checks the chain, then
2222 /// reassociates the expression as necessary to expose the optimization
2223 /// opportunity.  This makes use of a special Functor, which must define
2224 /// 'shouldApply' and 'apply' methods.
2225 ///
2226 template<typename Functor>
2227 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2228   unsigned Opcode = Root.getOpcode();
2229   Value *LHS = Root.getOperand(0);
2230
2231   // Quick check, see if the immediate LHS matches...
2232   if (F.shouldApply(LHS))
2233     return F.apply(Root);
2234
2235   // Otherwise, if the LHS is not of the same opcode as the root, return.
2236   Instruction *LHSI = dyn_cast<Instruction>(LHS);
2237   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2238     // Should we apply this transform to the RHS?
2239     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2240
2241     // If not to the RHS, check to see if we should apply to the LHS...
2242     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2243       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
2244       ShouldApply = true;
2245     }
2246
2247     // If the functor wants to apply the optimization to the RHS of LHSI,
2248     // reassociate the expression from ((? op A) op B) to (? op (A op B))
2249     if (ShouldApply) {
2250       BasicBlock *BB = Root.getParent();
2251
2252       // Now all of the instructions are in the current basic block, go ahead
2253       // and perform the reassociation.
2254       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2255
2256       // First move the selected RHS to the LHS of the root...
2257       Root.setOperand(0, LHSI->getOperand(1));
2258
2259       // Make what used to be the LHS of the root be the user of the root...
2260       Value *ExtraOperand = TmpLHSI->getOperand(1);
2261       if (&Root == TmpLHSI) {
2262         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2263         return 0;
2264       }
2265       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
2266       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
2267       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2268       BasicBlock::iterator ARI = &Root; ++ARI;
2269       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
2270       ARI = Root;
2271
2272       // Now propagate the ExtraOperand down the chain of instructions until we
2273       // get to LHSI.
2274       while (TmpLHSI != LHSI) {
2275         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2276         // Move the instruction to immediately before the chain we are
2277         // constructing to avoid breaking dominance properties.
2278         NextLHSI->getParent()->getInstList().remove(NextLHSI);
2279         BB->getInstList().insert(ARI, NextLHSI);
2280         ARI = NextLHSI;
2281
2282         Value *NextOp = NextLHSI->getOperand(1);
2283         NextLHSI->setOperand(1, ExtraOperand);
2284         TmpLHSI = NextLHSI;
2285         ExtraOperand = NextOp;
2286       }
2287
2288       // Now that the instructions are reassociated, have the functor perform
2289       // the transformation...
2290       return F.apply(Root);
2291     }
2292
2293     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2294   }
2295   return 0;
2296 }
2297
2298 namespace {
2299
2300 // AddRHS - Implements: X + X --> X << 1
2301 struct AddRHS {
2302   Value *RHS;
2303   AddRHS(Value *rhs) : RHS(rhs) {}
2304   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2305   Instruction *apply(BinaryOperator &Add) const {
2306     return BinaryOperator::CreateShl(Add.getOperand(0),
2307                                      ConstantInt::get(Add.getType(), 1));
2308   }
2309 };
2310
2311 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2312 //                 iff C1&C2 == 0
2313 struct AddMaskingAnd {
2314   Constant *C2;
2315   AddMaskingAnd(Constant *c) : C2(c) {}
2316   bool shouldApply(Value *LHS) const {
2317     ConstantInt *C1;
2318     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2319            ConstantExpr::getAnd(C1, C2)->isNullValue();
2320   }
2321   Instruction *apply(BinaryOperator &Add) const {
2322     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
2323   }
2324 };
2325
2326 }
2327
2328 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2329                                              InstCombiner *IC) {
2330   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2331     if (Constant *SOC = dyn_cast<Constant>(SO))
2332       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2333
2334     return IC->InsertNewInstBefore(CastInst::Create(
2335           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2336   }
2337
2338   // Figure out if the constant is the left or the right argument.
2339   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2340   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2341
2342   if (Constant *SOC = dyn_cast<Constant>(SO)) {
2343     if (ConstIsRHS)
2344       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2345     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2346   }
2347
2348   Value *Op0 = SO, *Op1 = ConstOperand;
2349   if (!ConstIsRHS)
2350     std::swap(Op0, Op1);
2351   Instruction *New;
2352   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2353     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
2354   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2355     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
2356                           SO->getName()+".cmp");
2357   else {
2358     assert(0 && "Unknown binary instruction type!");
2359     abort();
2360   }
2361   return IC->InsertNewInstBefore(New, I);
2362 }
2363
2364 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2365 // constant as the other operand, try to fold the binary operator into the
2366 // select arguments.  This also works for Cast instructions, which obviously do
2367 // not have a second operand.
2368 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2369                                      InstCombiner *IC) {
2370   // Don't modify shared select instructions
2371   if (!SI->hasOneUse()) return 0;
2372   Value *TV = SI->getOperand(1);
2373   Value *FV = SI->getOperand(2);
2374
2375   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2376     // Bool selects with constant operands can be folded to logical ops.
2377     if (SI->getType() == Type::Int1Ty) return 0;
2378
2379     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2380     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2381
2382     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2383                               SelectFalseVal);
2384   }
2385   return 0;
2386 }
2387
2388
2389 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2390 /// node as operand #0, see if we can fold the instruction into the PHI (which
2391 /// is only possible if all operands to the PHI are constants).
2392 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2393   PHINode *PN = cast<PHINode>(I.getOperand(0));
2394   unsigned NumPHIValues = PN->getNumIncomingValues();
2395   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2396
2397   // Check to see if all of the operands of the PHI are constants.  If there is
2398   // one non-constant value, remember the BB it is.  If there is more than one
2399   // or if *it* is a PHI, bail out.
2400   BasicBlock *NonConstBB = 0;
2401   for (unsigned i = 0; i != NumPHIValues; ++i)
2402     if (!isa<Constant>(PN->getIncomingValue(i))) {
2403       if (NonConstBB) return 0;  // More than one non-const value.
2404       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2405       NonConstBB = PN->getIncomingBlock(i);
2406       
2407       // If the incoming non-constant value is in I's block, we have an infinite
2408       // loop.
2409       if (NonConstBB == I.getParent())
2410         return 0;
2411     }
2412   
2413   // If there is exactly one non-constant value, we can insert a copy of the
2414   // operation in that block.  However, if this is a critical edge, we would be
2415   // inserting the computation one some other paths (e.g. inside a loop).  Only
2416   // do this if the pred block is unconditionally branching into the phi block.
2417   if (NonConstBB) {
2418     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2419     if (!BI || !BI->isUnconditional()) return 0;
2420   }
2421
2422   // Okay, we can do the transformation: create the new PHI node.
2423   PHINode *NewPN = PHINode::Create(I.getType(), "");
2424   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2425   InsertNewInstBefore(NewPN, *PN);
2426   NewPN->takeName(PN);
2427
2428   // Next, add all of the operands to the PHI.
2429   if (I.getNumOperands() == 2) {
2430     Constant *C = cast<Constant>(I.getOperand(1));
2431     for (unsigned i = 0; i != NumPHIValues; ++i) {
2432       Value *InV = 0;
2433       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2434         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2435           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2436         else
2437           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2438       } else {
2439         assert(PN->getIncomingBlock(i) == NonConstBB);
2440         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2441           InV = BinaryOperator::Create(BO->getOpcode(),
2442                                        PN->getIncomingValue(i), C, "phitmp",
2443                                        NonConstBB->getTerminator());
2444         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2445           InV = CmpInst::Create(CI->getOpcode(), 
2446                                 CI->getPredicate(),
2447                                 PN->getIncomingValue(i), C, "phitmp",
2448                                 NonConstBB->getTerminator());
2449         else
2450           assert(0 && "Unknown binop!");
2451         
2452         AddToWorkList(cast<Instruction>(InV));
2453       }
2454       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2455     }
2456   } else { 
2457     CastInst *CI = cast<CastInst>(&I);
2458     const Type *RetTy = CI->getType();
2459     for (unsigned i = 0; i != NumPHIValues; ++i) {
2460       Value *InV;
2461       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2462         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2463       } else {
2464         assert(PN->getIncomingBlock(i) == NonConstBB);
2465         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2466                                I.getType(), "phitmp", 
2467                                NonConstBB->getTerminator());
2468         AddToWorkList(cast<Instruction>(InV));
2469       }
2470       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2471     }
2472   }
2473   return ReplaceInstUsesWith(I, NewPN);
2474 }
2475
2476
2477 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
2478 /// value is never equal to -0.0.
2479 ///
2480 /// Note that this function will need to be revisited when we support nondefault
2481 /// rounding modes!
2482 ///
2483 static bool CannotBeNegativeZero(const Value *V) {
2484   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2485     return !CFP->getValueAPF().isNegZero();
2486
2487   if (const Instruction *I = dyn_cast<Instruction>(V)) {
2488     // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2489     if (I->getOpcode() == Instruction::Add &&
2490         isa<ConstantFP>(I->getOperand(1)) && 
2491         cast<ConstantFP>(I->getOperand(1))->isNullValue())
2492       return true;
2493     
2494     // sitofp and uitofp turn into +0.0 for zero.
2495     if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2496       return true;
2497     
2498     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2499       if (II->getIntrinsicID() == Intrinsic::sqrt)
2500         return CannotBeNegativeZero(II->getOperand(1));
2501     
2502     if (const CallInst *CI = dyn_cast<CallInst>(I))
2503       if (const Function *F = CI->getCalledFunction()) {
2504         if (F->isDeclaration()) {
2505           switch (F->getNameLen()) {
2506           case 3:  // abs(x) != -0.0
2507             if (!strcmp(F->getNameStart(), "abs")) return true;
2508             break;
2509           case 4:  // abs[lf](x) != -0.0
2510             if (!strcmp(F->getNameStart(), "absf")) return true;
2511             if (!strcmp(F->getNameStart(), "absl")) return true;
2512             break;
2513           }
2514         }
2515       }
2516   }
2517   
2518   return false;
2519 }
2520
2521 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2522 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2523 /// This basically requires proving that the add in the original type would not
2524 /// overflow to change the sign bit or have a carry out.
2525 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2526   // There are different heuristics we can use for this.  Here are some simple
2527   // ones.
2528   
2529   // Add has the property that adding any two 2's complement numbers can only 
2530   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2531   // have at least two sign bits, we know that the addition of the two values will
2532   // sign extend fine.
2533   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2534     return true;
2535   
2536   
2537   // If one of the operands only has one non-zero bit, and if the other operand
2538   // has a known-zero bit in a more significant place than it (not including the
2539   // sign bit) the ripple may go up to and fill the zero, but won't change the
2540   // sign.  For example, (X & ~4) + 1.
2541   
2542   // TODO: Implement.
2543   
2544   return false;
2545 }
2546
2547
2548 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2549   bool Changed = SimplifyCommutative(I);
2550   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2551
2552   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2553     // X + undef -> undef
2554     if (isa<UndefValue>(RHS))
2555       return ReplaceInstUsesWith(I, RHS);
2556
2557     // X + 0 --> X
2558     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2559       if (RHSC->isNullValue())
2560         return ReplaceInstUsesWith(I, LHS);
2561     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2562       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2563                               (I.getType())->getValueAPF()))
2564         return ReplaceInstUsesWith(I, LHS);
2565     }
2566
2567     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2568       // X + (signbit) --> X ^ signbit
2569       const APInt& Val = CI->getValue();
2570       uint32_t BitWidth = Val.getBitWidth();
2571       if (Val == APInt::getSignBit(BitWidth))
2572         return BinaryOperator::CreateXor(LHS, RHS);
2573       
2574       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2575       // (X & 254)+1 -> (X&254)|1
2576       if (!isa<VectorType>(I.getType())) {
2577         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2578         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2579                                  KnownZero, KnownOne))
2580           return &I;
2581       }
2582     }
2583
2584     if (isa<PHINode>(LHS))
2585       if (Instruction *NV = FoldOpIntoPhi(I))
2586         return NV;
2587     
2588     ConstantInt *XorRHS = 0;
2589     Value *XorLHS = 0;
2590     if (isa<ConstantInt>(RHSC) &&
2591         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2592       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2593       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2594       
2595       uint32_t Size = TySizeBits / 2;
2596       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2597       APInt CFF80Val(-C0080Val);
2598       do {
2599         if (TySizeBits > Size) {
2600           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2601           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2602           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2603               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2604             // This is a sign extend if the top bits are known zero.
2605             if (!MaskedValueIsZero(XorLHS, 
2606                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2607               Size = 0;  // Not a sign ext, but can't be any others either.
2608             break;
2609           }
2610         }
2611         Size >>= 1;
2612         C0080Val = APIntOps::lshr(C0080Val, Size);
2613         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2614       } while (Size >= 1);
2615       
2616       // FIXME: This shouldn't be necessary. When the backends can handle types
2617       // with funny bit widths then this switch statement should be removed. It
2618       // is just here to get the size of the "middle" type back up to something
2619       // that the back ends can handle.
2620       const Type *MiddleType = 0;
2621       switch (Size) {
2622         default: break;
2623         case 32: MiddleType = Type::Int32Ty; break;
2624         case 16: MiddleType = Type::Int16Ty; break;
2625         case  8: MiddleType = Type::Int8Ty; break;
2626       }
2627       if (MiddleType) {
2628         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2629         InsertNewInstBefore(NewTrunc, I);
2630         return new SExtInst(NewTrunc, I.getType(), I.getName());
2631       }
2632     }
2633   }
2634
2635   // X + X --> X << 1
2636   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2637     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2638
2639     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2640       if (RHSI->getOpcode() == Instruction::Sub)
2641         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2642           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2643     }
2644     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2645       if (LHSI->getOpcode() == Instruction::Sub)
2646         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2647           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2648     }
2649   }
2650
2651   // -A + B  -->  B - A
2652   // -A + -B  -->  -(A + B)
2653   if (Value *LHSV = dyn_castNegVal(LHS)) {
2654     if (LHS->getType()->isIntOrIntVector()) {
2655       if (Value *RHSV = dyn_castNegVal(RHS)) {
2656         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2657         InsertNewInstBefore(NewAdd, I);
2658         return BinaryOperator::CreateNeg(NewAdd);
2659       }
2660     }
2661     
2662     return BinaryOperator::CreateSub(RHS, LHSV);
2663   }
2664
2665   // A + -B  -->  A - B
2666   if (!isa<Constant>(RHS))
2667     if (Value *V = dyn_castNegVal(RHS))
2668       return BinaryOperator::CreateSub(LHS, V);
2669
2670
2671   ConstantInt *C2;
2672   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2673     if (X == RHS)   // X*C + X --> X * (C+1)
2674       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2675
2676     // X*C1 + X*C2 --> X * (C1+C2)
2677     ConstantInt *C1;
2678     if (X == dyn_castFoldableMul(RHS, C1))
2679       return BinaryOperator::CreateMul(X, Add(C1, C2));
2680   }
2681
2682   // X + X*C --> X * (C+1)
2683   if (dyn_castFoldableMul(RHS, C2) == LHS)
2684     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2685
2686   // X + ~X --> -1   since   ~X = -X-1
2687   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2688     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2689   
2690
2691   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2692   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2693     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2694       return R;
2695   
2696   // A+B --> A|B iff A and B have no bits set in common.
2697   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2698     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2699     APInt LHSKnownOne(IT->getBitWidth(), 0);
2700     APInt LHSKnownZero(IT->getBitWidth(), 0);
2701     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2702     if (LHSKnownZero != 0) {
2703       APInt RHSKnownOne(IT->getBitWidth(), 0);
2704       APInt RHSKnownZero(IT->getBitWidth(), 0);
2705       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2706       
2707       // No bits in common -> bitwise or.
2708       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2709         return BinaryOperator::CreateOr(LHS, RHS);
2710     }
2711   }
2712
2713   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2714   if (I.getType()->isIntOrIntVector()) {
2715     Value *W, *X, *Y, *Z;
2716     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2717         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2718       if (W != Y) {
2719         if (W == Z) {
2720           std::swap(Y, Z);
2721         } else if (Y == X) {
2722           std::swap(W, X);
2723         } else if (X == Z) {
2724           std::swap(Y, Z);
2725           std::swap(W, X);
2726         }
2727       }
2728
2729       if (W == Y) {
2730         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2731                                                             LHS->getName()), I);
2732         return BinaryOperator::CreateMul(W, NewAdd);
2733       }
2734     }
2735   }
2736
2737   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2738     Value *X = 0;
2739     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2740       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2741
2742     // (X & FF00) + xx00  -> (X+xx00) & FF00
2743     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2744       Constant *Anded = And(CRHS, C2);
2745       if (Anded == CRHS) {
2746         // See if all bits from the first bit set in the Add RHS up are included
2747         // in the mask.  First, get the rightmost bit.
2748         const APInt& AddRHSV = CRHS->getValue();
2749
2750         // Form a mask of all bits from the lowest bit added through the top.
2751         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2752
2753         // See if the and mask includes all of these bits.
2754         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2755
2756         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2757           // Okay, the xform is safe.  Insert the new add pronto.
2758           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2759                                                             LHS->getName()), I);
2760           return BinaryOperator::CreateAnd(NewAdd, C2);
2761         }
2762       }
2763     }
2764
2765     // Try to fold constant add into select arguments.
2766     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2767       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2768         return R;
2769   }
2770
2771   // add (cast *A to intptrtype) B -> 
2772   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2773   {
2774     CastInst *CI = dyn_cast<CastInst>(LHS);
2775     Value *Other = RHS;
2776     if (!CI) {
2777       CI = dyn_cast<CastInst>(RHS);
2778       Other = LHS;
2779     }
2780     if (CI && CI->getType()->isSized() && 
2781         (CI->getType()->getPrimitiveSizeInBits() == 
2782          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2783         && isa<PointerType>(CI->getOperand(0)->getType())) {
2784       unsigned AS =
2785         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2786       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2787                                       PointerType::get(Type::Int8Ty, AS), I);
2788       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2789       return new PtrToIntInst(I2, CI->getType());
2790     }
2791   }
2792   
2793   // add (select X 0 (sub n A)) A  -->  select X A n
2794   {
2795     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2796     Value *Other = RHS;
2797     if (!SI) {
2798       SI = dyn_cast<SelectInst>(RHS);
2799       Other = LHS;
2800     }
2801     if (SI && SI->hasOneUse()) {
2802       Value *TV = SI->getTrueValue();
2803       Value *FV = SI->getFalseValue();
2804       Value *A, *N;
2805
2806       // Can we fold the add into the argument of the select?
2807       // We check both true and false select arguments for a matching subtract.
2808       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2809           A == Other)  // Fold the add into the true select value.
2810         return SelectInst::Create(SI->getCondition(), N, A);
2811       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2812           A == Other)  // Fold the add into the false select value.
2813         return SelectInst::Create(SI->getCondition(), A, N);
2814     }
2815   }
2816   
2817   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2818   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2819     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2820       return ReplaceInstUsesWith(I, LHS);
2821
2822   // Check for (add (sext x), y), see if we can merge this into an
2823   // integer add followed by a sext.
2824   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2825     // (add (sext x), cst) --> (sext (add x, cst'))
2826     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2827       Constant *CI = 
2828         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2829       if (LHSConv->hasOneUse() &&
2830           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2831           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2832         // Insert the new, smaller add.
2833         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2834                                                         CI, "addconv");
2835         InsertNewInstBefore(NewAdd, I);
2836         return new SExtInst(NewAdd, I.getType());
2837       }
2838     }
2839     
2840     // (add (sext x), (sext y)) --> (sext (add int x, y))
2841     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2842       // Only do this if x/y have the same type, if at last one of them has a
2843       // single use (so we don't increase the number of sexts), and if the
2844       // integer add will not overflow.
2845       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2846           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2847           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2848                                    RHSConv->getOperand(0))) {
2849         // Insert the new integer add.
2850         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2851                                                         RHSConv->getOperand(0),
2852                                                         "addconv");
2853         InsertNewInstBefore(NewAdd, I);
2854         return new SExtInst(NewAdd, I.getType());
2855       }
2856     }
2857   }
2858   
2859   // Check for (add double (sitofp x), y), see if we can merge this into an
2860   // integer add followed by a promotion.
2861   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2862     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2863     // ... if the constant fits in the integer value.  This is useful for things
2864     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2865     // requires a constant pool load, and generally allows the add to be better
2866     // instcombined.
2867     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2868       Constant *CI = 
2869       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2870       if (LHSConv->hasOneUse() &&
2871           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2872           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2873         // Insert the new integer add.
2874         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2875                                                         CI, "addconv");
2876         InsertNewInstBefore(NewAdd, I);
2877         return new SIToFPInst(NewAdd, I.getType());
2878       }
2879     }
2880     
2881     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2882     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2883       // Only do this if x/y have the same type, if at last one of them has a
2884       // single use (so we don't increase the number of int->fp conversions),
2885       // and if the integer add will not overflow.
2886       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2887           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2888           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2889                                    RHSConv->getOperand(0))) {
2890         // Insert the new integer add.
2891         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2892                                                         RHSConv->getOperand(0),
2893                                                         "addconv");
2894         InsertNewInstBefore(NewAdd, I);
2895         return new SIToFPInst(NewAdd, I.getType());
2896       }
2897     }
2898   }
2899   
2900   return Changed ? &I : 0;
2901 }
2902
2903 // isSignBit - Return true if the value represented by the constant only has the
2904 // highest order bit set.
2905 static bool isSignBit(ConstantInt *CI) {
2906   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2907   return CI->getValue() == APInt::getSignBit(NumBits);
2908 }
2909
2910 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2911   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2912
2913   if (Op0 == Op1)         // sub X, X  -> 0
2914     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2915
2916   // If this is a 'B = x-(-A)', change to B = x+A...
2917   if (Value *V = dyn_castNegVal(Op1))
2918     return BinaryOperator::CreateAdd(Op0, V);
2919
2920   if (isa<UndefValue>(Op0))
2921     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2922   if (isa<UndefValue>(Op1))
2923     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2924
2925   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2926     // Replace (-1 - A) with (~A)...
2927     if (C->isAllOnesValue())
2928       return BinaryOperator::CreateNot(Op1);
2929
2930     // C - ~X == X + (1+C)
2931     Value *X = 0;
2932     if (match(Op1, m_Not(m_Value(X))))
2933       return BinaryOperator::CreateAdd(X, AddOne(C));
2934
2935     // -(X >>u 31) -> (X >>s 31)
2936     // -(X >>s 31) -> (X >>u 31)
2937     if (C->isZero()) {
2938       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2939         if (SI->getOpcode() == Instruction::LShr) {
2940           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2941             // Check to see if we are shifting out everything but the sign bit.
2942             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2943                 SI->getType()->getPrimitiveSizeInBits()-1) {
2944               // Ok, the transformation is safe.  Insert AShr.
2945               return BinaryOperator::Create(Instruction::AShr, 
2946                                           SI->getOperand(0), CU, SI->getName());
2947             }
2948           }
2949         }
2950         else if (SI->getOpcode() == Instruction::AShr) {
2951           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2952             // Check to see if we are shifting out everything but the sign bit.
2953             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2954                 SI->getType()->getPrimitiveSizeInBits()-1) {
2955               // Ok, the transformation is safe.  Insert LShr. 
2956               return BinaryOperator::CreateLShr(
2957                                           SI->getOperand(0), CU, SI->getName());
2958             }
2959           }
2960         }
2961       }
2962     }
2963
2964     // Try to fold constant sub into select arguments.
2965     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2966       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2967         return R;
2968
2969     if (isa<PHINode>(Op0))
2970       if (Instruction *NV = FoldOpIntoPhi(I))
2971         return NV;
2972   }
2973
2974   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2975     if (Op1I->getOpcode() == Instruction::Add &&
2976         !Op0->getType()->isFPOrFPVector()) {
2977       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2978         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2979       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2980         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2981       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2982         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2983           // C1-(X+C2) --> (C1-C2)-X
2984           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2985                                            Op1I->getOperand(0));
2986       }
2987     }
2988
2989     if (Op1I->hasOneUse()) {
2990       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2991       // is not used by anyone else...
2992       //
2993       if (Op1I->getOpcode() == Instruction::Sub &&
2994           !Op1I->getType()->isFPOrFPVector()) {
2995         // Swap the two operands of the subexpr...
2996         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2997         Op1I->setOperand(0, IIOp1);
2998         Op1I->setOperand(1, IIOp0);
2999
3000         // Create the new top level add instruction...
3001         return BinaryOperator::CreateAdd(Op0, Op1);
3002       }
3003
3004       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3005       //
3006       if (Op1I->getOpcode() == Instruction::And &&
3007           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3008         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3009
3010         Value *NewNot =
3011           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3012         return BinaryOperator::CreateAnd(Op0, NewNot);
3013       }
3014
3015       // 0 - (X sdiv C)  -> (X sdiv -C)
3016       if (Op1I->getOpcode() == Instruction::SDiv)
3017         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3018           if (CSI->isZero())
3019             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
3020               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
3021                                                ConstantExpr::getNeg(DivRHS));
3022
3023       // X - X*C --> X * (1-C)
3024       ConstantInt *C2 = 0;
3025       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
3026         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
3027         return BinaryOperator::CreateMul(Op0, CP1);
3028       }
3029
3030       // X - ((X / Y) * Y) --> X % Y
3031       if (Op1I->getOpcode() == Instruction::Mul)
3032         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3033           if (Op0 == I->getOperand(0) &&
3034               Op1I->getOperand(1) == I->getOperand(1)) {
3035             if (I->getOpcode() == Instruction::SDiv)
3036               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
3037             if (I->getOpcode() == Instruction::UDiv)
3038               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
3039           }
3040     }
3041   }
3042
3043   if (!Op0->getType()->isFPOrFPVector())
3044     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3045       if (Op0I->getOpcode() == Instruction::Add) {
3046         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
3047           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3048         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
3049           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3050       } else if (Op0I->getOpcode() == Instruction::Sub) {
3051         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
3052           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
3053       }
3054     }
3055
3056   ConstantInt *C1;
3057   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
3058     if (X == Op1)  // X*C - X --> X * (C-1)
3059       return BinaryOperator::CreateMul(Op1, SubOne(C1));
3060
3061     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
3062     if (X == dyn_castFoldableMul(Op1, C2))
3063       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
3064   }
3065   return 0;
3066 }
3067
3068 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
3069 /// comparison only checks the sign bit.  If it only checks the sign bit, set
3070 /// TrueIfSigned if the result of the comparison is true when the input value is
3071 /// signed.
3072 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3073                            bool &TrueIfSigned) {
3074   switch (pred) {
3075   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
3076     TrueIfSigned = true;
3077     return RHS->isZero();
3078   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
3079     TrueIfSigned = true;
3080     return RHS->isAllOnesValue();
3081   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
3082     TrueIfSigned = false;
3083     return RHS->isAllOnesValue();
3084   case ICmpInst::ICMP_UGT:
3085     // True if LHS u> RHS and RHS == high-bit-mask - 1
3086     TrueIfSigned = true;
3087     return RHS->getValue() ==
3088       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3089   case ICmpInst::ICMP_UGE: 
3090     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3091     TrueIfSigned = true;
3092     return RHS->getValue() == 
3093       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
3094   default:
3095     return false;
3096   }
3097 }
3098
3099 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3100   bool Changed = SimplifyCommutative(I);
3101   Value *Op0 = I.getOperand(0);
3102
3103   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
3104     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3105
3106   // Simplify mul instructions with a constant RHS...
3107   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3108     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3109
3110       // ((X << C1)*C2) == (X * (C2 << C1))
3111       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3112         if (SI->getOpcode() == Instruction::Shl)
3113           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
3114             return BinaryOperator::CreateMul(SI->getOperand(0),
3115                                              ConstantExpr::getShl(CI, ShOp));
3116
3117       if (CI->isZero())
3118         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
3119       if (CI->equalsInt(1))                  // X * 1  == X
3120         return ReplaceInstUsesWith(I, Op0);
3121       if (CI->isAllOnesValue())              // X * -1 == 0 - X
3122         return BinaryOperator::CreateNeg(Op0, I.getName());
3123
3124       const APInt& Val = cast<ConstantInt>(CI)->getValue();
3125       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
3126         return BinaryOperator::CreateShl(Op0,
3127                  ConstantInt::get(Op0->getType(), Val.logBase2()));
3128       }
3129     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
3130       if (Op1F->isNullValue())
3131         return ReplaceInstUsesWith(I, Op1);
3132
3133       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
3134       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3135       // We need a better interface for long double here.
3136       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3137         if (Op1F->isExactlyValue(1.0))
3138           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
3139     }
3140     
3141     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3142       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
3143           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
3144         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
3145         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
3146                                                      Op1, "tmp");
3147         InsertNewInstBefore(Add, I);
3148         Value *C1C2 = ConstantExpr::getMul(Op1, 
3149                                            cast<Constant>(Op0I->getOperand(1)));
3150         return BinaryOperator::CreateAdd(Add, C1C2);
3151         
3152       }
3153
3154     // Try to fold constant mul into select arguments.
3155     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3156       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3157         return R;
3158
3159     if (isa<PHINode>(Op0))
3160       if (Instruction *NV = FoldOpIntoPhi(I))
3161         return NV;
3162   }
3163
3164   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3165     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
3166       return BinaryOperator::CreateMul(Op0v, Op1v);
3167
3168   // If one of the operands of the multiply is a cast from a boolean value, then
3169   // we know the bool is either zero or one, so this is a 'masking' multiply.
3170   // See if we can simplify things based on how the boolean was originally
3171   // formed.
3172   CastInst *BoolCast = 0;
3173   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
3174     if (CI->getOperand(0)->getType() == Type::Int1Ty)
3175       BoolCast = CI;
3176   if (!BoolCast)
3177     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
3178       if (CI->getOperand(0)->getType() == Type::Int1Ty)
3179         BoolCast = CI;
3180   if (BoolCast) {
3181     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
3182       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3183       const Type *SCOpTy = SCIOp0->getType();
3184       bool TIS = false;
3185       
3186       // If the icmp is true iff the sign bit of X is set, then convert this
3187       // multiply into a shift/and combination.
3188       if (isa<ConstantInt>(SCIOp1) &&
3189           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3190           TIS) {
3191         // Shift the X value right to turn it into "all signbits".
3192         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
3193                                           SCOpTy->getPrimitiveSizeInBits()-1);
3194         Value *V =
3195           InsertNewInstBefore(
3196             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
3197                                             BoolCast->getOperand(0)->getName()+
3198                                             ".mask"), I);
3199
3200         // If the multiply type is not the same as the source type, sign extend
3201         // or truncate to the multiply type.
3202         if (I.getType() != V->getType()) {
3203           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3204           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
3205           Instruction::CastOps opcode = 
3206             (SrcBits == DstBits ? Instruction::BitCast : 
3207              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3208           V = InsertCastBefore(opcode, V, I.getType(), I);
3209         }
3210
3211         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
3212         return BinaryOperator::CreateAnd(V, OtherOp);
3213       }
3214     }
3215   }
3216
3217   return Changed ? &I : 0;
3218 }
3219
3220 /// This function implements the transforms on div instructions that work
3221 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3222 /// used by the visitors to those instructions.
3223 /// @brief Transforms common to all three div instructions
3224 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3225   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3226
3227   // undef / X -> 0        for integer.
3228   // undef / X -> undef    for FP (the undef could be a snan).
3229   if (isa<UndefValue>(Op0)) {
3230     if (Op0->getType()->isFPOrFPVector())
3231       return ReplaceInstUsesWith(I, Op0);
3232     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3233   }
3234
3235   // X / undef -> undef
3236   if (isa<UndefValue>(Op1))
3237     return ReplaceInstUsesWith(I, Op1);
3238
3239   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3240   // This does not apply for fdiv.
3241   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3242     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
3243     // the same basic block, then we replace the select with Y, and the
3244     // condition of the select with false (if the cond value is in the same BB).
3245     // If the select has uses other than the div, this allows them to be
3246     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3247     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
3248       if (ST->isNullValue()) {
3249         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3250         if (CondI && CondI->getParent() == I.getParent())
3251           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3252         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3253           I.setOperand(1, SI->getOperand(2));
3254         else
3255           UpdateValueUsesWith(SI, SI->getOperand(2));
3256         return &I;
3257       }
3258
3259     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3260     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
3261       if (ST->isNullValue()) {
3262         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3263         if (CondI && CondI->getParent() == I.getParent())
3264           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3265         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3266           I.setOperand(1, SI->getOperand(1));
3267         else
3268           UpdateValueUsesWith(SI, SI->getOperand(1));
3269         return &I;
3270       }
3271   }
3272
3273   return 0;
3274 }
3275
3276 /// This function implements the transforms common to both integer division
3277 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3278 /// division instructions.
3279 /// @brief Common integer divide transforms
3280 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3281   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3282
3283   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3284   if (Op0 == Op1) {
3285     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3286       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
3287       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3288       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3289     }
3290
3291     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
3292     return ReplaceInstUsesWith(I, CI);
3293   }
3294   
3295   if (Instruction *Common = commonDivTransforms(I))
3296     return Common;
3297
3298   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3299     // div X, 1 == X
3300     if (RHS->equalsInt(1))
3301       return ReplaceInstUsesWith(I, Op0);
3302
3303     // (X / C1) / C2  -> X / (C1*C2)
3304     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3305       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3306         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3307           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3308             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3309           else 
3310             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3311                                           Multiply(RHS, LHSRHS));
3312         }
3313
3314     if (!RHS->isZero()) { // avoid X udiv 0
3315       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3316         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3317           return R;
3318       if (isa<PHINode>(Op0))
3319         if (Instruction *NV = FoldOpIntoPhi(I))
3320           return NV;
3321     }
3322   }
3323
3324   // 0 / X == 0, we don't need to preserve faults!
3325   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3326     if (LHS->equalsInt(0))
3327       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3328
3329   return 0;
3330 }
3331
3332 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3333   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3334
3335   // Handle the integer div common cases
3336   if (Instruction *Common = commonIDivTransforms(I))
3337     return Common;
3338
3339   // X udiv C^2 -> X >> C
3340   // Check to see if this is an unsigned division with an exact power of 2,
3341   // if so, convert to a right shift.
3342   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3343     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3344       return BinaryOperator::CreateLShr(Op0, 
3345                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3346   }
3347
3348   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3349   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3350     if (RHSI->getOpcode() == Instruction::Shl &&
3351         isa<ConstantInt>(RHSI->getOperand(0))) {
3352       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3353       if (C1.isPowerOf2()) {
3354         Value *N = RHSI->getOperand(1);
3355         const Type *NTy = N->getType();
3356         if (uint32_t C2 = C1.logBase2()) {
3357           Constant *C2V = ConstantInt::get(NTy, C2);
3358           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3359         }
3360         return BinaryOperator::CreateLShr(Op0, N);
3361       }
3362     }
3363   }
3364   
3365   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3366   // where C1&C2 are powers of two.
3367   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3368     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3369       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3370         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3371         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3372           // Compute the shift amounts
3373           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3374           // Construct the "on true" case of the select
3375           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3376           Instruction *TSI = BinaryOperator::CreateLShr(
3377                                                  Op0, TC, SI->getName()+".t");
3378           TSI = InsertNewInstBefore(TSI, I);
3379   
3380           // Construct the "on false" case of the select
3381           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3382           Instruction *FSI = BinaryOperator::CreateLShr(
3383                                                  Op0, FC, SI->getName()+".f");
3384           FSI = InsertNewInstBefore(FSI, I);
3385
3386           // construct the select instruction and return it.
3387           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3388         }
3389       }
3390   return 0;
3391 }
3392
3393 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3394   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3395
3396   // Handle the integer div common cases
3397   if (Instruction *Common = commonIDivTransforms(I))
3398     return Common;
3399
3400   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3401     // sdiv X, -1 == -X
3402     if (RHS->isAllOnesValue())
3403       return BinaryOperator::CreateNeg(Op0);
3404
3405     // -X/C -> X/-C
3406     if (Value *LHSNeg = dyn_castNegVal(Op0))
3407       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3408   }
3409
3410   // If the sign bits of both operands are zero (i.e. we can prove they are
3411   // unsigned inputs), turn this into a udiv.
3412   if (I.getType()->isInteger()) {
3413     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3414     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3415       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3416       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3417     }
3418   }      
3419   
3420   return 0;
3421 }
3422
3423 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3424   return commonDivTransforms(I);
3425 }
3426
3427 /// This function implements the transforms on rem instructions that work
3428 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3429 /// is used by the visitors to those instructions.
3430 /// @brief Transforms common to all three rem instructions
3431 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3432   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3433
3434   // 0 % X == 0 for integer, we don't need to preserve faults!
3435   if (Constant *LHS = dyn_cast<Constant>(Op0))
3436     if (LHS->isNullValue())
3437       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3438
3439   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3440     if (I.getType()->isFPOrFPVector())
3441       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3442     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3443   }
3444   if (isa<UndefValue>(Op1))
3445     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3446
3447   // Handle cases involving: rem X, (select Cond, Y, Z)
3448   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3449     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
3450     // the same basic block, then we replace the select with Y, and the
3451     // condition of the select with false (if the cond value is in the same
3452     // BB).  If the select has uses other than the div, this allows them to be
3453     // simplified also.
3454     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3455       if (ST->isNullValue()) {
3456         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3457         if (CondI && CondI->getParent() == I.getParent())
3458           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3459         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3460           I.setOperand(1, SI->getOperand(2));
3461         else
3462           UpdateValueUsesWith(SI, SI->getOperand(2));
3463         return &I;
3464       }
3465     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3466     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3467       if (ST->isNullValue()) {
3468         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3469         if (CondI && CondI->getParent() == I.getParent())
3470           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3471         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3472           I.setOperand(1, SI->getOperand(1));
3473         else
3474           UpdateValueUsesWith(SI, SI->getOperand(1));
3475         return &I;
3476       }
3477   }
3478
3479   return 0;
3480 }
3481
3482 /// This function implements the transforms common to both integer remainder
3483 /// instructions (urem and srem). It is called by the visitors to those integer
3484 /// remainder instructions.
3485 /// @brief Common integer remainder transforms
3486 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3487   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3488
3489   if (Instruction *common = commonRemTransforms(I))
3490     return common;
3491
3492   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3493     // X % 0 == undef, we don't need to preserve faults!
3494     if (RHS->equalsInt(0))
3495       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3496     
3497     if (RHS->equalsInt(1))  // X % 1 == 0
3498       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3499
3500     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3501       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3502         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3503           return R;
3504       } else if (isa<PHINode>(Op0I)) {
3505         if (Instruction *NV = FoldOpIntoPhi(I))
3506           return NV;
3507       }
3508
3509       // See if we can fold away this rem instruction.
3510       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3511       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3512       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3513                                KnownZero, KnownOne))
3514         return &I;
3515     }
3516   }
3517
3518   return 0;
3519 }
3520
3521 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3522   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3523
3524   if (Instruction *common = commonIRemTransforms(I))
3525     return common;
3526   
3527   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3528     // X urem C^2 -> X and C
3529     // Check to see if this is an unsigned remainder with an exact power of 2,
3530     // if so, convert to a bitwise and.
3531     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3532       if (C->getValue().isPowerOf2())
3533         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3534   }
3535
3536   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3537     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3538     if (RHSI->getOpcode() == Instruction::Shl &&
3539         isa<ConstantInt>(RHSI->getOperand(0))) {
3540       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3541         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3542         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3543                                                                    "tmp"), I);
3544         return BinaryOperator::CreateAnd(Op0, Add);
3545       }
3546     }
3547   }
3548
3549   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3550   // where C1&C2 are powers of two.
3551   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3552     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3553       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3554         // STO == 0 and SFO == 0 handled above.
3555         if ((STO->getValue().isPowerOf2()) && 
3556             (SFO->getValue().isPowerOf2())) {
3557           Value *TrueAnd = InsertNewInstBefore(
3558             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3559           Value *FalseAnd = InsertNewInstBefore(
3560             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3561           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3562         }
3563       }
3564   }
3565   
3566   return 0;
3567 }
3568
3569 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3570   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3571
3572   // Handle the integer rem common cases
3573   if (Instruction *common = commonIRemTransforms(I))
3574     return common;
3575   
3576   if (Value *RHSNeg = dyn_castNegVal(Op1))
3577     if (!isa<ConstantInt>(RHSNeg) || 
3578         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3579       // X % -Y -> X % Y
3580       AddUsesToWorkList(I);
3581       I.setOperand(1, RHSNeg);
3582       return &I;
3583     }
3584  
3585   // If the sign bits of both operands are zero (i.e. we can prove they are
3586   // unsigned inputs), turn this into a urem.
3587   if (I.getType()->isInteger()) {
3588     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3589     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3590       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3591       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3592     }
3593   }
3594
3595   return 0;
3596 }
3597
3598 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3599   return commonRemTransforms(I);
3600 }
3601
3602 // isMaxValueMinusOne - return true if this is Max-1
3603 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3604   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3605   if (!isSigned)
3606     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3607   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3608 }
3609
3610 // isMinValuePlusOne - return true if this is Min+1
3611 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3612   if (!isSigned)
3613     return C->getValue() == 1; // unsigned
3614     
3615   // Calculate 1111111111000000000000
3616   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3617   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3618 }
3619
3620 // isOneBitSet - Return true if there is exactly one bit set in the specified
3621 // constant.
3622 static bool isOneBitSet(const ConstantInt *CI) {
3623   return CI->getValue().isPowerOf2();
3624 }
3625
3626 // isHighOnes - Return true if the constant is of the form 1+0+.
3627 // This is the same as lowones(~X).
3628 static bool isHighOnes(const ConstantInt *CI) {
3629   return (~CI->getValue() + 1).isPowerOf2();
3630 }
3631
3632 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3633 /// are carefully arranged to allow folding of expressions such as:
3634 ///
3635 ///      (A < B) | (A > B) --> (A != B)
3636 ///
3637 /// Note that this is only valid if the first and second predicates have the
3638 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3639 ///
3640 /// Three bits are used to represent the condition, as follows:
3641 ///   0  A > B
3642 ///   1  A == B
3643 ///   2  A < B
3644 ///
3645 /// <=>  Value  Definition
3646 /// 000     0   Always false
3647 /// 001     1   A >  B
3648 /// 010     2   A == B
3649 /// 011     3   A >= B
3650 /// 100     4   A <  B
3651 /// 101     5   A != B
3652 /// 110     6   A <= B
3653 /// 111     7   Always true
3654 ///  
3655 static unsigned getICmpCode(const ICmpInst *ICI) {
3656   switch (ICI->getPredicate()) {
3657     // False -> 0
3658   case ICmpInst::ICMP_UGT: return 1;  // 001
3659   case ICmpInst::ICMP_SGT: return 1;  // 001
3660   case ICmpInst::ICMP_EQ:  return 2;  // 010
3661   case ICmpInst::ICMP_UGE: return 3;  // 011
3662   case ICmpInst::ICMP_SGE: return 3;  // 011
3663   case ICmpInst::ICMP_ULT: return 4;  // 100
3664   case ICmpInst::ICMP_SLT: return 4;  // 100
3665   case ICmpInst::ICMP_NE:  return 5;  // 101
3666   case ICmpInst::ICMP_ULE: return 6;  // 110
3667   case ICmpInst::ICMP_SLE: return 6;  // 110
3668     // True -> 7
3669   default:
3670     assert(0 && "Invalid ICmp predicate!");
3671     return 0;
3672   }
3673 }
3674
3675 /// getICmpValue - This is the complement of getICmpCode, which turns an
3676 /// opcode and two operands into either a constant true or false, or a brand 
3677 /// new ICmp instruction. The sign is passed in to determine which kind
3678 /// of predicate to use in new icmp instructions.
3679 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3680   switch (code) {
3681   default: assert(0 && "Illegal ICmp code!");
3682   case  0: return ConstantInt::getFalse();
3683   case  1: 
3684     if (sign)
3685       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3686     else
3687       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3688   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3689   case  3: 
3690     if (sign)
3691       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3692     else
3693       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3694   case  4: 
3695     if (sign)
3696       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3697     else
3698       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3699   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3700   case  6: 
3701     if (sign)
3702       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3703     else
3704       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3705   case  7: return ConstantInt::getTrue();
3706   }
3707 }
3708
3709 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3710   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3711     (ICmpInst::isSignedPredicate(p1) && 
3712      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3713     (ICmpInst::isSignedPredicate(p2) && 
3714      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3715 }
3716
3717 namespace { 
3718 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3719 struct FoldICmpLogical {
3720   InstCombiner &IC;
3721   Value *LHS, *RHS;
3722   ICmpInst::Predicate pred;
3723   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3724     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3725       pred(ICI->getPredicate()) {}
3726   bool shouldApply(Value *V) const {
3727     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3728       if (PredicatesFoldable(pred, ICI->getPredicate()))
3729         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3730                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3731     return false;
3732   }
3733   Instruction *apply(Instruction &Log) const {
3734     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3735     if (ICI->getOperand(0) != LHS) {
3736       assert(ICI->getOperand(1) == LHS);
3737       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3738     }
3739
3740     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3741     unsigned LHSCode = getICmpCode(ICI);
3742     unsigned RHSCode = getICmpCode(RHSICI);
3743     unsigned Code;
3744     switch (Log.getOpcode()) {
3745     case Instruction::And: Code = LHSCode & RHSCode; break;
3746     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3747     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3748     default: assert(0 && "Illegal logical opcode!"); return 0;
3749     }
3750
3751     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3752                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3753       
3754     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3755     if (Instruction *I = dyn_cast<Instruction>(RV))
3756       return I;
3757     // Otherwise, it's a constant boolean value...
3758     return IC.ReplaceInstUsesWith(Log, RV);
3759   }
3760 };
3761 } // end anonymous namespace
3762
3763 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3764 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3765 // guaranteed to be a binary operator.
3766 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3767                                     ConstantInt *OpRHS,
3768                                     ConstantInt *AndRHS,
3769                                     BinaryOperator &TheAnd) {
3770   Value *X = Op->getOperand(0);
3771   Constant *Together = 0;
3772   if (!Op->isShift())
3773     Together = And(AndRHS, OpRHS);
3774
3775   switch (Op->getOpcode()) {
3776   case Instruction::Xor:
3777     if (Op->hasOneUse()) {
3778       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3779       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3780       InsertNewInstBefore(And, TheAnd);
3781       And->takeName(Op);
3782       return BinaryOperator::CreateXor(And, Together);
3783     }
3784     break;
3785   case Instruction::Or:
3786     if (Together == AndRHS) // (X | C) & C --> C
3787       return ReplaceInstUsesWith(TheAnd, AndRHS);
3788
3789     if (Op->hasOneUse() && Together != OpRHS) {
3790       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3791       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3792       InsertNewInstBefore(Or, TheAnd);
3793       Or->takeName(Op);
3794       return BinaryOperator::CreateAnd(Or, AndRHS);
3795     }
3796     break;
3797   case Instruction::Add:
3798     if (Op->hasOneUse()) {
3799       // Adding a one to a single bit bit-field should be turned into an XOR
3800       // of the bit.  First thing to check is to see if this AND is with a
3801       // single bit constant.
3802       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3803
3804       // If there is only one bit set...
3805       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3806         // Ok, at this point, we know that we are masking the result of the
3807         // ADD down to exactly one bit.  If the constant we are adding has
3808         // no bits set below this bit, then we can eliminate the ADD.
3809         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3810
3811         // Check to see if any bits below the one bit set in AndRHSV are set.
3812         if ((AddRHS & (AndRHSV-1)) == 0) {
3813           // If not, the only thing that can effect the output of the AND is
3814           // the bit specified by AndRHSV.  If that bit is set, the effect of
3815           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3816           // no effect.
3817           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3818             TheAnd.setOperand(0, X);
3819             return &TheAnd;
3820           } else {
3821             // Pull the XOR out of the AND.
3822             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3823             InsertNewInstBefore(NewAnd, TheAnd);
3824             NewAnd->takeName(Op);
3825             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3826           }
3827         }
3828       }
3829     }
3830     break;
3831
3832   case Instruction::Shl: {
3833     // We know that the AND will not produce any of the bits shifted in, so if
3834     // the anded constant includes them, clear them now!
3835     //
3836     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3837     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3838     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3839     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3840
3841     if (CI->getValue() == ShlMask) { 
3842     // Masking out bits that the shift already masks
3843       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3844     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3845       TheAnd.setOperand(1, CI);
3846       return &TheAnd;
3847     }
3848     break;
3849   }
3850   case Instruction::LShr:
3851   {
3852     // We know that the AND will not produce any of the bits shifted in, so if
3853     // the anded constant includes them, clear them now!  This only applies to
3854     // unsigned shifts, because a signed shr may bring in set bits!
3855     //
3856     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3857     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3858     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3859     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3860
3861     if (CI->getValue() == ShrMask) {   
3862     // Masking out bits that the shift already masks.
3863       return ReplaceInstUsesWith(TheAnd, Op);
3864     } else if (CI != AndRHS) {
3865       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3866       return &TheAnd;
3867     }
3868     break;
3869   }
3870   case Instruction::AShr:
3871     // Signed shr.
3872     // See if this is shifting in some sign extension, then masking it out
3873     // with an and.
3874     if (Op->hasOneUse()) {
3875       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3876       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3877       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3878       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3879       if (C == AndRHS) {          // Masking out bits shifted in.
3880         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3881         // Make the argument unsigned.
3882         Value *ShVal = Op->getOperand(0);
3883         ShVal = InsertNewInstBefore(
3884             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3885                                    Op->getName()), TheAnd);
3886         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3887       }
3888     }
3889     break;
3890   }
3891   return 0;
3892 }
3893
3894
3895 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3896 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3897 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3898 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3899 /// insert new instructions.
3900 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3901                                            bool isSigned, bool Inside, 
3902                                            Instruction &IB) {
3903   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3904             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3905          "Lo is not <= Hi in range emission code!");
3906     
3907   if (Inside) {
3908     if (Lo == Hi)  // Trivially false.
3909       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3910
3911     // V >= Min && V < Hi --> V < Hi
3912     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3913       ICmpInst::Predicate pred = (isSigned ? 
3914         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3915       return new ICmpInst(pred, V, Hi);
3916     }
3917
3918     // Emit V-Lo <u Hi-Lo
3919     Constant *NegLo = ConstantExpr::getNeg(Lo);
3920     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3921     InsertNewInstBefore(Add, IB);
3922     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3923     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3924   }
3925
3926   if (Lo == Hi)  // Trivially true.
3927     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3928
3929   // V < Min || V >= Hi -> V > Hi-1
3930   Hi = SubOne(cast<ConstantInt>(Hi));
3931   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3932     ICmpInst::Predicate pred = (isSigned ? 
3933         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3934     return new ICmpInst(pred, V, Hi);
3935   }
3936
3937   // Emit V-Lo >u Hi-1-Lo
3938   // Note that Hi has already had one subtracted from it, above.
3939   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3940   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3941   InsertNewInstBefore(Add, IB);
3942   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3943   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3944 }
3945
3946 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3947 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3948 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3949 // not, since all 1s are not contiguous.
3950 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3951   const APInt& V = Val->getValue();
3952   uint32_t BitWidth = Val->getType()->getBitWidth();
3953   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3954
3955   // look for the first zero bit after the run of ones
3956   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3957   // look for the first non-zero bit
3958   ME = V.getActiveBits(); 
3959   return true;
3960 }
3961
3962 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3963 /// where isSub determines whether the operator is a sub.  If we can fold one of
3964 /// the following xforms:
3965 /// 
3966 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3967 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3968 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3969 ///
3970 /// return (A +/- B).
3971 ///
3972 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3973                                         ConstantInt *Mask, bool isSub,
3974                                         Instruction &I) {
3975   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3976   if (!LHSI || LHSI->getNumOperands() != 2 ||
3977       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3978
3979   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3980
3981   switch (LHSI->getOpcode()) {
3982   default: return 0;
3983   case Instruction::And:
3984     if (And(N, Mask) == Mask) {
3985       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3986       if ((Mask->getValue().countLeadingZeros() + 
3987            Mask->getValue().countPopulation()) == 
3988           Mask->getValue().getBitWidth())
3989         break;
3990
3991       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3992       // part, we don't need any explicit masks to take them out of A.  If that
3993       // is all N is, ignore it.
3994       uint32_t MB = 0, ME = 0;
3995       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3996         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3997         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3998         if (MaskedValueIsZero(RHS, Mask))
3999           break;
4000       }
4001     }
4002     return 0;
4003   case Instruction::Or:
4004   case Instruction::Xor:
4005     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4006     if ((Mask->getValue().countLeadingZeros() + 
4007          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4008         && And(N, Mask)->isZero())
4009       break;
4010     return 0;
4011   }
4012   
4013   Instruction *New;
4014   if (isSub)
4015     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
4016   else
4017     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
4018   return InsertNewInstBefore(New, I);
4019 }
4020
4021 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4022   bool Changed = SimplifyCommutative(I);
4023   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4024
4025   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4026     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4027
4028   // and X, X = X
4029   if (Op0 == Op1)
4030     return ReplaceInstUsesWith(I, Op1);
4031
4032   // See if we can simplify any instructions used by the instruction whose sole 
4033   // purpose is to compute bits we don't care about.
4034   if (!isa<VectorType>(I.getType())) {
4035     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4036     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4037     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4038                              KnownZero, KnownOne))
4039       return &I;
4040   } else {
4041     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4042       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4043         return ReplaceInstUsesWith(I, I.getOperand(0));
4044     } else if (isa<ConstantAggregateZero>(Op1)) {
4045       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4046     }
4047   }
4048   
4049   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4050     const APInt& AndRHSMask = AndRHS->getValue();
4051     APInt NotAndRHS(~AndRHSMask);
4052
4053     // Optimize a variety of ((val OP C1) & C2) combinations...
4054     if (isa<BinaryOperator>(Op0)) {
4055       Instruction *Op0I = cast<Instruction>(Op0);
4056       Value *Op0LHS = Op0I->getOperand(0);
4057       Value *Op0RHS = Op0I->getOperand(1);
4058       switch (Op0I->getOpcode()) {
4059       case Instruction::Xor:
4060       case Instruction::Or:
4061         // If the mask is only needed on one incoming arm, push it up.
4062         if (Op0I->hasOneUse()) {
4063           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4064             // Not masking anything out for the LHS, move to RHS.
4065             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4066                                                    Op0RHS->getName()+".masked");
4067             InsertNewInstBefore(NewRHS, I);
4068             return BinaryOperator::Create(
4069                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4070           }
4071           if (!isa<Constant>(Op0RHS) &&
4072               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4073             // Not masking anything out for the RHS, move to LHS.
4074             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4075                                                    Op0LHS->getName()+".masked");
4076             InsertNewInstBefore(NewLHS, I);
4077             return BinaryOperator::Create(
4078                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4079           }
4080         }
4081
4082         break;
4083       case Instruction::Add:
4084         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4085         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4086         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4087         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4088           return BinaryOperator::CreateAnd(V, AndRHS);
4089         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4090           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4091         break;
4092
4093       case Instruction::Sub:
4094         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4095         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4096         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4097         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4098           return BinaryOperator::CreateAnd(V, AndRHS);
4099         break;
4100       }
4101
4102       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4103         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4104           return Res;
4105     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4106       // If this is an integer truncation or change from signed-to-unsigned, and
4107       // if the source is an and/or with immediate, transform it.  This
4108       // frequently occurs for bitfield accesses.
4109       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4110         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4111             CastOp->getNumOperands() == 2)
4112           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4113             if (CastOp->getOpcode() == Instruction::And) {
4114               // Change: and (cast (and X, C1) to T), C2
4115               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4116               // This will fold the two constants together, which may allow 
4117               // other simplifications.
4118               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4119                 CastOp->getOperand(0), I.getType(), 
4120                 CastOp->getName()+".shrunk");
4121               NewCast = InsertNewInstBefore(NewCast, I);
4122               // trunc_or_bitcast(C1)&C2
4123               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4124               C3 = ConstantExpr::getAnd(C3, AndRHS);
4125               return BinaryOperator::CreateAnd(NewCast, C3);
4126             } else if (CastOp->getOpcode() == Instruction::Or) {
4127               // Change: and (cast (or X, C1) to T), C2
4128               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4129               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4130               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
4131                 return ReplaceInstUsesWith(I, AndRHS);
4132             }
4133           }
4134       }
4135     }
4136
4137     // Try to fold constant and into select arguments.
4138     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4139       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4140         return R;
4141     if (isa<PHINode>(Op0))
4142       if (Instruction *NV = FoldOpIntoPhi(I))
4143         return NV;
4144   }
4145
4146   Value *Op0NotVal = dyn_castNotVal(Op0);
4147   Value *Op1NotVal = dyn_castNotVal(Op1);
4148
4149   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4150     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4151
4152   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4153   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4154     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4155                                                I.getName()+".demorgan");
4156     InsertNewInstBefore(Or, I);
4157     return BinaryOperator::CreateNot(Or);
4158   }
4159   
4160   {
4161     Value *A = 0, *B = 0, *C = 0, *D = 0;
4162     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4163       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4164         return ReplaceInstUsesWith(I, Op1);
4165     
4166       // (A|B) & ~(A&B) -> A^B
4167       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4168         if ((A == C && B == D) || (A == D && B == C))
4169           return BinaryOperator::CreateXor(A, B);
4170       }
4171     }
4172     
4173     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4174       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4175         return ReplaceInstUsesWith(I, Op0);
4176
4177       // ~(A&B) & (A|B) -> A^B
4178       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4179         if ((A == C && B == D) || (A == D && B == C))
4180           return BinaryOperator::CreateXor(A, B);
4181       }
4182     }
4183     
4184     if (Op0->hasOneUse() &&
4185         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4186       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4187         I.swapOperands();     // Simplify below
4188         std::swap(Op0, Op1);
4189       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4190         cast<BinaryOperator>(Op0)->swapOperands();
4191         I.swapOperands();     // Simplify below
4192         std::swap(Op0, Op1);
4193       }
4194     }
4195     if (Op1->hasOneUse() &&
4196         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4197       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4198         cast<BinaryOperator>(Op1)->swapOperands();
4199         std::swap(A, B);
4200       }
4201       if (A == Op0) {                                // A&(A^B) -> A & ~B
4202         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4203         InsertNewInstBefore(NotB, I);
4204         return BinaryOperator::CreateAnd(A, NotB);
4205       }
4206     }
4207   }
4208   
4209   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4210     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4211     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4212       return R;
4213
4214     Value *LHSVal, *RHSVal;
4215     ConstantInt *LHSCst, *RHSCst;
4216     ICmpInst::Predicate LHSCC, RHSCC;
4217     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4218       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4219         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
4220             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4221             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4222             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4223             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4224             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4225             
4226             // Don't try to fold ICMP_SLT + ICMP_ULT.
4227             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4228              ICmpInst::isSignedPredicate(LHSCC) == 
4229                  ICmpInst::isSignedPredicate(RHSCC))) {
4230           // Ensure that the larger constant is on the RHS.
4231           ICmpInst::Predicate GT;
4232           if (ICmpInst::isSignedPredicate(LHSCC) ||
4233               (ICmpInst::isEquality(LHSCC) && 
4234                ICmpInst::isSignedPredicate(RHSCC)))
4235             GT = ICmpInst::ICMP_SGT;
4236           else
4237             GT = ICmpInst::ICMP_UGT;
4238           
4239           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4240           ICmpInst *LHS = cast<ICmpInst>(Op0);
4241           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4242             std::swap(LHS, RHS);
4243             std::swap(LHSCst, RHSCst);
4244             std::swap(LHSCC, RHSCC);
4245           }
4246
4247           // At this point, we know we have have two icmp instructions
4248           // comparing a value against two constants and and'ing the result
4249           // together.  Because of the above check, we know that we only have
4250           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4251           // (from the FoldICmpLogical check above), that the two constants 
4252           // are not equal and that the larger constant is on the RHS
4253           assert(LHSCst != RHSCst && "Compares not folded above?");
4254
4255           switch (LHSCC) {
4256           default: assert(0 && "Unknown integer condition code!");
4257           case ICmpInst::ICMP_EQ:
4258             switch (RHSCC) {
4259             default: assert(0 && "Unknown integer condition code!");
4260             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4261             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4262             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4263               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4264             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4265             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4266             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4267               return ReplaceInstUsesWith(I, LHS);
4268             }
4269           case ICmpInst::ICMP_NE:
4270             switch (RHSCC) {
4271             default: assert(0 && "Unknown integer condition code!");
4272             case ICmpInst::ICMP_ULT:
4273               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4274                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4275               break;                        // (X != 13 & X u< 15) -> no change
4276             case ICmpInst::ICMP_SLT:
4277               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4278                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4279               break;                        // (X != 13 & X s< 15) -> no change
4280             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4281             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4282             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4283               return ReplaceInstUsesWith(I, RHS);
4284             case ICmpInst::ICMP_NE:
4285               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4286                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4287                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4288                                                       LHSVal->getName()+".off");
4289                 InsertNewInstBefore(Add, I);
4290                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4291                                     ConstantInt::get(Add->getType(), 1));
4292               }
4293               break;                        // (X != 13 & X != 15) -> no change
4294             }
4295             break;
4296           case ICmpInst::ICMP_ULT:
4297             switch (RHSCC) {
4298             default: assert(0 && "Unknown integer condition code!");
4299             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4300             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4301               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4302             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4303               break;
4304             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4305             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4306               return ReplaceInstUsesWith(I, LHS);
4307             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4308               break;
4309             }
4310             break;
4311           case ICmpInst::ICMP_SLT:
4312             switch (RHSCC) {
4313             default: assert(0 && "Unknown integer condition code!");
4314             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4315             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4316               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4317             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4318               break;
4319             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4320             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4321               return ReplaceInstUsesWith(I, LHS);
4322             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4323               break;
4324             }
4325             break;
4326           case ICmpInst::ICMP_UGT:
4327             switch (RHSCC) {
4328             default: assert(0 && "Unknown integer condition code!");
4329             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
4330               return ReplaceInstUsesWith(I, LHS);
4331             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4332               return ReplaceInstUsesWith(I, RHS);
4333             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4334               break;
4335             case ICmpInst::ICMP_NE:
4336               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4337                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4338               break;                        // (X u> 13 & X != 15) -> no change
4339             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
4340               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
4341                                      true, I);
4342             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4343               break;
4344             }
4345             break;
4346           case ICmpInst::ICMP_SGT:
4347             switch (RHSCC) {
4348             default: assert(0 && "Unknown integer condition code!");
4349             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4350             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4351               return ReplaceInstUsesWith(I, RHS);
4352             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4353               break;
4354             case ICmpInst::ICMP_NE:
4355               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4356                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4357               break;                        // (X s> 13 & X != 15) -> no change
4358             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
4359               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
4360                                      true, I);
4361             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4362               break;
4363             }
4364             break;
4365           }
4366         }
4367   }
4368
4369   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4370   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4371     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4372       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4373         const Type *SrcTy = Op0C->getOperand(0)->getType();
4374         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4375             // Only do this if the casts both really cause code to be generated.
4376             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4377                               I.getType(), TD) &&
4378             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4379                               I.getType(), TD)) {
4380           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4381                                                          Op1C->getOperand(0),
4382                                                          I.getName());
4383           InsertNewInstBefore(NewOp, I);
4384           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4385         }
4386       }
4387     
4388   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4389   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4390     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4391       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4392           SI0->getOperand(1) == SI1->getOperand(1) &&
4393           (SI0->hasOneUse() || SI1->hasOneUse())) {
4394         Instruction *NewOp =
4395           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4396                                                         SI1->getOperand(0),
4397                                                         SI0->getName()), I);
4398         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4399                                       SI1->getOperand(1));
4400       }
4401   }
4402
4403   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4404   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4405     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4406       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4407           RHS->getPredicate() == FCmpInst::FCMP_ORD)
4408         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4409           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4410             // If either of the constants are nans, then the whole thing returns
4411             // false.
4412             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4413               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4414             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4415                                 RHS->getOperand(0));
4416           }
4417     }
4418   }
4419       
4420   return Changed ? &I : 0;
4421 }
4422
4423 /// CollectBSwapParts - Look to see if the specified value defines a single byte
4424 /// in the result.  If it does, and if the specified byte hasn't been filled in
4425 /// yet, fill it in and return false.
4426 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4427   Instruction *I = dyn_cast<Instruction>(V);
4428   if (I == 0) return true;
4429
4430   // If this is an or instruction, it is an inner node of the bswap.
4431   if (I->getOpcode() == Instruction::Or)
4432     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4433            CollectBSwapParts(I->getOperand(1), ByteValues);
4434   
4435   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4436   // If this is a shift by a constant int, and it is "24", then its operand
4437   // defines a byte.  We only handle unsigned types here.
4438   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4439     // Not shifting the entire input by N-1 bytes?
4440     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4441         8*(ByteValues.size()-1))
4442       return true;
4443     
4444     unsigned DestNo;
4445     if (I->getOpcode() == Instruction::Shl) {
4446       // X << 24 defines the top byte with the lowest of the input bytes.
4447       DestNo = ByteValues.size()-1;
4448     } else {
4449       // X >>u 24 defines the low byte with the highest of the input bytes.
4450       DestNo = 0;
4451     }
4452     
4453     // If the destination byte value is already defined, the values are or'd
4454     // together, which isn't a bswap (unless it's an or of the same bits).
4455     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4456       return true;
4457     ByteValues[DestNo] = I->getOperand(0);
4458     return false;
4459   }
4460   
4461   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
4462   // don't have this.
4463   Value *Shift = 0, *ShiftLHS = 0;
4464   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4465   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4466       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4467     return true;
4468   Instruction *SI = cast<Instruction>(Shift);
4469
4470   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4471   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4472       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4473     return true;
4474   
4475   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4476   unsigned DestByte;
4477   if (AndAmt->getValue().getActiveBits() > 64)
4478     return true;
4479   uint64_t AndAmtVal = AndAmt->getZExtValue();
4480   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4481     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4482       break;
4483   // Unknown mask for bswap.
4484   if (DestByte == ByteValues.size()) return true;
4485   
4486   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4487   unsigned SrcByte;
4488   if (SI->getOpcode() == Instruction::Shl)
4489     SrcByte = DestByte - ShiftBytes;
4490   else
4491     SrcByte = DestByte + ShiftBytes;
4492   
4493   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4494   if (SrcByte != ByteValues.size()-DestByte-1)
4495     return true;
4496   
4497   // If the destination byte value is already defined, the values are or'd
4498   // together, which isn't a bswap (unless it's an or of the same bits).
4499   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4500     return true;
4501   ByteValues[DestByte] = SI->getOperand(0);
4502   return false;
4503 }
4504
4505 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4506 /// If so, insert the new bswap intrinsic and return it.
4507 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4508   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4509   if (!ITy || ITy->getBitWidth() % 16) 
4510     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4511   
4512   /// ByteValues - For each byte of the result, we keep track of which value
4513   /// defines each byte.
4514   SmallVector<Value*, 8> ByteValues;
4515   ByteValues.resize(ITy->getBitWidth()/8);
4516     
4517   // Try to find all the pieces corresponding to the bswap.
4518   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4519       CollectBSwapParts(I.getOperand(1), ByteValues))
4520     return 0;
4521   
4522   // Check to see if all of the bytes come from the same value.
4523   Value *V = ByteValues[0];
4524   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4525   
4526   // Check to make sure that all of the bytes come from the same value.
4527   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4528     if (ByteValues[i] != V)
4529       return 0;
4530   const Type *Tys[] = { ITy };
4531   Module *M = I.getParent()->getParent()->getParent();
4532   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4533   return CallInst::Create(F, V);
4534 }
4535
4536
4537 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4538   bool Changed = SimplifyCommutative(I);
4539   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4540
4541   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4542     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4543
4544   // or X, X = X
4545   if (Op0 == Op1)
4546     return ReplaceInstUsesWith(I, Op0);
4547
4548   // See if we can simplify any instructions used by the instruction whose sole 
4549   // purpose is to compute bits we don't care about.
4550   if (!isa<VectorType>(I.getType())) {
4551     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4552     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4553     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4554                              KnownZero, KnownOne))
4555       return &I;
4556   } else if (isa<ConstantAggregateZero>(Op1)) {
4557     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4558   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4559     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4560       return ReplaceInstUsesWith(I, I.getOperand(1));
4561   }
4562     
4563
4564   
4565   // or X, -1 == -1
4566   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4567     ConstantInt *C1 = 0; Value *X = 0;
4568     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4569     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4570       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4571       InsertNewInstBefore(Or, I);
4572       Or->takeName(Op0);
4573       return BinaryOperator::CreateAnd(Or, 
4574                ConstantInt::get(RHS->getValue() | C1->getValue()));
4575     }
4576
4577     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4578     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4579       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4580       InsertNewInstBefore(Or, I);
4581       Or->takeName(Op0);
4582       return BinaryOperator::CreateXor(Or,
4583                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4584     }
4585
4586     // Try to fold constant and into select arguments.
4587     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4588       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4589         return R;
4590     if (isa<PHINode>(Op0))
4591       if (Instruction *NV = FoldOpIntoPhi(I))
4592         return NV;
4593   }
4594
4595   Value *A = 0, *B = 0;
4596   ConstantInt *C1 = 0, *C2 = 0;
4597
4598   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4599     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4600       return ReplaceInstUsesWith(I, Op1);
4601   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4602     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4603       return ReplaceInstUsesWith(I, Op0);
4604
4605   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4606   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4607   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4608       match(Op1, m_Or(m_Value(), m_Value())) ||
4609       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4610        match(Op1, m_Shift(m_Value(), m_Value())))) {
4611     if (Instruction *BSwap = MatchBSwap(I))
4612       return BSwap;
4613   }
4614   
4615   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4616   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4617       MaskedValueIsZero(Op1, C1->getValue())) {
4618     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4619     InsertNewInstBefore(NOr, I);
4620     NOr->takeName(Op0);
4621     return BinaryOperator::CreateXor(NOr, C1);
4622   }
4623
4624   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4625   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4626       MaskedValueIsZero(Op0, C1->getValue())) {
4627     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4628     InsertNewInstBefore(NOr, I);
4629     NOr->takeName(Op0);
4630     return BinaryOperator::CreateXor(NOr, C1);
4631   }
4632
4633   // (A & C)|(B & D)
4634   Value *C = 0, *D = 0;
4635   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4636       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4637     Value *V1 = 0, *V2 = 0, *V3 = 0;
4638     C1 = dyn_cast<ConstantInt>(C);
4639     C2 = dyn_cast<ConstantInt>(D);
4640     if (C1 && C2) {  // (A & C1)|(B & C2)
4641       // If we have: ((V + N) & C1) | (V & C2)
4642       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4643       // replace with V+N.
4644       if (C1->getValue() == ~C2->getValue()) {
4645         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4646             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4647           // Add commutes, try both ways.
4648           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4649             return ReplaceInstUsesWith(I, A);
4650           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4651             return ReplaceInstUsesWith(I, A);
4652         }
4653         // Or commutes, try both ways.
4654         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4655             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4656           // Add commutes, try both ways.
4657           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4658             return ReplaceInstUsesWith(I, B);
4659           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4660             return ReplaceInstUsesWith(I, B);
4661         }
4662       }
4663       V1 = 0; V2 = 0; V3 = 0;
4664     }
4665     
4666     // Check to see if we have any common things being and'ed.  If so, find the
4667     // terms for V1 & (V2|V3).
4668     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4669       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4670         V1 = A, V2 = C, V3 = D;
4671       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4672         V1 = A, V2 = B, V3 = C;
4673       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4674         V1 = C, V2 = A, V3 = D;
4675       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4676         V1 = C, V2 = A, V3 = B;
4677       
4678       if (V1) {
4679         Value *Or =
4680           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4681         return BinaryOperator::CreateAnd(V1, Or);
4682       }
4683     }
4684   }
4685   
4686   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4687   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4688     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4689       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4690           SI0->getOperand(1) == SI1->getOperand(1) &&
4691           (SI0->hasOneUse() || SI1->hasOneUse())) {
4692         Instruction *NewOp =
4693         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4694                                                      SI1->getOperand(0),
4695                                                      SI0->getName()), I);
4696         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4697                                       SI1->getOperand(1));
4698       }
4699   }
4700
4701   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4702     if (A == Op1)   // ~A | A == -1
4703       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4704   } else {
4705     A = 0;
4706   }
4707   // Note, A is still live here!
4708   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4709     if (Op0 == B)
4710       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4711
4712     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4713     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4714       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4715                                               I.getName()+".demorgan"), I);
4716       return BinaryOperator::CreateNot(And);
4717     }
4718   }
4719
4720   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4721   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4722     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4723       return R;
4724
4725     Value *LHSVal, *RHSVal;
4726     ConstantInt *LHSCst, *RHSCst;
4727     ICmpInst::Predicate LHSCC, RHSCC;
4728     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4729       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4730         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4731             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4732             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4733             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4734             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4735             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4736             // We can't fold (ugt x, C) | (sgt x, C2).
4737             PredicatesFoldable(LHSCC, RHSCC)) {
4738           // Ensure that the larger constant is on the RHS.
4739           ICmpInst *LHS = cast<ICmpInst>(Op0);
4740           bool NeedsSwap;
4741           if (ICmpInst::isSignedPredicate(LHSCC))
4742             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4743           else
4744             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4745             
4746           if (NeedsSwap) {
4747             std::swap(LHS, RHS);
4748             std::swap(LHSCst, RHSCst);
4749             std::swap(LHSCC, RHSCC);
4750           }
4751
4752           // At this point, we know we have have two icmp instructions
4753           // comparing a value against two constants and or'ing the result
4754           // together.  Because of the above check, we know that we only have
4755           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4756           // FoldICmpLogical check above), that the two constants are not
4757           // equal.
4758           assert(LHSCst != RHSCst && "Compares not folded above?");
4759
4760           switch (LHSCC) {
4761           default: assert(0 && "Unknown integer condition code!");
4762           case ICmpInst::ICMP_EQ:
4763             switch (RHSCC) {
4764             default: assert(0 && "Unknown integer condition code!");
4765             case ICmpInst::ICMP_EQ:
4766               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4767                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4768                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4769                                                       LHSVal->getName()+".off");
4770                 InsertNewInstBefore(Add, I);
4771                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4772                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4773               }
4774               break;                         // (X == 13 | X == 15) -> no change
4775             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4776             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4777               break;
4778             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4779             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4780             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4781               return ReplaceInstUsesWith(I, RHS);
4782             }
4783             break;
4784           case ICmpInst::ICMP_NE:
4785             switch (RHSCC) {
4786             default: assert(0 && "Unknown integer condition code!");
4787             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4788             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4789             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4790               return ReplaceInstUsesWith(I, LHS);
4791             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4792             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4793             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4794               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4795             }
4796             break;
4797           case ICmpInst::ICMP_ULT:
4798             switch (RHSCC) {
4799             default: assert(0 && "Unknown integer condition code!");
4800             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4801               break;
4802             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4803               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4804               // this can cause overflow.
4805               if (RHSCst->isMaxValue(false))
4806                 return ReplaceInstUsesWith(I, LHS);
4807               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4808                                      false, I);
4809             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4810               break;
4811             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4812             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4813               return ReplaceInstUsesWith(I, RHS);
4814             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4815               break;
4816             }
4817             break;
4818           case ICmpInst::ICMP_SLT:
4819             switch (RHSCC) {
4820             default: assert(0 && "Unknown integer condition code!");
4821             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4822               break;
4823             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4824               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4825               // this can cause overflow.
4826               if (RHSCst->isMaxValue(true))
4827                 return ReplaceInstUsesWith(I, LHS);
4828               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4829                                      false, I);
4830             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4831               break;
4832             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4833             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4834               return ReplaceInstUsesWith(I, RHS);
4835             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4836               break;
4837             }
4838             break;
4839           case ICmpInst::ICMP_UGT:
4840             switch (RHSCC) {
4841             default: assert(0 && "Unknown integer condition code!");
4842             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4843             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4844               return ReplaceInstUsesWith(I, LHS);
4845             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4846               break;
4847             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4848             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4849               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4850             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4851               break;
4852             }
4853             break;
4854           case ICmpInst::ICMP_SGT:
4855             switch (RHSCC) {
4856             default: assert(0 && "Unknown integer condition code!");
4857             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4858             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4859               return ReplaceInstUsesWith(I, LHS);
4860             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4861               break;
4862             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4863             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4864               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4865             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4866               break;
4867             }
4868             break;
4869           }
4870         }
4871   }
4872     
4873   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4874   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4875     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4876       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4877         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4878             !isa<ICmpInst>(Op1C->getOperand(0))) {
4879           const Type *SrcTy = Op0C->getOperand(0)->getType();
4880           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4881               // Only do this if the casts both really cause code to be
4882               // generated.
4883               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4884                                 I.getType(), TD) &&
4885               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4886                                 I.getType(), TD)) {
4887             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4888                                                           Op1C->getOperand(0),
4889                                                           I.getName());
4890             InsertNewInstBefore(NewOp, I);
4891             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4892           }
4893         }
4894       }
4895   }
4896   
4897     
4898   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4899   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4900     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4901       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4902           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4903           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4904         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4905           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4906             // If either of the constants are nans, then the whole thing returns
4907             // true.
4908             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4909               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4910             
4911             // Otherwise, no need to compare the two constants, compare the
4912             // rest.
4913             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4914                                 RHS->getOperand(0));
4915           }
4916     }
4917   }
4918
4919   return Changed ? &I : 0;
4920 }
4921
4922 namespace {
4923
4924 // XorSelf - Implements: X ^ X --> 0
4925 struct XorSelf {
4926   Value *RHS;
4927   XorSelf(Value *rhs) : RHS(rhs) {}
4928   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4929   Instruction *apply(BinaryOperator &Xor) const {
4930     return &Xor;
4931   }
4932 };
4933
4934 }
4935
4936 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4937   bool Changed = SimplifyCommutative(I);
4938   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4939
4940   if (isa<UndefValue>(Op1)) {
4941     if (isa<UndefValue>(Op0))
4942       // Handle undef ^ undef -> 0 special case. This is a common
4943       // idiom (misuse).
4944       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4945     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4946   }
4947
4948   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4949   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4950     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4951     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4952   }
4953   
4954   // See if we can simplify any instructions used by the instruction whose sole 
4955   // purpose is to compute bits we don't care about.
4956   if (!isa<VectorType>(I.getType())) {
4957     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4958     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4959     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4960                              KnownZero, KnownOne))
4961       return &I;
4962   } else if (isa<ConstantAggregateZero>(Op1)) {
4963     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4964   }
4965
4966   // Is this a ~ operation?
4967   if (Value *NotOp = dyn_castNotVal(&I)) {
4968     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4969     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4970     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4971       if (Op0I->getOpcode() == Instruction::And || 
4972           Op0I->getOpcode() == Instruction::Or) {
4973         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4974         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4975           Instruction *NotY =
4976             BinaryOperator::CreateNot(Op0I->getOperand(1),
4977                                       Op0I->getOperand(1)->getName()+".not");
4978           InsertNewInstBefore(NotY, I);
4979           if (Op0I->getOpcode() == Instruction::And)
4980             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4981           else
4982             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4983         }
4984       }
4985     }
4986   }
4987   
4988   
4989   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4990     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4991     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4992       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4993         return new ICmpInst(ICI->getInversePredicate(),
4994                             ICI->getOperand(0), ICI->getOperand(1));
4995
4996       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4997         return new FCmpInst(FCI->getInversePredicate(),
4998                             FCI->getOperand(0), FCI->getOperand(1));
4999     }
5000
5001     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5002       // ~(c-X) == X-c-1 == X+(-c-1)
5003       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5004         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5005           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5006           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5007                                               ConstantInt::get(I.getType(), 1));
5008           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5009         }
5010           
5011       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5012         if (Op0I->getOpcode() == Instruction::Add) {
5013           // ~(X-c) --> (-c-1)-X
5014           if (RHS->isAllOnesValue()) {
5015             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5016             return BinaryOperator::CreateSub(
5017                            ConstantExpr::getSub(NegOp0CI,
5018                                              ConstantInt::get(I.getType(), 1)),
5019                                           Op0I->getOperand(0));
5020           } else if (RHS->getValue().isSignBit()) {
5021             // (X + C) ^ signbit -> (X + C + signbit)
5022             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
5023             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5024
5025           }
5026         } else if (Op0I->getOpcode() == Instruction::Or) {
5027           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5028           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5029             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5030             // Anything in both C1 and C2 is known to be zero, remove it from
5031             // NewRHS.
5032             Constant *CommonBits = And(Op0CI, RHS);
5033             NewRHS = ConstantExpr::getAnd(NewRHS, 
5034                                           ConstantExpr::getNot(CommonBits));
5035             AddToWorkList(Op0I);
5036             I.setOperand(0, Op0I->getOperand(0));
5037             I.setOperand(1, NewRHS);
5038             return &I;
5039           }
5040         }
5041       }
5042     }
5043
5044     // Try to fold constant and into select arguments.
5045     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5046       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5047         return R;
5048     if (isa<PHINode>(Op0))
5049       if (Instruction *NV = FoldOpIntoPhi(I))
5050         return NV;
5051   }
5052
5053   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5054     if (X == Op1)
5055       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5056
5057   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5058     if (X == Op0)
5059       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5060
5061   
5062   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5063   if (Op1I) {
5064     Value *A, *B;
5065     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5066       if (A == Op0) {              // B^(B|A) == (A|B)^B
5067         Op1I->swapOperands();
5068         I.swapOperands();
5069         std::swap(Op0, Op1);
5070       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5071         I.swapOperands();     // Simplified below.
5072         std::swap(Op0, Op1);
5073       }
5074     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5075       if (Op0 == A)                                          // A^(A^B) == B
5076         return ReplaceInstUsesWith(I, B);
5077       else if (Op0 == B)                                     // A^(B^A) == B
5078         return ReplaceInstUsesWith(I, A);
5079     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5080       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5081         Op1I->swapOperands();
5082         std::swap(A, B);
5083       }
5084       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5085         I.swapOperands();     // Simplified below.
5086         std::swap(Op0, Op1);
5087       }
5088     }
5089   }
5090   
5091   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5092   if (Op0I) {
5093     Value *A, *B;
5094     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5095       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5096         std::swap(A, B);
5097       if (B == Op1) {                                // (A|B)^B == A & ~B
5098         Instruction *NotB =
5099           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5100         return BinaryOperator::CreateAnd(A, NotB);
5101       }
5102     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5103       if (Op1 == A)                                          // (A^B)^A == B
5104         return ReplaceInstUsesWith(I, B);
5105       else if (Op1 == B)                                     // (B^A)^A == B
5106         return ReplaceInstUsesWith(I, A);
5107     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5108       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5109         std::swap(A, B);
5110       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5111           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5112         Instruction *N =
5113           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5114         return BinaryOperator::CreateAnd(N, Op1);
5115       }
5116     }
5117   }
5118   
5119   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5120   if (Op0I && Op1I && Op0I->isShift() && 
5121       Op0I->getOpcode() == Op1I->getOpcode() && 
5122       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5123       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5124     Instruction *NewOp =
5125       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5126                                                     Op1I->getOperand(0),
5127                                                     Op0I->getName()), I);
5128     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5129                                   Op1I->getOperand(1));
5130   }
5131     
5132   if (Op0I && Op1I) {
5133     Value *A, *B, *C, *D;
5134     // (A & B)^(A | B) -> A ^ B
5135     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5136         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5137       if ((A == C && B == D) || (A == D && B == C)) 
5138         return BinaryOperator::CreateXor(A, B);
5139     }
5140     // (A | B)^(A & B) -> A ^ B
5141     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5142         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5143       if ((A == C && B == D) || (A == D && B == C)) 
5144         return BinaryOperator::CreateXor(A, B);
5145     }
5146     
5147     // (A & B)^(C & D)
5148     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5149         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5150         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5151       // (X & Y)^(X & Y) -> (Y^Z) & X
5152       Value *X = 0, *Y = 0, *Z = 0;
5153       if (A == C)
5154         X = A, Y = B, Z = D;
5155       else if (A == D)
5156         X = A, Y = B, Z = C;
5157       else if (B == C)
5158         X = B, Y = A, Z = D;
5159       else if (B == D)
5160         X = B, Y = A, Z = C;
5161       
5162       if (X) {
5163         Instruction *NewOp =
5164         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5165         return BinaryOperator::CreateAnd(NewOp, X);
5166       }
5167     }
5168   }
5169     
5170   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5171   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5172     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5173       return R;
5174
5175   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5176   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5177     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5178       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5179         const Type *SrcTy = Op0C->getOperand(0)->getType();
5180         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5181             // Only do this if the casts both really cause code to be generated.
5182             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5183                               I.getType(), TD) &&
5184             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5185                               I.getType(), TD)) {
5186           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5187                                                          Op1C->getOperand(0),
5188                                                          I.getName());
5189           InsertNewInstBefore(NewOp, I);
5190           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5191         }
5192       }
5193   }
5194   return Changed ? &I : 0;
5195 }
5196
5197 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5198 /// overflowed for this type.
5199 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5200                             ConstantInt *In2, bool IsSigned = false) {
5201   Result = cast<ConstantInt>(Add(In1, In2));
5202
5203   if (IsSigned)
5204     if (In2->getValue().isNegative())
5205       return Result->getValue().sgt(In1->getValue());
5206     else
5207       return Result->getValue().slt(In1->getValue());
5208   else
5209     return Result->getValue().ult(In1->getValue());
5210 }
5211
5212 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5213 /// code necessary to compute the offset from the base pointer (without adding
5214 /// in the base pointer).  Return the result as a signed integer of intptr size.
5215 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5216   TargetData &TD = IC.getTargetData();
5217   gep_type_iterator GTI = gep_type_begin(GEP);
5218   const Type *IntPtrTy = TD.getIntPtrType();
5219   Value *Result = Constant::getNullValue(IntPtrTy);
5220
5221   // Build a mask for high order bits.
5222   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5223   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5224
5225   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5226     Value *Op = GEP->getOperand(i);
5227     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5228     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5229       if (OpC->isZero()) continue;
5230       
5231       // Handle a struct index, which adds its field offset to the pointer.
5232       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5233         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5234         
5235         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5236           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5237         else
5238           Result = IC.InsertNewInstBefore(
5239                    BinaryOperator::CreateAdd(Result,
5240                                              ConstantInt::get(IntPtrTy, Size),
5241                                              GEP->getName()+".offs"), I);
5242         continue;
5243       }
5244       
5245       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5246       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5247       Scale = ConstantExpr::getMul(OC, Scale);
5248       if (Constant *RC = dyn_cast<Constant>(Result))
5249         Result = ConstantExpr::getAdd(RC, Scale);
5250       else {
5251         // Emit an add instruction.
5252         Result = IC.InsertNewInstBefore(
5253            BinaryOperator::CreateAdd(Result, Scale,
5254                                      GEP->getName()+".offs"), I);
5255       }
5256       continue;
5257     }
5258     // Convert to correct type.
5259     if (Op->getType() != IntPtrTy) {
5260       if (Constant *OpC = dyn_cast<Constant>(Op))
5261         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5262       else
5263         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5264                                                  Op->getName()+".c"), I);
5265     }
5266     if (Size != 1) {
5267       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5268       if (Constant *OpC = dyn_cast<Constant>(Op))
5269         Op = ConstantExpr::getMul(OpC, Scale);
5270       else    // We'll let instcombine(mul) convert this to a shl if possible.
5271         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5272                                                   GEP->getName()+".idx"), I);
5273     }
5274
5275     // Emit an add instruction.
5276     if (isa<Constant>(Op) && isa<Constant>(Result))
5277       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5278                                     cast<Constant>(Result));
5279     else
5280       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5281                                                   GEP->getName()+".offs"), I);
5282   }
5283   return Result;
5284 }
5285
5286
5287 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5288 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5289 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5290 /// complex, and scales are involved.  The above expression would also be legal
5291 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5292 /// later form is less amenable to optimization though, and we are allowed to
5293 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5294 ///
5295 /// If we can't emit an optimized form for this expression, this returns null.
5296 /// 
5297 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5298                                           InstCombiner &IC) {
5299   TargetData &TD = IC.getTargetData();
5300   gep_type_iterator GTI = gep_type_begin(GEP);
5301
5302   // Check to see if this gep only has a single variable index.  If so, and if
5303   // any constant indices are a multiple of its scale, then we can compute this
5304   // in terms of the scale of the variable index.  For example, if the GEP
5305   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5306   // because the expression will cross zero at the same point.
5307   unsigned i, e = GEP->getNumOperands();
5308   int64_t Offset = 0;
5309   for (i = 1; i != e; ++i, ++GTI) {
5310     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5311       // Compute the aggregate offset of constant indices.
5312       if (CI->isZero()) continue;
5313
5314       // Handle a struct index, which adds its field offset to the pointer.
5315       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5316         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5317       } else {
5318         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5319         Offset += Size*CI->getSExtValue();
5320       }
5321     } else {
5322       // Found our variable index.
5323       break;
5324     }
5325   }
5326   
5327   // If there are no variable indices, we must have a constant offset, just
5328   // evaluate it the general way.
5329   if (i == e) return 0;
5330   
5331   Value *VariableIdx = GEP->getOperand(i);
5332   // Determine the scale factor of the variable element.  For example, this is
5333   // 4 if the variable index is into an array of i32.
5334   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5335   
5336   // Verify that there are no other variable indices.  If so, emit the hard way.
5337   for (++i, ++GTI; i != e; ++i, ++GTI) {
5338     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5339     if (!CI) return 0;
5340    
5341     // Compute the aggregate offset of constant indices.
5342     if (CI->isZero()) continue;
5343     
5344     // Handle a struct index, which adds its field offset to the pointer.
5345     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5346       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5347     } else {
5348       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5349       Offset += Size*CI->getSExtValue();
5350     }
5351   }
5352   
5353   // Okay, we know we have a single variable index, which must be a
5354   // pointer/array/vector index.  If there is no offset, life is simple, return
5355   // the index.
5356   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5357   if (Offset == 0) {
5358     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5359     // we don't need to bother extending: the extension won't affect where the
5360     // computation crosses zero.
5361     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5362       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5363                                   VariableIdx->getNameStart(), &I);
5364     return VariableIdx;
5365   }
5366   
5367   // Otherwise, there is an index.  The computation we will do will be modulo
5368   // the pointer size, so get it.
5369   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5370   
5371   Offset &= PtrSizeMask;
5372   VariableScale &= PtrSizeMask;
5373
5374   // To do this transformation, any constant index must be a multiple of the
5375   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5376   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5377   // multiple of the variable scale.
5378   int64_t NewOffs = Offset / (int64_t)VariableScale;
5379   if (Offset != NewOffs*(int64_t)VariableScale)
5380     return 0;
5381
5382   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5383   const Type *IntPtrTy = TD.getIntPtrType();
5384   if (VariableIdx->getType() != IntPtrTy)
5385     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5386                                               true /*SExt*/, 
5387                                               VariableIdx->getNameStart(), &I);
5388   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5389   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5390 }
5391
5392
5393 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5394 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5395 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5396                                        ICmpInst::Predicate Cond,
5397                                        Instruction &I) {
5398   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5399
5400   // Look through bitcasts.
5401   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5402     RHS = BCI->getOperand(0);
5403
5404   Value *PtrBase = GEPLHS->getOperand(0);
5405   if (PtrBase == RHS) {
5406     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5407     // This transformation (ignoring the base and scales) is valid because we
5408     // know pointers can't overflow.  See if we can output an optimized form.
5409     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5410     
5411     // If not, synthesize the offset the hard way.
5412     if (Offset == 0)
5413       Offset = EmitGEPOffset(GEPLHS, I, *this);
5414     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5415                         Constant::getNullValue(Offset->getType()));
5416   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5417     // If the base pointers are different, but the indices are the same, just
5418     // compare the base pointer.
5419     if (PtrBase != GEPRHS->getOperand(0)) {
5420       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5421       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5422                         GEPRHS->getOperand(0)->getType();
5423       if (IndicesTheSame)
5424         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5425           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5426             IndicesTheSame = false;
5427             break;
5428           }
5429
5430       // If all indices are the same, just compare the base pointers.
5431       if (IndicesTheSame)
5432         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5433                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5434
5435       // Otherwise, the base pointers are different and the indices are
5436       // different, bail out.
5437       return 0;
5438     }
5439
5440     // If one of the GEPs has all zero indices, recurse.
5441     bool AllZeros = true;
5442     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5443       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5444           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5445         AllZeros = false;
5446         break;
5447       }
5448     if (AllZeros)
5449       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5450                           ICmpInst::getSwappedPredicate(Cond), I);
5451
5452     // If the other GEP has all zero indices, recurse.
5453     AllZeros = true;
5454     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5455       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5456           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5457         AllZeros = false;
5458         break;
5459       }
5460     if (AllZeros)
5461       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5462
5463     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5464       // If the GEPs only differ by one index, compare it.
5465       unsigned NumDifferences = 0;  // Keep track of # differences.
5466       unsigned DiffOperand = 0;     // The operand that differs.
5467       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5468         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5469           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5470                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5471             // Irreconcilable differences.
5472             NumDifferences = 2;
5473             break;
5474           } else {
5475             if (NumDifferences++) break;
5476             DiffOperand = i;
5477           }
5478         }
5479
5480       if (NumDifferences == 0)   // SAME GEP?
5481         return ReplaceInstUsesWith(I, // No comparison is needed here.
5482                                    ConstantInt::get(Type::Int1Ty,
5483                                              ICmpInst::isTrueWhenEqual(Cond)));
5484
5485       else if (NumDifferences == 1) {
5486         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5487         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5488         // Make sure we do a signed comparison here.
5489         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5490       }
5491     }
5492
5493     // Only lower this if the icmp is the only user of the GEP or if we expect
5494     // the result to fold to a constant!
5495     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5496         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5497       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5498       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5499       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5500       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5501     }
5502   }
5503   return 0;
5504 }
5505
5506 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5507 ///
5508 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5509                                                 Instruction *LHSI,
5510                                                 Constant *RHSC) {
5511   if (!isa<ConstantFP>(RHSC)) return 0;
5512   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5513   
5514   // Get the width of the mantissa.  We don't want to hack on conversions that
5515   // might lose information from the integer, e.g. "i64 -> float"
5516   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5517   if (MantissaWidth == -1) return 0;  // Unknown.
5518   
5519   // Check to see that the input is converted from an integer type that is small
5520   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5521   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5522   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5523   
5524   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5525   if (isa<UIToFPInst>(LHSI))
5526     ++InputSize;
5527   
5528   // If the conversion would lose info, don't hack on this.
5529   if ((int)InputSize > MantissaWidth)
5530     return 0;
5531   
5532   // Otherwise, we can potentially simplify the comparison.  We know that it
5533   // will always come through as an integer value and we know the constant is
5534   // not a NAN (it would have been previously simplified).
5535   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5536   
5537   ICmpInst::Predicate Pred;
5538   switch (I.getPredicate()) {
5539   default: assert(0 && "Unexpected predicate!");
5540   case FCmpInst::FCMP_UEQ:
5541   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5542   case FCmpInst::FCMP_UGT:
5543   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5544   case FCmpInst::FCMP_UGE:
5545   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5546   case FCmpInst::FCMP_ULT:
5547   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5548   case FCmpInst::FCMP_ULE:
5549   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5550   case FCmpInst::FCMP_UNE:
5551   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5552   case FCmpInst::FCMP_ORD:
5553     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5554   case FCmpInst::FCMP_UNO:
5555     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5556   }
5557   
5558   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5559   
5560   // Now we know that the APFloat is a normal number, zero or inf.
5561   
5562   // See if the FP constant is too large for the integer.  For example,
5563   // comparing an i8 to 300.0.
5564   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5565   
5566   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5567   // and large values. 
5568   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5569   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5570                         APFloat::rmNearestTiesToEven);
5571   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5572     if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5573       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5574     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5575   }
5576   
5577   // See if the RHS value is < SignedMin.
5578   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5579   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5580                         APFloat::rmNearestTiesToEven);
5581   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5582     if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5583       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5584     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5585   }
5586
5587   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5588   // it may still be fractional.  See if it is fractional by casting the FP
5589   // value to the integer value and back, checking for equality.  Don't do this
5590   // for zero, because -0.0 is not fractional.
5591   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5592   if (!RHS.isZero() &&
5593       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5594     // If we had a comparison against a fractional value, we have to adjust
5595     // the compare predicate and sometimes the value.  RHSC is rounded towards
5596     // zero at this point.
5597     switch (Pred) {
5598     default: assert(0 && "Unexpected integer comparison!");
5599     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5600       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5601     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5602       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5603     case ICmpInst::ICMP_SLE:
5604       // (float)int <= 4.4   --> int <= 4
5605       // (float)int <= -4.4  --> int < -4
5606       if (RHS.isNegative())
5607         Pred = ICmpInst::ICMP_SLT;
5608       break;
5609     case ICmpInst::ICMP_SLT:
5610       // (float)int < -4.4   --> int < -4
5611       // (float)int < 4.4    --> int <= 4
5612       if (!RHS.isNegative())
5613         Pred = ICmpInst::ICMP_SLE;
5614       break;
5615     case ICmpInst::ICMP_SGT:
5616       // (float)int > 4.4    --> int > 4
5617       // (float)int > -4.4   --> int >= -4
5618       if (RHS.isNegative())
5619         Pred = ICmpInst::ICMP_SGE;
5620       break;
5621     case ICmpInst::ICMP_SGE:
5622       // (float)int >= -4.4   --> int >= -4
5623       // (float)int >= 4.4    --> int > 4
5624       if (!RHS.isNegative())
5625         Pred = ICmpInst::ICMP_SGT;
5626       break;
5627     }
5628   }
5629
5630   // Lower this FP comparison into an appropriate integer version of the
5631   // comparison.
5632   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5633 }
5634
5635 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5636   bool Changed = SimplifyCompare(I);
5637   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5638
5639   // Fold trivial predicates.
5640   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5641     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5642   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5643     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5644   
5645   // Simplify 'fcmp pred X, X'
5646   if (Op0 == Op1) {
5647     switch (I.getPredicate()) {
5648     default: assert(0 && "Unknown predicate!");
5649     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5650     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5651     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5652       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5653     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5654     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5655     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5656       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5657       
5658     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5659     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5660     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5661     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5662       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5663       I.setPredicate(FCmpInst::FCMP_UNO);
5664       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5665       return &I;
5666       
5667     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5668     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5669     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5670     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5671       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5672       I.setPredicate(FCmpInst::FCMP_ORD);
5673       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5674       return &I;
5675     }
5676   }
5677     
5678   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5679     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5680
5681   // Handle fcmp with constant RHS
5682   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5683     // If the constant is a nan, see if we can fold the comparison based on it.
5684     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5685       if (CFP->getValueAPF().isNaN()) {
5686         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5687           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5688         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5689                "Comparison must be either ordered or unordered!");
5690         // True if unordered.
5691         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5692       }
5693     }
5694     
5695     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5696       switch (LHSI->getOpcode()) {
5697       case Instruction::PHI:
5698         if (Instruction *NV = FoldOpIntoPhi(I))
5699           return NV;
5700         break;
5701       case Instruction::SIToFP:
5702       case Instruction::UIToFP:
5703         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5704           return NV;
5705         break;
5706       case Instruction::Select:
5707         // If either operand of the select is a constant, we can fold the
5708         // comparison into the select arms, which will cause one to be
5709         // constant folded and the select turned into a bitwise or.
5710         Value *Op1 = 0, *Op2 = 0;
5711         if (LHSI->hasOneUse()) {
5712           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5713             // Fold the known value into the constant operand.
5714             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5715             // Insert a new FCmp of the other select operand.
5716             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5717                                                       LHSI->getOperand(2), RHSC,
5718                                                       I.getName()), I);
5719           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5720             // Fold the known value into the constant operand.
5721             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5722             // Insert a new FCmp of the other select operand.
5723             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5724                                                       LHSI->getOperand(1), RHSC,
5725                                                       I.getName()), I);
5726           }
5727         }
5728
5729         if (Op1)
5730           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5731         break;
5732       }
5733   }
5734
5735   return Changed ? &I : 0;
5736 }
5737
5738 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5739   bool Changed = SimplifyCompare(I);
5740   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5741   const Type *Ty = Op0->getType();
5742
5743   // icmp X, X
5744   if (Op0 == Op1)
5745     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5746                                                    I.isTrueWhenEqual()));
5747
5748   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5749     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5750   
5751   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5752   // addresses never equal each other!  We already know that Op0 != Op1.
5753   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5754        isa<ConstantPointerNull>(Op0)) &&
5755       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5756        isa<ConstantPointerNull>(Op1)))
5757     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5758                                                    !I.isTrueWhenEqual()));
5759
5760   // icmp's with boolean values can always be turned into bitwise operations
5761   if (Ty == Type::Int1Ty) {
5762     switch (I.getPredicate()) {
5763     default: assert(0 && "Invalid icmp instruction!");
5764     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
5765       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5766       InsertNewInstBefore(Xor, I);
5767       return BinaryOperator::CreateNot(Xor);
5768     }
5769     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
5770       return BinaryOperator::CreateXor(Op0, Op1);
5771
5772     case ICmpInst::ICMP_UGT:
5773     case ICmpInst::ICMP_SGT:
5774       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
5775       // FALL THROUGH
5776     case ICmpInst::ICMP_ULT:
5777     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
5778       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5779       InsertNewInstBefore(Not, I);
5780       return BinaryOperator::CreateAnd(Not, Op1);
5781     }
5782     case ICmpInst::ICMP_UGE:
5783     case ICmpInst::ICMP_SGE:
5784       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
5785       // FALL THROUGH
5786     case ICmpInst::ICMP_ULE:
5787     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
5788       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5789       InsertNewInstBefore(Not, I);
5790       return BinaryOperator::CreateOr(Not, Op1);
5791     }
5792     }
5793   }
5794
5795   // See if we are doing a comparison between a constant and an instruction that
5796   // can be folded into the comparison.
5797   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5798       Value *A, *B;
5799     
5800     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5801     if (I.isEquality() && CI->isNullValue() &&
5802         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5803       // (icmp cond A B) if cond is equality
5804       return new ICmpInst(I.getPredicate(), A, B);
5805     }
5806     
5807     switch (I.getPredicate()) {
5808     default: break;
5809     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5810       if (CI->isMinValue(false))
5811         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5812       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5813         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5814       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5815         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5816       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5817       if (CI->isMinValue(true))
5818         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5819                             ConstantInt::getAllOnesValue(Op0->getType()));
5820           
5821       break;
5822
5823     case ICmpInst::ICMP_SLT:
5824       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5825         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5826       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5827         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5828       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5829         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5830       break;
5831
5832     case ICmpInst::ICMP_UGT:
5833       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5834         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5835       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5836         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5837       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5838         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5839         
5840       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5841       if (CI->isMaxValue(true))
5842         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5843                             ConstantInt::getNullValue(Op0->getType()));
5844       break;
5845
5846     case ICmpInst::ICMP_SGT:
5847       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5848         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5849       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5850         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5851       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5852         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5853       break;
5854
5855     case ICmpInst::ICMP_ULE:
5856       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5857         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5858       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5859         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5860       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5861         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5862       break;
5863
5864     case ICmpInst::ICMP_SLE:
5865       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5866         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5867       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5868         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5869       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5870         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5871       break;
5872
5873     case ICmpInst::ICMP_UGE:
5874       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5875         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5876       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5877         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5878       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5879         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5880       break;
5881
5882     case ICmpInst::ICMP_SGE:
5883       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5884         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5885       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5886         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5887       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5888         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5889       break;
5890     }
5891
5892     // If we still have a icmp le or icmp ge instruction, turn it into the
5893     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5894     // already been handled above, this requires little checking.
5895     //
5896     switch (I.getPredicate()) {
5897     default: break;
5898     case ICmpInst::ICMP_ULE: 
5899       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5900     case ICmpInst::ICMP_SLE:
5901       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5902     case ICmpInst::ICMP_UGE:
5903       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5904     case ICmpInst::ICMP_SGE:
5905       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5906     }
5907     
5908     // See if we can fold the comparison based on bits known to be zero or one
5909     // in the input.  If this comparison is a normal comparison, it demands all
5910     // bits, if it is a sign bit comparison, it only demands the sign bit.
5911     
5912     bool UnusedBit;
5913     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5914     
5915     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5916     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5917     if (SimplifyDemandedBits(Op0, 
5918                              isSignBit ? APInt::getSignBit(BitWidth)
5919                                        : APInt::getAllOnesValue(BitWidth),
5920                              KnownZero, KnownOne, 0))
5921       return &I;
5922         
5923     // Given the known and unknown bits, compute a range that the LHS could be
5924     // in.
5925     if ((KnownOne | KnownZero) != 0) {
5926       // Compute the Min, Max and RHS values based on the known bits. For the
5927       // EQ and NE we use unsigned values.
5928       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5929       const APInt& RHSVal = CI->getValue();
5930       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5931         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5932                                                Max);
5933       } else {
5934         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5935                                                  Max);
5936       }
5937       switch (I.getPredicate()) {  // LE/GE have been folded already.
5938       default: assert(0 && "Unknown icmp opcode!");
5939       case ICmpInst::ICMP_EQ:
5940         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5941           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5942         break;
5943       case ICmpInst::ICMP_NE:
5944         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5945           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5946         break;
5947       case ICmpInst::ICMP_ULT:
5948         if (Max.ult(RHSVal))
5949           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5950         if (Min.uge(RHSVal))
5951           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5952         break;
5953       case ICmpInst::ICMP_UGT:
5954         if (Min.ugt(RHSVal))
5955           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5956         if (Max.ule(RHSVal))
5957           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5958         break;
5959       case ICmpInst::ICMP_SLT:
5960         if (Max.slt(RHSVal))
5961           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5962         if (Min.sgt(RHSVal))
5963           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5964         break;
5965       case ICmpInst::ICMP_SGT: 
5966         if (Min.sgt(RHSVal))
5967           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5968         if (Max.sle(RHSVal))
5969           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5970         break;
5971       }
5972     }
5973           
5974     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5975     // instruction, see if that instruction also has constants so that the 
5976     // instruction can be folded into the icmp 
5977     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5978       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5979         return Res;
5980   }
5981
5982   // Handle icmp with constant (but not simple integer constant) RHS
5983   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5984     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5985       switch (LHSI->getOpcode()) {
5986       case Instruction::GetElementPtr:
5987         if (RHSC->isNullValue()) {
5988           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5989           bool isAllZeros = true;
5990           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5991             if (!isa<Constant>(LHSI->getOperand(i)) ||
5992                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5993               isAllZeros = false;
5994               break;
5995             }
5996           if (isAllZeros)
5997             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5998                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5999         }
6000         break;
6001
6002       case Instruction::PHI:
6003         if (Instruction *NV = FoldOpIntoPhi(I))
6004           return NV;
6005         break;
6006       case Instruction::Select: {
6007         // If either operand of the select is a constant, we can fold the
6008         // comparison into the select arms, which will cause one to be
6009         // constant folded and the select turned into a bitwise or.
6010         Value *Op1 = 0, *Op2 = 0;
6011         if (LHSI->hasOneUse()) {
6012           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6013             // Fold the known value into the constant operand.
6014             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6015             // Insert a new ICmp of the other select operand.
6016             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6017                                                    LHSI->getOperand(2), RHSC,
6018                                                    I.getName()), I);
6019           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6020             // Fold the known value into the constant operand.
6021             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6022             // Insert a new ICmp of the other select operand.
6023             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6024                                                    LHSI->getOperand(1), RHSC,
6025                                                    I.getName()), I);
6026           }
6027         }
6028
6029         if (Op1)
6030           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6031         break;
6032       }
6033       case Instruction::Malloc:
6034         // If we have (malloc != null), and if the malloc has a single use, we
6035         // can assume it is successful and remove the malloc.
6036         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6037           AddToWorkList(LHSI);
6038           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6039                                                          !I.isTrueWhenEqual()));
6040         }
6041         break;
6042       }
6043   }
6044
6045   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6046   if (User *GEP = dyn_castGetElementPtr(Op0))
6047     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6048       return NI;
6049   if (User *GEP = dyn_castGetElementPtr(Op1))
6050     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6051                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6052       return NI;
6053
6054   // Test to see if the operands of the icmp are casted versions of other
6055   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6056   // now.
6057   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6058     if (isa<PointerType>(Op0->getType()) && 
6059         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6060       // We keep moving the cast from the left operand over to the right
6061       // operand, where it can often be eliminated completely.
6062       Op0 = CI->getOperand(0);
6063
6064       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6065       // so eliminate it as well.
6066       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6067         Op1 = CI2->getOperand(0);
6068
6069       // If Op1 is a constant, we can fold the cast into the constant.
6070       if (Op0->getType() != Op1->getType()) {
6071         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6072           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6073         } else {
6074           // Otherwise, cast the RHS right before the icmp
6075           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6076         }
6077       }
6078       return new ICmpInst(I.getPredicate(), Op0, Op1);
6079     }
6080   }
6081   
6082   if (isa<CastInst>(Op0)) {
6083     // Handle the special case of: icmp (cast bool to X), <cst>
6084     // This comes up when you have code like
6085     //   int X = A < B;
6086     //   if (X) ...
6087     // For generality, we handle any zero-extension of any operand comparison
6088     // with a constant or another cast from the same type.
6089     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6090       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6091         return R;
6092   }
6093   
6094   // ~x < ~y --> y < x
6095   { Value *A, *B;
6096     if (match(Op0, m_Not(m_Value(A))) &&
6097         match(Op1, m_Not(m_Value(B))))
6098       return new ICmpInst(I.getPredicate(), B, A);
6099   }
6100   
6101   if (I.isEquality()) {
6102     Value *A, *B, *C, *D;
6103     
6104     // -x == -y --> x == y
6105     if (match(Op0, m_Neg(m_Value(A))) &&
6106         match(Op1, m_Neg(m_Value(B))))
6107       return new ICmpInst(I.getPredicate(), A, B);
6108     
6109     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6110       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6111         Value *OtherVal = A == Op1 ? B : A;
6112         return new ICmpInst(I.getPredicate(), OtherVal,
6113                             Constant::getNullValue(A->getType()));
6114       }
6115
6116       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6117         // A^c1 == C^c2 --> A == C^(c1^c2)
6118         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6119           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6120             if (Op1->hasOneUse()) {
6121               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6122               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6123               return new ICmpInst(I.getPredicate(), A,
6124                                   InsertNewInstBefore(Xor, I));
6125             }
6126         
6127         // A^B == A^D -> B == D
6128         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6129         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6130         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6131         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6132       }
6133     }
6134     
6135     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6136         (A == Op0 || B == Op0)) {
6137       // A == (A^B)  ->  B == 0
6138       Value *OtherVal = A == Op0 ? B : A;
6139       return new ICmpInst(I.getPredicate(), OtherVal,
6140                           Constant::getNullValue(A->getType()));
6141     }
6142     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
6143       // (A-B) == A  ->  B == 0
6144       return new ICmpInst(I.getPredicate(), B,
6145                           Constant::getNullValue(B->getType()));
6146     }
6147     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
6148       // A == (A-B)  ->  B == 0
6149       return new ICmpInst(I.getPredicate(), B,
6150                           Constant::getNullValue(B->getType()));
6151     }
6152     
6153     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6154     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6155         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6156         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6157       Value *X = 0, *Y = 0, *Z = 0;
6158       
6159       if (A == C) {
6160         X = B; Y = D; Z = A;
6161       } else if (A == D) {
6162         X = B; Y = C; Z = A;
6163       } else if (B == C) {
6164         X = A; Y = D; Z = B;
6165       } else if (B == D) {
6166         X = A; Y = C; Z = B;
6167       }
6168       
6169       if (X) {   // Build (X^Y) & Z
6170         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6171         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6172         I.setOperand(0, Op1);
6173         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6174         return &I;
6175       }
6176     }
6177   }
6178   return Changed ? &I : 0;
6179 }
6180
6181
6182 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6183 /// and CmpRHS are both known to be integer constants.
6184 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6185                                           ConstantInt *DivRHS) {
6186   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6187   const APInt &CmpRHSV = CmpRHS->getValue();
6188   
6189   // FIXME: If the operand types don't match the type of the divide 
6190   // then don't attempt this transform. The code below doesn't have the
6191   // logic to deal with a signed divide and an unsigned compare (and
6192   // vice versa). This is because (x /s C1) <s C2  produces different 
6193   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6194   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6195   // work. :(  The if statement below tests that condition and bails 
6196   // if it finds it. 
6197   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6198   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6199     return 0;
6200   if (DivRHS->isZero())
6201     return 0; // The ProdOV computation fails on divide by zero.
6202
6203   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6204   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6205   // C2 (CI). By solving for X we can turn this into a range check 
6206   // instead of computing a divide. 
6207   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6208
6209   // Determine if the product overflows by seeing if the product is
6210   // not equal to the divide. Make sure we do the same kind of divide
6211   // as in the LHS instruction that we're folding. 
6212   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6213                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6214
6215   // Get the ICmp opcode
6216   ICmpInst::Predicate Pred = ICI.getPredicate();
6217
6218   // Figure out the interval that is being checked.  For example, a comparison
6219   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6220   // Compute this interval based on the constants involved and the signedness of
6221   // the compare/divide.  This computes a half-open interval, keeping track of
6222   // whether either value in the interval overflows.  After analysis each
6223   // overflow variable is set to 0 if it's corresponding bound variable is valid
6224   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6225   int LoOverflow = 0, HiOverflow = 0;
6226   ConstantInt *LoBound = 0, *HiBound = 0;
6227   
6228   
6229   if (!DivIsSigned) {  // udiv
6230     // e.g. X/5 op 3  --> [15, 20)
6231     LoBound = Prod;
6232     HiOverflow = LoOverflow = ProdOV;
6233     if (!HiOverflow)
6234       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6235   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6236     if (CmpRHSV == 0) {       // (X / pos) op 0
6237       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6238       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6239       HiBound = DivRHS;
6240     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6241       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6242       HiOverflow = LoOverflow = ProdOV;
6243       if (!HiOverflow)
6244         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6245     } else {                       // (X / pos) op neg
6246       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6247       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6248       LoOverflow = AddWithOverflow(LoBound, Prod,
6249                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
6250       HiBound = AddOne(Prod);
6251       HiOverflow = ProdOV ? -1 : 0;
6252     }
6253   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6254     if (CmpRHSV == 0) {       // (X / neg) op 0
6255       // e.g. X/-5 op 0  --> [-4, 5)
6256       LoBound = AddOne(DivRHS);
6257       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6258       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6259         HiOverflow = 1;            // [INTMIN+1, overflow)
6260         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6261       }
6262     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6263       // e.g. X/-5 op 3  --> [-19, -14)
6264       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6265       if (!LoOverflow)
6266         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
6267       HiBound = AddOne(Prod);
6268     } else {                       // (X / neg) op neg
6269       // e.g. X/-5 op -3  --> [15, 20)
6270       LoBound = Prod;
6271       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
6272       HiBound = Subtract(Prod, DivRHS);
6273     }
6274     
6275     // Dividing by a negative swaps the condition.  LT <-> GT
6276     Pred = ICmpInst::getSwappedPredicate(Pred);
6277   }
6278
6279   Value *X = DivI->getOperand(0);
6280   switch (Pred) {
6281   default: assert(0 && "Unhandled icmp opcode!");
6282   case ICmpInst::ICMP_EQ:
6283     if (LoOverflow && HiOverflow)
6284       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6285     else if (HiOverflow)
6286       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6287                           ICmpInst::ICMP_UGE, X, LoBound);
6288     else if (LoOverflow)
6289       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6290                           ICmpInst::ICMP_ULT, X, HiBound);
6291     else
6292       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6293   case ICmpInst::ICMP_NE:
6294     if (LoOverflow && HiOverflow)
6295       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6296     else if (HiOverflow)
6297       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6298                           ICmpInst::ICMP_ULT, X, LoBound);
6299     else if (LoOverflow)
6300       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6301                           ICmpInst::ICMP_UGE, X, HiBound);
6302     else
6303       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6304   case ICmpInst::ICMP_ULT:
6305   case ICmpInst::ICMP_SLT:
6306     if (LoOverflow == +1)   // Low bound is greater than input range.
6307       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6308     if (LoOverflow == -1)   // Low bound is less than input range.
6309       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6310     return new ICmpInst(Pred, X, LoBound);
6311   case ICmpInst::ICMP_UGT:
6312   case ICmpInst::ICMP_SGT:
6313     if (HiOverflow == +1)       // High bound greater than input range.
6314       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6315     else if (HiOverflow == -1)  // High bound less than input range.
6316       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6317     if (Pred == ICmpInst::ICMP_UGT)
6318       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6319     else
6320       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6321   }
6322 }
6323
6324
6325 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6326 ///
6327 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6328                                                           Instruction *LHSI,
6329                                                           ConstantInt *RHS) {
6330   const APInt &RHSV = RHS->getValue();
6331   
6332   switch (LHSI->getOpcode()) {
6333   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6334     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6335       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6336       // fold the xor.
6337       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6338           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6339         Value *CompareVal = LHSI->getOperand(0);
6340         
6341         // If the sign bit of the XorCST is not set, there is no change to
6342         // the operation, just stop using the Xor.
6343         if (!XorCST->getValue().isNegative()) {
6344           ICI.setOperand(0, CompareVal);
6345           AddToWorkList(LHSI);
6346           return &ICI;
6347         }
6348         
6349         // Was the old condition true if the operand is positive?
6350         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6351         
6352         // If so, the new one isn't.
6353         isTrueIfPositive ^= true;
6354         
6355         if (isTrueIfPositive)
6356           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6357         else
6358           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6359       }
6360     }
6361     break;
6362   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6363     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6364         LHSI->getOperand(0)->hasOneUse()) {
6365       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6366       
6367       // If the LHS is an AND of a truncating cast, we can widen the
6368       // and/compare to be the input width without changing the value
6369       // produced, eliminating a cast.
6370       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6371         // We can do this transformation if either the AND constant does not
6372         // have its sign bit set or if it is an equality comparison. 
6373         // Extending a relational comparison when we're checking the sign
6374         // bit would not work.
6375         if (Cast->hasOneUse() &&
6376             (ICI.isEquality() ||
6377              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6378           uint32_t BitWidth = 
6379             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6380           APInt NewCST = AndCST->getValue();
6381           NewCST.zext(BitWidth);
6382           APInt NewCI = RHSV;
6383           NewCI.zext(BitWidth);
6384           Instruction *NewAnd = 
6385             BinaryOperator::CreateAnd(Cast->getOperand(0),
6386                                       ConstantInt::get(NewCST),LHSI->getName());
6387           InsertNewInstBefore(NewAnd, ICI);
6388           return new ICmpInst(ICI.getPredicate(), NewAnd,
6389                               ConstantInt::get(NewCI));
6390         }
6391       }
6392       
6393       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6394       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6395       // happens a LOT in code produced by the C front-end, for bitfield
6396       // access.
6397       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6398       if (Shift && !Shift->isShift())
6399         Shift = 0;
6400       
6401       ConstantInt *ShAmt;
6402       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6403       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6404       const Type *AndTy = AndCST->getType();          // Type of the and.
6405       
6406       // We can fold this as long as we can't shift unknown bits
6407       // into the mask.  This can only happen with signed shift
6408       // rights, as they sign-extend.
6409       if (ShAmt) {
6410         bool CanFold = Shift->isLogicalShift();
6411         if (!CanFold) {
6412           // To test for the bad case of the signed shr, see if any
6413           // of the bits shifted in could be tested after the mask.
6414           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6415           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6416           
6417           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6418           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6419                AndCST->getValue()) == 0)
6420             CanFold = true;
6421         }
6422         
6423         if (CanFold) {
6424           Constant *NewCst;
6425           if (Shift->getOpcode() == Instruction::Shl)
6426             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6427           else
6428             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6429           
6430           // Check to see if we are shifting out any of the bits being
6431           // compared.
6432           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6433             // If we shifted bits out, the fold is not going to work out.
6434             // As a special case, check to see if this means that the
6435             // result is always true or false now.
6436             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6437               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6438             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6439               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6440           } else {
6441             ICI.setOperand(1, NewCst);
6442             Constant *NewAndCST;
6443             if (Shift->getOpcode() == Instruction::Shl)
6444               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6445             else
6446               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6447             LHSI->setOperand(1, NewAndCST);
6448             LHSI->setOperand(0, Shift->getOperand(0));
6449             AddToWorkList(Shift); // Shift is dead.
6450             AddUsesToWorkList(ICI);
6451             return &ICI;
6452           }
6453         }
6454       }
6455       
6456       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6457       // preferable because it allows the C<<Y expression to be hoisted out
6458       // of a loop if Y is invariant and X is not.
6459       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6460           ICI.isEquality() && !Shift->isArithmeticShift() &&
6461           isa<Instruction>(Shift->getOperand(0))) {
6462         // Compute C << Y.
6463         Value *NS;
6464         if (Shift->getOpcode() == Instruction::LShr) {
6465           NS = BinaryOperator::CreateShl(AndCST, 
6466                                          Shift->getOperand(1), "tmp");
6467         } else {
6468           // Insert a logical shift.
6469           NS = BinaryOperator::CreateLShr(AndCST,
6470                                           Shift->getOperand(1), "tmp");
6471         }
6472         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6473         
6474         // Compute X & (C << Y).
6475         Instruction *NewAnd = 
6476           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6477         InsertNewInstBefore(NewAnd, ICI);
6478         
6479         ICI.setOperand(0, NewAnd);
6480         return &ICI;
6481       }
6482     }
6483     break;
6484     
6485   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6486     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6487     if (!ShAmt) break;
6488     
6489     uint32_t TypeBits = RHSV.getBitWidth();
6490     
6491     // Check that the shift amount is in range.  If not, don't perform
6492     // undefined shifts.  When the shift is visited it will be
6493     // simplified.
6494     if (ShAmt->uge(TypeBits))
6495       break;
6496     
6497     if (ICI.isEquality()) {
6498       // If we are comparing against bits always shifted out, the
6499       // comparison cannot succeed.
6500       Constant *Comp =
6501         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6502       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6503         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6504         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6505         return ReplaceInstUsesWith(ICI, Cst);
6506       }
6507       
6508       if (LHSI->hasOneUse()) {
6509         // Otherwise strength reduce the shift into an and.
6510         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6511         Constant *Mask =
6512           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6513         
6514         Instruction *AndI =
6515           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6516                                     Mask, LHSI->getName()+".mask");
6517         Value *And = InsertNewInstBefore(AndI, ICI);
6518         return new ICmpInst(ICI.getPredicate(), And,
6519                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6520       }
6521     }
6522     
6523     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6524     bool TrueIfSigned = false;
6525     if (LHSI->hasOneUse() &&
6526         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6527       // (X << 31) <s 0  --> (X&1) != 0
6528       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6529                                            (TypeBits-ShAmt->getZExtValue()-1));
6530       Instruction *AndI =
6531         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6532                                   Mask, LHSI->getName()+".mask");
6533       Value *And = InsertNewInstBefore(AndI, ICI);
6534       
6535       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6536                           And, Constant::getNullValue(And->getType()));
6537     }
6538     break;
6539   }
6540     
6541   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6542   case Instruction::AShr: {
6543     // Only handle equality comparisons of shift-by-constant.
6544     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6545     if (!ShAmt || !ICI.isEquality()) break;
6546
6547     // Check that the shift amount is in range.  If not, don't perform
6548     // undefined shifts.  When the shift is visited it will be
6549     // simplified.
6550     uint32_t TypeBits = RHSV.getBitWidth();
6551     if (ShAmt->uge(TypeBits))
6552       break;
6553     
6554     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6555       
6556     // If we are comparing against bits always shifted out, the
6557     // comparison cannot succeed.
6558     APInt Comp = RHSV << ShAmtVal;
6559     if (LHSI->getOpcode() == Instruction::LShr)
6560       Comp = Comp.lshr(ShAmtVal);
6561     else
6562       Comp = Comp.ashr(ShAmtVal);
6563     
6564     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6565       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6566       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6567       return ReplaceInstUsesWith(ICI, Cst);
6568     }
6569     
6570     // Otherwise, check to see if the bits shifted out are known to be zero.
6571     // If so, we can compare against the unshifted value:
6572     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6573     if (LHSI->hasOneUse() &&
6574         MaskedValueIsZero(LHSI->getOperand(0), 
6575                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6576       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6577                           ConstantExpr::getShl(RHS, ShAmt));
6578     }
6579       
6580     if (LHSI->hasOneUse()) {
6581       // Otherwise strength reduce the shift into an and.
6582       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6583       Constant *Mask = ConstantInt::get(Val);
6584       
6585       Instruction *AndI =
6586         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6587                                   Mask, LHSI->getName()+".mask");
6588       Value *And = InsertNewInstBefore(AndI, ICI);
6589       return new ICmpInst(ICI.getPredicate(), And,
6590                           ConstantExpr::getShl(RHS, ShAmt));
6591     }
6592     break;
6593   }
6594     
6595   case Instruction::SDiv:
6596   case Instruction::UDiv:
6597     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6598     // Fold this div into the comparison, producing a range check. 
6599     // Determine, based on the divide type, what the range is being 
6600     // checked.  If there is an overflow on the low or high side, remember 
6601     // it, otherwise compute the range [low, hi) bounding the new value.
6602     // See: InsertRangeTest above for the kinds of replacements possible.
6603     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6604       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6605                                           DivRHS))
6606         return R;
6607     break;
6608
6609   case Instruction::Add:
6610     // Fold: icmp pred (add, X, C1), C2
6611
6612     if (!ICI.isEquality()) {
6613       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6614       if (!LHSC) break;
6615       const APInt &LHSV = LHSC->getValue();
6616
6617       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6618                             .subtract(LHSV);
6619
6620       if (ICI.isSignedPredicate()) {
6621         if (CR.getLower().isSignBit()) {
6622           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6623                               ConstantInt::get(CR.getUpper()));
6624         } else if (CR.getUpper().isSignBit()) {
6625           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6626                               ConstantInt::get(CR.getLower()));
6627         }
6628       } else {
6629         if (CR.getLower().isMinValue()) {
6630           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6631                               ConstantInt::get(CR.getUpper()));
6632         } else if (CR.getUpper().isMinValue()) {
6633           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6634                               ConstantInt::get(CR.getLower()));
6635         }
6636       }
6637     }
6638     break;
6639   }
6640   
6641   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6642   if (ICI.isEquality()) {
6643     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6644     
6645     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6646     // the second operand is a constant, simplify a bit.
6647     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6648       switch (BO->getOpcode()) {
6649       case Instruction::SRem:
6650         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6651         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6652           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6653           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6654             Instruction *NewRem =
6655               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6656                                          BO->getName());
6657             InsertNewInstBefore(NewRem, ICI);
6658             return new ICmpInst(ICI.getPredicate(), NewRem, 
6659                                 Constant::getNullValue(BO->getType()));
6660           }
6661         }
6662         break;
6663       case Instruction::Add:
6664         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6665         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6666           if (BO->hasOneUse())
6667             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6668                                 Subtract(RHS, BOp1C));
6669         } else if (RHSV == 0) {
6670           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6671           // efficiently invertible, or if the add has just this one use.
6672           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6673           
6674           if (Value *NegVal = dyn_castNegVal(BOp1))
6675             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6676           else if (Value *NegVal = dyn_castNegVal(BOp0))
6677             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6678           else if (BO->hasOneUse()) {
6679             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6680             InsertNewInstBefore(Neg, ICI);
6681             Neg->takeName(BO);
6682             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6683           }
6684         }
6685         break;
6686       case Instruction::Xor:
6687         // For the xor case, we can xor two constants together, eliminating
6688         // the explicit xor.
6689         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6690           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6691                               ConstantExpr::getXor(RHS, BOC));
6692         
6693         // FALLTHROUGH
6694       case Instruction::Sub:
6695         // Replace (([sub|xor] A, B) != 0) with (A != B)
6696         if (RHSV == 0)
6697           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6698                               BO->getOperand(1));
6699         break;
6700         
6701       case Instruction::Or:
6702         // If bits are being or'd in that are not present in the constant we
6703         // are comparing against, then the comparison could never succeed!
6704         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6705           Constant *NotCI = ConstantExpr::getNot(RHS);
6706           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6707             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6708                                                              isICMP_NE));
6709         }
6710         break;
6711         
6712       case Instruction::And:
6713         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6714           // If bits are being compared against that are and'd out, then the
6715           // comparison can never succeed!
6716           if ((RHSV & ~BOC->getValue()) != 0)
6717             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6718                                                              isICMP_NE));
6719           
6720           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6721           if (RHS == BOC && RHSV.isPowerOf2())
6722             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6723                                 ICmpInst::ICMP_NE, LHSI,
6724                                 Constant::getNullValue(RHS->getType()));
6725           
6726           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6727           if (isSignBit(BOC)) {
6728             Value *X = BO->getOperand(0);
6729             Constant *Zero = Constant::getNullValue(X->getType());
6730             ICmpInst::Predicate pred = isICMP_NE ? 
6731               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6732             return new ICmpInst(pred, X, Zero);
6733           }
6734           
6735           // ((X & ~7) == 0) --> X < 8
6736           if (RHSV == 0 && isHighOnes(BOC)) {
6737             Value *X = BO->getOperand(0);
6738             Constant *NegX = ConstantExpr::getNeg(BOC);
6739             ICmpInst::Predicate pred = isICMP_NE ? 
6740               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6741             return new ICmpInst(pred, X, NegX);
6742           }
6743         }
6744       default: break;
6745       }
6746     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6747       // Handle icmp {eq|ne} <intrinsic>, intcst.
6748       if (II->getIntrinsicID() == Intrinsic::bswap) {
6749         AddToWorkList(II);
6750         ICI.setOperand(0, II->getOperand(1));
6751         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6752         return &ICI;
6753       }
6754     }
6755   } else {  // Not a ICMP_EQ/ICMP_NE
6756             // If the LHS is a cast from an integral value of the same size, 
6757             // then since we know the RHS is a constant, try to simlify.
6758     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6759       Value *CastOp = Cast->getOperand(0);
6760       const Type *SrcTy = CastOp->getType();
6761       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6762       if (SrcTy->isInteger() && 
6763           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6764         // If this is an unsigned comparison, try to make the comparison use
6765         // smaller constant values.
6766         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6767           // X u< 128 => X s> -1
6768           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6769                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6770         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6771                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6772           // X u> 127 => X s< 0
6773           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6774                               Constant::getNullValue(SrcTy));
6775         }
6776       }
6777     }
6778   }
6779   return 0;
6780 }
6781
6782 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6783 /// We only handle extending casts so far.
6784 ///
6785 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6786   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6787   Value *LHSCIOp        = LHSCI->getOperand(0);
6788   const Type *SrcTy     = LHSCIOp->getType();
6789   const Type *DestTy    = LHSCI->getType();
6790   Value *RHSCIOp;
6791
6792   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6793   // integer type is the same size as the pointer type.
6794   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6795       getTargetData().getPointerSizeInBits() == 
6796          cast<IntegerType>(DestTy)->getBitWidth()) {
6797     Value *RHSOp = 0;
6798     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6799       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6800     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6801       RHSOp = RHSC->getOperand(0);
6802       // If the pointer types don't match, insert a bitcast.
6803       if (LHSCIOp->getType() != RHSOp->getType())
6804         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6805     }
6806
6807     if (RHSOp)
6808       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6809   }
6810   
6811   // The code below only handles extension cast instructions, so far.
6812   // Enforce this.
6813   if (LHSCI->getOpcode() != Instruction::ZExt &&
6814       LHSCI->getOpcode() != Instruction::SExt)
6815     return 0;
6816
6817   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6818   bool isSignedCmp = ICI.isSignedPredicate();
6819
6820   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6821     // Not an extension from the same type?
6822     RHSCIOp = CI->getOperand(0);
6823     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6824       return 0;
6825     
6826     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6827     // and the other is a zext), then we can't handle this.
6828     if (CI->getOpcode() != LHSCI->getOpcode())
6829       return 0;
6830
6831     // Deal with equality cases early.
6832     if (ICI.isEquality())
6833       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6834
6835     // A signed comparison of sign extended values simplifies into a
6836     // signed comparison.
6837     if (isSignedCmp && isSignedExt)
6838       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6839
6840     // The other three cases all fold into an unsigned comparison.
6841     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6842   }
6843
6844   // If we aren't dealing with a constant on the RHS, exit early
6845   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6846   if (!CI)
6847     return 0;
6848
6849   // Compute the constant that would happen if we truncated to SrcTy then
6850   // reextended to DestTy.
6851   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6852   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6853
6854   // If the re-extended constant didn't change...
6855   if (Res2 == CI) {
6856     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6857     // For example, we might have:
6858     //    %A = sext short %X to uint
6859     //    %B = icmp ugt uint %A, 1330
6860     // It is incorrect to transform this into 
6861     //    %B = icmp ugt short %X, 1330 
6862     // because %A may have negative value. 
6863     //
6864     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6865     // OR operation is EQ/NE.
6866     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6867       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6868     else
6869       return 0;
6870   }
6871
6872   // The re-extended constant changed so the constant cannot be represented 
6873   // in the shorter type. Consequently, we cannot emit a simple comparison.
6874
6875   // First, handle some easy cases. We know the result cannot be equal at this
6876   // point so handle the ICI.isEquality() cases
6877   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6878     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6879   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6880     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6881
6882   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6883   // should have been folded away previously and not enter in here.
6884   Value *Result;
6885   if (isSignedCmp) {
6886     // We're performing a signed comparison.
6887     if (cast<ConstantInt>(CI)->getValue().isNegative())
6888       Result = ConstantInt::getFalse();          // X < (small) --> false
6889     else
6890       Result = ConstantInt::getTrue();           // X < (large) --> true
6891   } else {
6892     // We're performing an unsigned comparison.
6893     if (isSignedExt) {
6894       // We're performing an unsigned comp with a sign extended value.
6895       // This is true if the input is >= 0. [aka >s -1]
6896       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6897       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6898                                    NegOne, ICI.getName()), ICI);
6899     } else {
6900       // Unsigned extend & unsigned compare -> always true.
6901       Result = ConstantInt::getTrue();
6902     }
6903   }
6904
6905   // Finally, return the value computed.
6906   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6907       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6908     return ReplaceInstUsesWith(ICI, Result);
6909   } else {
6910     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6911             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6912            "ICmp should be folded!");
6913     if (Constant *CI = dyn_cast<Constant>(Result))
6914       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6915     else
6916       return BinaryOperator::CreateNot(Result);
6917   }
6918 }
6919
6920 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6921   return commonShiftTransforms(I);
6922 }
6923
6924 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6925   return commonShiftTransforms(I);
6926 }
6927
6928 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6929   if (Instruction *R = commonShiftTransforms(I))
6930     return R;
6931   
6932   Value *Op0 = I.getOperand(0);
6933   
6934   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6935   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6936     if (CSI->isAllOnesValue())
6937       return ReplaceInstUsesWith(I, CSI);
6938   
6939   // See if we can turn a signed shr into an unsigned shr.
6940   if (MaskedValueIsZero(Op0, 
6941                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6942     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6943   
6944   return 0;
6945 }
6946
6947 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6948   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6949   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6950
6951   // shl X, 0 == X and shr X, 0 == X
6952   // shl 0, X == 0 and shr 0, X == 0
6953   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6954       Op0 == Constant::getNullValue(Op0->getType()))
6955     return ReplaceInstUsesWith(I, Op0);
6956   
6957   if (isa<UndefValue>(Op0)) {            
6958     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6959       return ReplaceInstUsesWith(I, Op0);
6960     else                                    // undef << X -> 0, undef >>u X -> 0
6961       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6962   }
6963   if (isa<UndefValue>(Op1)) {
6964     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6965       return ReplaceInstUsesWith(I, Op0);          
6966     else                                     // X << undef, X >>u undef -> 0
6967       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6968   }
6969
6970   // Try to fold constant and into select arguments.
6971   if (isa<Constant>(Op0))
6972     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6973       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6974         return R;
6975
6976   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6977     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6978       return Res;
6979   return 0;
6980 }
6981
6982 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6983                                                BinaryOperator &I) {
6984   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6985
6986   // See if we can simplify any instructions used by the instruction whose sole 
6987   // purpose is to compute bits we don't care about.
6988   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6989   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6990   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6991                            KnownZero, KnownOne))
6992     return &I;
6993   
6994   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6995   // of a signed value.
6996   //
6997   if (Op1->uge(TypeBits)) {
6998     if (I.getOpcode() != Instruction::AShr)
6999       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7000     else {
7001       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7002       return &I;
7003     }
7004   }
7005   
7006   // ((X*C1) << C2) == (X * (C1 << C2))
7007   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7008     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7009       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7010         return BinaryOperator::CreateMul(BO->getOperand(0),
7011                                          ConstantExpr::getShl(BOOp, Op1));
7012   
7013   // Try to fold constant and into select arguments.
7014   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7015     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7016       return R;
7017   if (isa<PHINode>(Op0))
7018     if (Instruction *NV = FoldOpIntoPhi(I))
7019       return NV;
7020   
7021   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7022   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7023     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7024     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7025     // place.  Don't try to do this transformation in this case.  Also, we
7026     // require that the input operand is a shift-by-constant so that we have
7027     // confidence that the shifts will get folded together.  We could do this
7028     // xform in more cases, but it is unlikely to be profitable.
7029     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7030         isa<ConstantInt>(TrOp->getOperand(1))) {
7031       // Okay, we'll do this xform.  Make the shift of shift.
7032       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7033       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7034                                                 I.getName());
7035       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7036
7037       // For logical shifts, the truncation has the effect of making the high
7038       // part of the register be zeros.  Emulate this by inserting an AND to
7039       // clear the top bits as needed.  This 'and' will usually be zapped by
7040       // other xforms later if dead.
7041       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7042       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7043       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7044       
7045       // The mask we constructed says what the trunc would do if occurring
7046       // between the shifts.  We want to know the effect *after* the second
7047       // shift.  We know that it is a logical shift by a constant, so adjust the
7048       // mask as appropriate.
7049       if (I.getOpcode() == Instruction::Shl)
7050         MaskV <<= Op1->getZExtValue();
7051       else {
7052         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7053         MaskV = MaskV.lshr(Op1->getZExtValue());
7054       }
7055
7056       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7057                                                    TI->getName());
7058       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7059
7060       // Return the value truncated to the interesting size.
7061       return new TruncInst(And, I.getType());
7062     }
7063   }
7064   
7065   if (Op0->hasOneUse()) {
7066     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7067       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7068       Value *V1, *V2;
7069       ConstantInt *CC;
7070       switch (Op0BO->getOpcode()) {
7071         default: break;
7072         case Instruction::Add:
7073         case Instruction::And:
7074         case Instruction::Or:
7075         case Instruction::Xor: {
7076           // These operators commute.
7077           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7078           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7079               match(Op0BO->getOperand(1),
7080                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7081             Instruction *YS = BinaryOperator::CreateShl(
7082                                             Op0BO->getOperand(0), Op1,
7083                                             Op0BO->getName());
7084             InsertNewInstBefore(YS, I); // (Y << C)
7085             Instruction *X = 
7086               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7087                                      Op0BO->getOperand(1)->getName());
7088             InsertNewInstBefore(X, I);  // (X + (Y << C))
7089             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7090             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7091                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7092           }
7093           
7094           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7095           Value *Op0BOOp1 = Op0BO->getOperand(1);
7096           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7097               match(Op0BOOp1, 
7098                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
7099               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7100               V2 == Op1) {
7101             Instruction *YS = BinaryOperator::CreateShl(
7102                                                      Op0BO->getOperand(0), Op1,
7103                                                      Op0BO->getName());
7104             InsertNewInstBefore(YS, I); // (Y << C)
7105             Instruction *XM =
7106               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7107                                         V1->getName()+".mask");
7108             InsertNewInstBefore(XM, I); // X & (CC << C)
7109             
7110             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7111           }
7112         }
7113           
7114         // FALL THROUGH.
7115         case Instruction::Sub: {
7116           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7117           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7118               match(Op0BO->getOperand(0),
7119                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7120             Instruction *YS = BinaryOperator::CreateShl(
7121                                                      Op0BO->getOperand(1), Op1,
7122                                                      Op0BO->getName());
7123             InsertNewInstBefore(YS, I); // (Y << C)
7124             Instruction *X =
7125               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7126                                      Op0BO->getOperand(0)->getName());
7127             InsertNewInstBefore(X, I);  // (X + (Y << C))
7128             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7129             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7130                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7131           }
7132           
7133           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7134           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7135               match(Op0BO->getOperand(0),
7136                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7137                           m_ConstantInt(CC))) && V2 == Op1 &&
7138               cast<BinaryOperator>(Op0BO->getOperand(0))
7139                   ->getOperand(0)->hasOneUse()) {
7140             Instruction *YS = BinaryOperator::CreateShl(
7141                                                      Op0BO->getOperand(1), Op1,
7142                                                      Op0BO->getName());
7143             InsertNewInstBefore(YS, I); // (Y << C)
7144             Instruction *XM =
7145               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7146                                         V1->getName()+".mask");
7147             InsertNewInstBefore(XM, I); // X & (CC << C)
7148             
7149             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7150           }
7151           
7152           break;
7153         }
7154       }
7155       
7156       
7157       // If the operand is an bitwise operator with a constant RHS, and the
7158       // shift is the only use, we can pull it out of the shift.
7159       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7160         bool isValid = true;     // Valid only for And, Or, Xor
7161         bool highBitSet = false; // Transform if high bit of constant set?
7162         
7163         switch (Op0BO->getOpcode()) {
7164           default: isValid = false; break;   // Do not perform transform!
7165           case Instruction::Add:
7166             isValid = isLeftShift;
7167             break;
7168           case Instruction::Or:
7169           case Instruction::Xor:
7170             highBitSet = false;
7171             break;
7172           case Instruction::And:
7173             highBitSet = true;
7174             break;
7175         }
7176         
7177         // If this is a signed shift right, and the high bit is modified
7178         // by the logical operation, do not perform the transformation.
7179         // The highBitSet boolean indicates the value of the high bit of
7180         // the constant which would cause it to be modified for this
7181         // operation.
7182         //
7183         if (isValid && I.getOpcode() == Instruction::AShr)
7184           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7185         
7186         if (isValid) {
7187           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7188           
7189           Instruction *NewShift =
7190             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7191           InsertNewInstBefore(NewShift, I);
7192           NewShift->takeName(Op0BO);
7193           
7194           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7195                                         NewRHS);
7196         }
7197       }
7198     }
7199   }
7200   
7201   // Find out if this is a shift of a shift by a constant.
7202   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7203   if (ShiftOp && !ShiftOp->isShift())
7204     ShiftOp = 0;
7205   
7206   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7207     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7208     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7209     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7210     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7211     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7212     Value *X = ShiftOp->getOperand(0);
7213     
7214     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7215     if (AmtSum > TypeBits)
7216       AmtSum = TypeBits;
7217     
7218     const IntegerType *Ty = cast<IntegerType>(I.getType());
7219     
7220     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7221     if (I.getOpcode() == ShiftOp->getOpcode()) {
7222       return BinaryOperator::Create(I.getOpcode(), X,
7223                                     ConstantInt::get(Ty, AmtSum));
7224     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7225                I.getOpcode() == Instruction::AShr) {
7226       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7227       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7228     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7229                I.getOpcode() == Instruction::LShr) {
7230       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7231       Instruction *Shift =
7232         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7233       InsertNewInstBefore(Shift, I);
7234
7235       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7236       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7237     }
7238     
7239     // Okay, if we get here, one shift must be left, and the other shift must be
7240     // right.  See if the amounts are equal.
7241     if (ShiftAmt1 == ShiftAmt2) {
7242       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7243       if (I.getOpcode() == Instruction::Shl) {
7244         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7245         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7246       }
7247       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7248       if (I.getOpcode() == Instruction::LShr) {
7249         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7250         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7251       }
7252       // We can simplify ((X << C) >>s C) into a trunc + sext.
7253       // NOTE: we could do this for any C, but that would make 'unusual' integer
7254       // types.  For now, just stick to ones well-supported by the code
7255       // generators.
7256       const Type *SExtType = 0;
7257       switch (Ty->getBitWidth() - ShiftAmt1) {
7258       case 1  :
7259       case 8  :
7260       case 16 :
7261       case 32 :
7262       case 64 :
7263       case 128:
7264         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7265         break;
7266       default: break;
7267       }
7268       if (SExtType) {
7269         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7270         InsertNewInstBefore(NewTrunc, I);
7271         return new SExtInst(NewTrunc, Ty);
7272       }
7273       // Otherwise, we can't handle it yet.
7274     } else if (ShiftAmt1 < ShiftAmt2) {
7275       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7276       
7277       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7278       if (I.getOpcode() == Instruction::Shl) {
7279         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7280                ShiftOp->getOpcode() == Instruction::AShr);
7281         Instruction *Shift =
7282           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7283         InsertNewInstBefore(Shift, I);
7284         
7285         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7286         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7287       }
7288       
7289       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7290       if (I.getOpcode() == Instruction::LShr) {
7291         assert(ShiftOp->getOpcode() == Instruction::Shl);
7292         Instruction *Shift =
7293           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7294         InsertNewInstBefore(Shift, I);
7295         
7296         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7297         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7298       }
7299       
7300       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7301     } else {
7302       assert(ShiftAmt2 < ShiftAmt1);
7303       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7304
7305       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7306       if (I.getOpcode() == Instruction::Shl) {
7307         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7308                ShiftOp->getOpcode() == Instruction::AShr);
7309         Instruction *Shift =
7310           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7311                                  ConstantInt::get(Ty, ShiftDiff));
7312         InsertNewInstBefore(Shift, I);
7313         
7314         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7315         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7316       }
7317       
7318       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7319       if (I.getOpcode() == Instruction::LShr) {
7320         assert(ShiftOp->getOpcode() == Instruction::Shl);
7321         Instruction *Shift =
7322           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7323         InsertNewInstBefore(Shift, I);
7324         
7325         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7326         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7327       }
7328       
7329       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7330     }
7331   }
7332   return 0;
7333 }
7334
7335
7336 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7337 /// expression.  If so, decompose it, returning some value X, such that Val is
7338 /// X*Scale+Offset.
7339 ///
7340 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7341                                         int &Offset) {
7342   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7343   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7344     Offset = CI->getZExtValue();
7345     Scale  = 0;
7346     return ConstantInt::get(Type::Int32Ty, 0);
7347   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7348     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7349       if (I->getOpcode() == Instruction::Shl) {
7350         // This is a value scaled by '1 << the shift amt'.
7351         Scale = 1U << RHS->getZExtValue();
7352         Offset = 0;
7353         return I->getOperand(0);
7354       } else if (I->getOpcode() == Instruction::Mul) {
7355         // This value is scaled by 'RHS'.
7356         Scale = RHS->getZExtValue();
7357         Offset = 0;
7358         return I->getOperand(0);
7359       } else if (I->getOpcode() == Instruction::Add) {
7360         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7361         // where C1 is divisible by C2.
7362         unsigned SubScale;
7363         Value *SubVal = 
7364           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7365         Offset += RHS->getZExtValue();
7366         Scale = SubScale;
7367         return SubVal;
7368       }
7369     }
7370   }
7371
7372   // Otherwise, we can't look past this.
7373   Scale = 1;
7374   Offset = 0;
7375   return Val;
7376 }
7377
7378
7379 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7380 /// try to eliminate the cast by moving the type information into the alloc.
7381 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7382                                                    AllocationInst &AI) {
7383   const PointerType *PTy = cast<PointerType>(CI.getType());
7384   
7385   // Remove any uses of AI that are dead.
7386   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7387   
7388   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7389     Instruction *User = cast<Instruction>(*UI++);
7390     if (isInstructionTriviallyDead(User)) {
7391       while (UI != E && *UI == User)
7392         ++UI; // If this instruction uses AI more than once, don't break UI.
7393       
7394       ++NumDeadInst;
7395       DOUT << "IC: DCE: " << *User;
7396       EraseInstFromFunction(*User);
7397     }
7398   }
7399   
7400   // Get the type really allocated and the type casted to.
7401   const Type *AllocElTy = AI.getAllocatedType();
7402   const Type *CastElTy = PTy->getElementType();
7403   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7404
7405   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7406   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7407   if (CastElTyAlign < AllocElTyAlign) return 0;
7408
7409   // If the allocation has multiple uses, only promote it if we are strictly
7410   // increasing the alignment of the resultant allocation.  If we keep it the
7411   // same, we open the door to infinite loops of various kinds.
7412   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7413
7414   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7415   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7416   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7417
7418   // See if we can satisfy the modulus by pulling a scale out of the array
7419   // size argument.
7420   unsigned ArraySizeScale;
7421   int ArrayOffset;
7422   Value *NumElements = // See if the array size is a decomposable linear expr.
7423     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7424  
7425   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7426   // do the xform.
7427   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7428       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7429
7430   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7431   Value *Amt = 0;
7432   if (Scale == 1) {
7433     Amt = NumElements;
7434   } else {
7435     // If the allocation size is constant, form a constant mul expression
7436     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7437     if (isa<ConstantInt>(NumElements))
7438       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7439     // otherwise multiply the amount and the number of elements
7440     else if (Scale != 1) {
7441       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7442       Amt = InsertNewInstBefore(Tmp, AI);
7443     }
7444   }
7445   
7446   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7447     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7448     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7449     Amt = InsertNewInstBefore(Tmp, AI);
7450   }
7451   
7452   AllocationInst *New;
7453   if (isa<MallocInst>(AI))
7454     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7455   else
7456     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7457   InsertNewInstBefore(New, AI);
7458   New->takeName(&AI);
7459   
7460   // If the allocation has multiple uses, insert a cast and change all things
7461   // that used it to use the new cast.  This will also hack on CI, but it will
7462   // die soon.
7463   if (!AI.hasOneUse()) {
7464     AddUsesToWorkList(AI);
7465     // New is the allocation instruction, pointer typed. AI is the original
7466     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7467     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7468     InsertNewInstBefore(NewCast, AI);
7469     AI.replaceAllUsesWith(NewCast);
7470   }
7471   return ReplaceInstUsesWith(CI, New);
7472 }
7473
7474 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7475 /// and return it as type Ty without inserting any new casts and without
7476 /// changing the computed value.  This is used by code that tries to decide
7477 /// whether promoting or shrinking integer operations to wider or smaller types
7478 /// will allow us to eliminate a truncate or extend.
7479 ///
7480 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7481 /// extension operation if Ty is larger.
7482 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7483                                               unsigned CastOpc,
7484                                               int &NumCastsRemoved) {
7485   // We can always evaluate constants in another type.
7486   if (isa<ConstantInt>(V))
7487     return true;
7488   
7489   Instruction *I = dyn_cast<Instruction>(V);
7490   if (!I) return false;
7491   
7492   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7493   
7494   // If this is an extension or truncate, we can often eliminate it.
7495   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7496     // If this is a cast from the destination type, we can trivially eliminate
7497     // it, and this will remove a cast overall.
7498     if (I->getOperand(0)->getType() == Ty) {
7499       // If the first operand is itself a cast, and is eliminable, do not count
7500       // this as an eliminable cast.  We would prefer to eliminate those two
7501       // casts first.
7502       if (!isa<CastInst>(I->getOperand(0)))
7503         ++NumCastsRemoved;
7504       return true;
7505     }
7506   }
7507
7508   // We can't extend or shrink something that has multiple uses: doing so would
7509   // require duplicating the instruction in general, which isn't profitable.
7510   if (!I->hasOneUse()) return false;
7511
7512   switch (I->getOpcode()) {
7513   case Instruction::Add:
7514   case Instruction::Sub:
7515   case Instruction::And:
7516   case Instruction::Or:
7517   case Instruction::Xor:
7518     // These operators can all arbitrarily be extended or truncated.
7519     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7520                                       NumCastsRemoved) &&
7521            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7522                                       NumCastsRemoved);
7523
7524   case Instruction::Mul:
7525     // A multiply can be truncated by truncating its operands.
7526     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
7527            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7528                                       NumCastsRemoved) &&
7529            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7530                                       NumCastsRemoved);
7531
7532   case Instruction::Shl:
7533     // If we are truncating the result of this SHL, and if it's a shift of a
7534     // constant amount, we can always perform a SHL in a smaller type.
7535     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7536       uint32_t BitWidth = Ty->getBitWidth();
7537       if (BitWidth < OrigTy->getBitWidth() && 
7538           CI->getLimitedValue(BitWidth) < BitWidth)
7539         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7540                                           NumCastsRemoved);
7541     }
7542     break;
7543   case Instruction::LShr:
7544     // If this is a truncate of a logical shr, we can truncate it to a smaller
7545     // lshr iff we know that the bits we would otherwise be shifting in are
7546     // already zeros.
7547     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7548       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7549       uint32_t BitWidth = Ty->getBitWidth();
7550       if (BitWidth < OrigBitWidth &&
7551           MaskedValueIsZero(I->getOperand(0),
7552             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7553           CI->getLimitedValue(BitWidth) < BitWidth) {
7554         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7555                                           NumCastsRemoved);
7556       }
7557     }
7558     break;
7559   case Instruction::ZExt:
7560   case Instruction::SExt:
7561   case Instruction::Trunc:
7562     // If this is the same kind of case as our original (e.g. zext+zext), we
7563     // can safely replace it.  Note that replacing it does not reduce the number
7564     // of casts in the input.
7565     if (I->getOpcode() == CastOpc)
7566       return true;
7567     
7568     break;
7569   default:
7570     // TODO: Can handle more cases here.
7571     break;
7572   }
7573   
7574   return false;
7575 }
7576
7577 /// EvaluateInDifferentType - Given an expression that 
7578 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7579 /// evaluate the expression.
7580 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7581                                              bool isSigned) {
7582   if (Constant *C = dyn_cast<Constant>(V))
7583     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7584
7585   // Otherwise, it must be an instruction.
7586   Instruction *I = cast<Instruction>(V);
7587   Instruction *Res = 0;
7588   switch (I->getOpcode()) {
7589   case Instruction::Add:
7590   case Instruction::Sub:
7591   case Instruction::Mul:
7592   case Instruction::And:
7593   case Instruction::Or:
7594   case Instruction::Xor:
7595   case Instruction::AShr:
7596   case Instruction::LShr:
7597   case Instruction::Shl: {
7598     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7599     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7600     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7601                                  LHS, RHS, I->getName());
7602     break;
7603   }    
7604   case Instruction::Trunc:
7605   case Instruction::ZExt:
7606   case Instruction::SExt:
7607     // If the source type of the cast is the type we're trying for then we can
7608     // just return the source.  There's no need to insert it because it is not
7609     // new.
7610     if (I->getOperand(0)->getType() == Ty)
7611       return I->getOperand(0);
7612     
7613     // Otherwise, must be the same type of case, so just reinsert a new one.
7614     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7615                            Ty, I->getName());
7616     break;
7617   default: 
7618     // TODO: Can handle more cases here.
7619     assert(0 && "Unreachable!");
7620     break;
7621   }
7622   
7623   return InsertNewInstBefore(Res, *I);
7624 }
7625
7626 /// @brief Implement the transforms common to all CastInst visitors.
7627 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7628   Value *Src = CI.getOperand(0);
7629
7630   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7631   // eliminate it now.
7632   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7633     if (Instruction::CastOps opc = 
7634         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7635       // The first cast (CSrc) is eliminable so we need to fix up or replace
7636       // the second cast (CI). CSrc will then have a good chance of being dead.
7637       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7638     }
7639   }
7640
7641   // If we are casting a select then fold the cast into the select
7642   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7643     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7644       return NV;
7645
7646   // If we are casting a PHI then fold the cast into the PHI
7647   if (isa<PHINode>(Src))
7648     if (Instruction *NV = FoldOpIntoPhi(CI))
7649       return NV;
7650   
7651   return 0;
7652 }
7653
7654 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7655 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7656   Value *Src = CI.getOperand(0);
7657   
7658   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7659     // If casting the result of a getelementptr instruction with no offset, turn
7660     // this into a cast of the original pointer!
7661     if (GEP->hasAllZeroIndices()) {
7662       // Changing the cast operand is usually not a good idea but it is safe
7663       // here because the pointer operand is being replaced with another 
7664       // pointer operand so the opcode doesn't need to change.
7665       AddToWorkList(GEP);
7666       CI.setOperand(0, GEP->getOperand(0));
7667       return &CI;
7668     }
7669     
7670     // If the GEP has a single use, and the base pointer is a bitcast, and the
7671     // GEP computes a constant offset, see if we can convert these three
7672     // instructions into fewer.  This typically happens with unions and other
7673     // non-type-safe code.
7674     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7675       if (GEP->hasAllConstantIndices()) {
7676         // We are guaranteed to get a constant from EmitGEPOffset.
7677         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7678         int64_t Offset = OffsetV->getSExtValue();
7679         
7680         // Get the base pointer input of the bitcast, and the type it points to.
7681         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7682         const Type *GEPIdxTy =
7683           cast<PointerType>(OrigBase->getType())->getElementType();
7684         if (GEPIdxTy->isSized()) {
7685           SmallVector<Value*, 8> NewIndices;
7686           
7687           // Start with the index over the outer type.  Note that the type size
7688           // might be zero (even if the offset isn't zero) if the indexed type
7689           // is something like [0 x {int, int}]
7690           const Type *IntPtrTy = TD->getIntPtrType();
7691           int64_t FirstIdx = 0;
7692           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7693             FirstIdx = Offset/TySize;
7694             Offset %= TySize;
7695           
7696             // Handle silly modulus not returning values values [0..TySize).
7697             if (Offset < 0) {
7698               --FirstIdx;
7699               Offset += TySize;
7700               assert(Offset >= 0);
7701             }
7702             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7703           }
7704           
7705           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7706
7707           // Index into the types.  If we fail, set OrigBase to null.
7708           while (Offset) {
7709             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7710               const StructLayout *SL = TD->getStructLayout(STy);
7711               if (Offset < (int64_t)SL->getSizeInBytes()) {
7712                 unsigned Elt = SL->getElementContainingOffset(Offset);
7713                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7714               
7715                 Offset -= SL->getElementOffset(Elt);
7716                 GEPIdxTy = STy->getElementType(Elt);
7717               } else {
7718                 // Otherwise, we can't index into this, bail out.
7719                 Offset = 0;
7720                 OrigBase = 0;
7721               }
7722             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7723               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7724               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7725                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7726                 Offset %= EltSize;
7727               } else {
7728                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7729               }
7730               GEPIdxTy = STy->getElementType();
7731             } else {
7732               // Otherwise, we can't index into this, bail out.
7733               Offset = 0;
7734               OrigBase = 0;
7735             }
7736           }
7737           if (OrigBase) {
7738             // If we were able to index down into an element, create the GEP
7739             // and bitcast the result.  This eliminates one bitcast, potentially
7740             // two.
7741             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7742                                                           NewIndices.begin(),
7743                                                           NewIndices.end(), "");
7744             InsertNewInstBefore(NGEP, CI);
7745             NGEP->takeName(GEP);
7746             
7747             if (isa<BitCastInst>(CI))
7748               return new BitCastInst(NGEP, CI.getType());
7749             assert(isa<PtrToIntInst>(CI));
7750             return new PtrToIntInst(NGEP, CI.getType());
7751           }
7752         }
7753       }      
7754     }
7755   }
7756     
7757   return commonCastTransforms(CI);
7758 }
7759
7760
7761
7762 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7763 /// integer types. This function implements the common transforms for all those
7764 /// cases.
7765 /// @brief Implement the transforms common to CastInst with integer operands
7766 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7767   if (Instruction *Result = commonCastTransforms(CI))
7768     return Result;
7769
7770   Value *Src = CI.getOperand(0);
7771   const Type *SrcTy = Src->getType();
7772   const Type *DestTy = CI.getType();
7773   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7774   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7775
7776   // See if we can simplify any instructions used by the LHS whose sole 
7777   // purpose is to compute bits we don't care about.
7778   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7779   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7780                            KnownZero, KnownOne))
7781     return &CI;
7782
7783   // If the source isn't an instruction or has more than one use then we
7784   // can't do anything more. 
7785   Instruction *SrcI = dyn_cast<Instruction>(Src);
7786   if (!SrcI || !Src->hasOneUse())
7787     return 0;
7788
7789   // Attempt to propagate the cast into the instruction for int->int casts.
7790   int NumCastsRemoved = 0;
7791   if (!isa<BitCastInst>(CI) &&
7792       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7793                                  CI.getOpcode(), NumCastsRemoved)) {
7794     // If this cast is a truncate, evaluting in a different type always
7795     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7796     // we need to do an AND to maintain the clear top-part of the computation,
7797     // so we require that the input have eliminated at least one cast.  If this
7798     // is a sign extension, we insert two new casts (to do the extension) so we
7799     // require that two casts have been eliminated.
7800     bool DoXForm;
7801     switch (CI.getOpcode()) {
7802     default:
7803       // All the others use floating point so we shouldn't actually 
7804       // get here because of the check above.
7805       assert(0 && "Unknown cast type");
7806     case Instruction::Trunc:
7807       DoXForm = true;
7808       break;
7809     case Instruction::ZExt:
7810       DoXForm = NumCastsRemoved >= 1;
7811       break;
7812     case Instruction::SExt:
7813       DoXForm = NumCastsRemoved >= 2;
7814       break;
7815     }
7816     
7817     if (DoXForm) {
7818       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7819                                            CI.getOpcode() == Instruction::SExt);
7820       assert(Res->getType() == DestTy);
7821       switch (CI.getOpcode()) {
7822       default: assert(0 && "Unknown cast type!");
7823       case Instruction::Trunc:
7824       case Instruction::BitCast:
7825         // Just replace this cast with the result.
7826         return ReplaceInstUsesWith(CI, Res);
7827       case Instruction::ZExt: {
7828         // We need to emit an AND to clear the high bits.
7829         assert(SrcBitSize < DestBitSize && "Not a zext?");
7830         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7831                                                             SrcBitSize));
7832         return BinaryOperator::CreateAnd(Res, C);
7833       }
7834       case Instruction::SExt:
7835         // We need to emit a cast to truncate, then a cast to sext.
7836         return CastInst::Create(Instruction::SExt,
7837             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7838                              CI), DestTy);
7839       }
7840     }
7841   }
7842   
7843   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7844   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7845
7846   switch (SrcI->getOpcode()) {
7847   case Instruction::Add:
7848   case Instruction::Mul:
7849   case Instruction::And:
7850   case Instruction::Or:
7851   case Instruction::Xor:
7852     // If we are discarding information, rewrite.
7853     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7854       // Don't insert two casts if they cannot be eliminated.  We allow 
7855       // two casts to be inserted if the sizes are the same.  This could 
7856       // only be converting signedness, which is a noop.
7857       if (DestBitSize == SrcBitSize || 
7858           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7859           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7860         Instruction::CastOps opcode = CI.getOpcode();
7861         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7862         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7863         return BinaryOperator::Create(
7864             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7865       }
7866     }
7867
7868     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7869     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7870         SrcI->getOpcode() == Instruction::Xor &&
7871         Op1 == ConstantInt::getTrue() &&
7872         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7873       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7874       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7875     }
7876     break;
7877   case Instruction::SDiv:
7878   case Instruction::UDiv:
7879   case Instruction::SRem:
7880   case Instruction::URem:
7881     // If we are just changing the sign, rewrite.
7882     if (DestBitSize == SrcBitSize) {
7883       // Don't insert two casts if they cannot be eliminated.  We allow 
7884       // two casts to be inserted if the sizes are the same.  This could 
7885       // only be converting signedness, which is a noop.
7886       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7887           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7888         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7889                                               Op0, DestTy, SrcI);
7890         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7891                                               Op1, DestTy, SrcI);
7892         return BinaryOperator::Create(
7893           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7894       }
7895     }
7896     break;
7897
7898   case Instruction::Shl:
7899     // Allow changing the sign of the source operand.  Do not allow 
7900     // changing the size of the shift, UNLESS the shift amount is a 
7901     // constant.  We must not change variable sized shifts to a smaller 
7902     // size, because it is undefined to shift more bits out than exist 
7903     // in the value.
7904     if (DestBitSize == SrcBitSize ||
7905         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7906       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7907           Instruction::BitCast : Instruction::Trunc);
7908       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7909       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7910       return BinaryOperator::CreateShl(Op0c, Op1c);
7911     }
7912     break;
7913   case Instruction::AShr:
7914     // If this is a signed shr, and if all bits shifted in are about to be
7915     // truncated off, turn it into an unsigned shr to allow greater
7916     // simplifications.
7917     if (DestBitSize < SrcBitSize &&
7918         isa<ConstantInt>(Op1)) {
7919       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7920       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7921         // Insert the new logical shift right.
7922         return BinaryOperator::CreateLShr(Op0, Op1);
7923       }
7924     }
7925     break;
7926   }
7927   return 0;
7928 }
7929
7930 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7931   if (Instruction *Result = commonIntCastTransforms(CI))
7932     return Result;
7933   
7934   Value *Src = CI.getOperand(0);
7935   const Type *Ty = CI.getType();
7936   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7937   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7938   
7939   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7940     switch (SrcI->getOpcode()) {
7941     default: break;
7942     case Instruction::LShr:
7943       // We can shrink lshr to something smaller if we know the bits shifted in
7944       // are already zeros.
7945       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7946         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7947         
7948         // Get a mask for the bits shifting in.
7949         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7950         Value* SrcIOp0 = SrcI->getOperand(0);
7951         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7952           if (ShAmt >= DestBitWidth)        // All zeros.
7953             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7954
7955           // Okay, we can shrink this.  Truncate the input, then return a new
7956           // shift.
7957           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7958           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7959                                        Ty, CI);
7960           return BinaryOperator::CreateLShr(V1, V2);
7961         }
7962       } else {     // This is a variable shr.
7963         
7964         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7965         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7966         // loop-invariant and CSE'd.
7967         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7968           Value *One = ConstantInt::get(SrcI->getType(), 1);
7969
7970           Value *V = InsertNewInstBefore(
7971               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7972                                      "tmp"), CI);
7973           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7974                                                             SrcI->getOperand(0),
7975                                                             "tmp"), CI);
7976           Value *Zero = Constant::getNullValue(V->getType());
7977           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7978         }
7979       }
7980       break;
7981     }
7982   }
7983   
7984   return 0;
7985 }
7986
7987 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7988 /// in order to eliminate the icmp.
7989 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7990                                              bool DoXform) {
7991   // If we are just checking for a icmp eq of a single bit and zext'ing it
7992   // to an integer, then shift the bit to the appropriate place and then
7993   // cast to integer to avoid the comparison.
7994   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7995     const APInt &Op1CV = Op1C->getValue();
7996       
7997     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7998     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7999     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8000         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8001       if (!DoXform) return ICI;
8002
8003       Value *In = ICI->getOperand(0);
8004       Value *Sh = ConstantInt::get(In->getType(),
8005                                    In->getType()->getPrimitiveSizeInBits()-1);
8006       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8007                                                         In->getName()+".lobit"),
8008                                CI);
8009       if (In->getType() != CI.getType())
8010         In = CastInst::CreateIntegerCast(In, CI.getType(),
8011                                          false/*ZExt*/, "tmp", &CI);
8012
8013       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8014         Constant *One = ConstantInt::get(In->getType(), 1);
8015         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8016                                                          In->getName()+".not"),
8017                                  CI);
8018       }
8019
8020       return ReplaceInstUsesWith(CI, In);
8021     }
8022       
8023       
8024       
8025     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8026     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8027     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8028     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8029     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8030     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8031     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8032     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8033     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8034         // This only works for EQ and NE
8035         ICI->isEquality()) {
8036       // If Op1C some other power of two, convert:
8037       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8038       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8039       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8040       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8041         
8042       APInt KnownZeroMask(~KnownZero);
8043       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8044         if (!DoXform) return ICI;
8045
8046         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8047         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8048           // (X&4) == 2 --> false
8049           // (X&4) != 2 --> true
8050           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8051           Res = ConstantExpr::getZExt(Res, CI.getType());
8052           return ReplaceInstUsesWith(CI, Res);
8053         }
8054           
8055         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8056         Value *In = ICI->getOperand(0);
8057         if (ShiftAmt) {
8058           // Perform a logical shr by shiftamt.
8059           // Insert the shift to put the result in the low bit.
8060           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8061                                   ConstantInt::get(In->getType(), ShiftAmt),
8062                                                    In->getName()+".lobit"), CI);
8063         }
8064           
8065         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8066           Constant *One = ConstantInt::get(In->getType(), 1);
8067           In = BinaryOperator::CreateXor(In, One, "tmp");
8068           InsertNewInstBefore(cast<Instruction>(In), CI);
8069         }
8070           
8071         if (CI.getType() == In->getType())
8072           return ReplaceInstUsesWith(CI, In);
8073         else
8074           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8075       }
8076     }
8077   }
8078
8079   return 0;
8080 }
8081
8082 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8083   // If one of the common conversion will work ..
8084   if (Instruction *Result = commonIntCastTransforms(CI))
8085     return Result;
8086
8087   Value *Src = CI.getOperand(0);
8088
8089   // If this is a cast of a cast
8090   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8091     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8092     // types and if the sizes are just right we can convert this into a logical
8093     // 'and' which will be much cheaper than the pair of casts.
8094     if (isa<TruncInst>(CSrc)) {
8095       // Get the sizes of the types involved
8096       Value *A = CSrc->getOperand(0);
8097       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8098       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8099       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8100       // If we're actually extending zero bits and the trunc is a no-op
8101       if (MidSize < DstSize && SrcSize == DstSize) {
8102         // Replace both of the casts with an And of the type mask.
8103         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8104         Constant *AndConst = ConstantInt::get(AndValue);
8105         Instruction *And = 
8106           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8107         // Unfortunately, if the type changed, we need to cast it back.
8108         if (And->getType() != CI.getType()) {
8109           And->setName(CSrc->getName()+".mask");
8110           InsertNewInstBefore(And, CI);
8111           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8112         }
8113         return And;
8114       }
8115     }
8116   }
8117
8118   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8119     return transformZExtICmp(ICI, CI);
8120
8121   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8122   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8123     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8124     // of the (zext icmp) will be transformed.
8125     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8126     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8127     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8128         (transformZExtICmp(LHS, CI, false) ||
8129          transformZExtICmp(RHS, CI, false))) {
8130       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8131       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8132       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8133     }
8134   }
8135
8136   return 0;
8137 }
8138
8139 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8140   if (Instruction *I = commonIntCastTransforms(CI))
8141     return I;
8142   
8143   Value *Src = CI.getOperand(0);
8144   
8145   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
8146   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
8147   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8148     // If we are just checking for a icmp eq of a single bit and zext'ing it
8149     // to an integer, then shift the bit to the appropriate place and then
8150     // cast to integer to avoid the comparison.
8151     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8152       const APInt &Op1CV = Op1C->getValue();
8153       
8154       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8155       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8156       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8157           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8158         Value *In = ICI->getOperand(0);
8159         Value *Sh = ConstantInt::get(In->getType(),
8160                                      In->getType()->getPrimitiveSizeInBits()-1);
8161         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8162                                                         In->getName()+".lobit"),
8163                                  CI);
8164         if (In->getType() != CI.getType())
8165           In = CastInst::CreateIntegerCast(In, CI.getType(),
8166                                            true/*SExt*/, "tmp", &CI);
8167         
8168         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
8169           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8170                                      In->getName()+".not"), CI);
8171         
8172         return ReplaceInstUsesWith(CI, In);
8173       }
8174     }
8175   }
8176
8177   // See if the value being truncated is already sign extended.  If so, just
8178   // eliminate the trunc/sext pair.
8179   if (getOpcode(Src) == Instruction::Trunc) {
8180     Value *Op = cast<User>(Src)->getOperand(0);
8181     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8182     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8183     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8184     unsigned NumSignBits = ComputeNumSignBits(Op);
8185
8186     if (OpBits == DestBits) {
8187       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8188       // bits, it is already ready.
8189       if (NumSignBits > DestBits-MidBits)
8190         return ReplaceInstUsesWith(CI, Op);
8191     } else if (OpBits < DestBits) {
8192       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8193       // bits, just sext from i32.
8194       if (NumSignBits > OpBits-MidBits)
8195         return new SExtInst(Op, CI.getType(), "tmp");
8196     } else {
8197       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8198       // bits, just truncate to i32.
8199       if (NumSignBits > OpBits-MidBits)
8200         return new TruncInst(Op, CI.getType(), "tmp");
8201     }
8202   }
8203       
8204   return 0;
8205 }
8206
8207 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8208 /// in the specified FP type without changing its value.
8209 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8210   APFloat F = CFP->getValueAPF();
8211   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
8212     return ConstantFP::get(F);
8213   return 0;
8214 }
8215
8216 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8217 /// through it until we get the source value.
8218 static Value *LookThroughFPExtensions(Value *V) {
8219   if (Instruction *I = dyn_cast<Instruction>(V))
8220     if (I->getOpcode() == Instruction::FPExt)
8221       return LookThroughFPExtensions(I->getOperand(0));
8222   
8223   // If this value is a constant, return the constant in the smallest FP type
8224   // that can accurately represent it.  This allows us to turn
8225   // (float)((double)X+2.0) into x+2.0f.
8226   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8227     if (CFP->getType() == Type::PPC_FP128Ty)
8228       return V;  // No constant folding of this.
8229     // See if the value can be truncated to float and then reextended.
8230     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8231       return V;
8232     if (CFP->getType() == Type::DoubleTy)
8233       return V;  // Won't shrink.
8234     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8235       return V;
8236     // Don't try to shrink to various long double types.
8237   }
8238   
8239   return V;
8240 }
8241
8242 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8243   if (Instruction *I = commonCastTransforms(CI))
8244     return I;
8245   
8246   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8247   // smaller than the destination type, we can eliminate the truncate by doing
8248   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8249   // many builtins (sqrt, etc).
8250   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8251   if (OpI && OpI->hasOneUse()) {
8252     switch (OpI->getOpcode()) {
8253     default: break;
8254     case Instruction::Add:
8255     case Instruction::Sub:
8256     case Instruction::Mul:
8257     case Instruction::FDiv:
8258     case Instruction::FRem:
8259       const Type *SrcTy = OpI->getType();
8260       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8261       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8262       if (LHSTrunc->getType() != SrcTy && 
8263           RHSTrunc->getType() != SrcTy) {
8264         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8265         // If the source types were both smaller than the destination type of
8266         // the cast, do this xform.
8267         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8268             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8269           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8270                                       CI.getType(), CI);
8271           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8272                                       CI.getType(), CI);
8273           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8274         }
8275       }
8276       break;  
8277     }
8278   }
8279   return 0;
8280 }
8281
8282 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8283   return commonCastTransforms(CI);
8284 }
8285
8286 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8287   // fptoui(uitofp(X)) --> X  if the intermediate type has enough bits in its
8288   // mantissa to accurately represent all values of X.  For example, do not
8289   // do this with i64->float->i64.
8290   if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8291     if (SrcI->getOperand(0)->getType() == FI.getType() &&
8292         (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8293                     SrcI->getType()->getFPMantissaWidth())
8294       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8295
8296   return commonCastTransforms(FI);
8297 }
8298
8299 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8300   // fptosi(sitofp(X)) --> X  if the intermediate type has enough bits in its
8301   // mantissa to accurately represent all values of X.  For example, do not
8302   // do this with i64->float->i64.
8303   if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8304     if (SrcI->getOperand(0)->getType() == FI.getType() &&
8305         (int)FI.getType()->getPrimitiveSizeInBits() <= 
8306                     SrcI->getType()->getFPMantissaWidth())
8307       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8308   
8309   return commonCastTransforms(FI);
8310 }
8311
8312 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8313   return commonCastTransforms(CI);
8314 }
8315
8316 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8317   return commonCastTransforms(CI);
8318 }
8319
8320 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8321   return commonPointerCastTransforms(CI);
8322 }
8323
8324 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8325   if (Instruction *I = commonCastTransforms(CI))
8326     return I;
8327   
8328   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8329   if (!DestPointee->isSized()) return 0;
8330
8331   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8332   ConstantInt *Cst;
8333   Value *X;
8334   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8335                                     m_ConstantInt(Cst)))) {
8336     // If the source and destination operands have the same type, see if this
8337     // is a single-index GEP.
8338     if (X->getType() == CI.getType()) {
8339       // Get the size of the pointee type.
8340       uint64_t Size = TD->getABITypeSize(DestPointee);
8341
8342       // Convert the constant to intptr type.
8343       APInt Offset = Cst->getValue();
8344       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8345
8346       // If Offset is evenly divisible by Size, we can do this xform.
8347       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8348         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8349         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8350       }
8351     }
8352     // TODO: Could handle other cases, e.g. where add is indexing into field of
8353     // struct etc.
8354   } else if (CI.getOperand(0)->hasOneUse() &&
8355              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8356     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8357     // "inttoptr+GEP" instead of "add+intptr".
8358     
8359     // Get the size of the pointee type.
8360     uint64_t Size = TD->getABITypeSize(DestPointee);
8361     
8362     // Convert the constant to intptr type.
8363     APInt Offset = Cst->getValue();
8364     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8365     
8366     // If Offset is evenly divisible by Size, we can do this xform.
8367     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8368       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8369       
8370       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8371                                                             "tmp"), CI);
8372       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8373     }
8374   }
8375   return 0;
8376 }
8377
8378 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8379   // If the operands are integer typed then apply the integer transforms,
8380   // otherwise just apply the common ones.
8381   Value *Src = CI.getOperand(0);
8382   const Type *SrcTy = Src->getType();
8383   const Type *DestTy = CI.getType();
8384
8385   if (SrcTy->isInteger() && DestTy->isInteger()) {
8386     if (Instruction *Result = commonIntCastTransforms(CI))
8387       return Result;
8388   } else if (isa<PointerType>(SrcTy)) {
8389     if (Instruction *I = commonPointerCastTransforms(CI))
8390       return I;
8391   } else {
8392     if (Instruction *Result = commonCastTransforms(CI))
8393       return Result;
8394   }
8395
8396
8397   // Get rid of casts from one type to the same type. These are useless and can
8398   // be replaced by the operand.
8399   if (DestTy == Src->getType())
8400     return ReplaceInstUsesWith(CI, Src);
8401
8402   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8403     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8404     const Type *DstElTy = DstPTy->getElementType();
8405     const Type *SrcElTy = SrcPTy->getElementType();
8406     
8407     // If the address spaces don't match, don't eliminate the bitcast, which is
8408     // required for changing types.
8409     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8410       return 0;
8411     
8412     // If we are casting a malloc or alloca to a pointer to a type of the same
8413     // size, rewrite the allocation instruction to allocate the "right" type.
8414     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8415       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8416         return V;
8417     
8418     // If the source and destination are pointers, and this cast is equivalent
8419     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8420     // This can enhance SROA and other transforms that want type-safe pointers.
8421     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8422     unsigned NumZeros = 0;
8423     while (SrcElTy != DstElTy && 
8424            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8425            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8426       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8427       ++NumZeros;
8428     }
8429
8430     // If we found a path from the src to dest, create the getelementptr now.
8431     if (SrcElTy == DstElTy) {
8432       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8433       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8434                                        ((Instruction*) NULL));
8435     }
8436   }
8437
8438   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8439     if (SVI->hasOneUse()) {
8440       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8441       // a bitconvert to a vector with the same # elts.
8442       if (isa<VectorType>(DestTy) && 
8443           cast<VectorType>(DestTy)->getNumElements() == 
8444                 SVI->getType()->getNumElements()) {
8445         CastInst *Tmp;
8446         // If either of the operands is a cast from CI.getType(), then
8447         // evaluating the shuffle in the casted destination's type will allow
8448         // us to eliminate at least one cast.
8449         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8450              Tmp->getOperand(0)->getType() == DestTy) ||
8451             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8452              Tmp->getOperand(0)->getType() == DestTy)) {
8453           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8454                                                SVI->getOperand(0), DestTy, &CI);
8455           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8456                                                SVI->getOperand(1), DestTy, &CI);
8457           // Return a new shuffle vector.  Use the same element ID's, as we
8458           // know the vector types match #elts.
8459           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8460         }
8461       }
8462     }
8463   }
8464   return 0;
8465 }
8466
8467 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8468 ///   %C = or %A, %B
8469 ///   %D = select %cond, %C, %A
8470 /// into:
8471 ///   %C = select %cond, %B, 0
8472 ///   %D = or %A, %C
8473 ///
8474 /// Assuming that the specified instruction is an operand to the select, return
8475 /// a bitmask indicating which operands of this instruction are foldable if they
8476 /// equal the other incoming value of the select.
8477 ///
8478 static unsigned GetSelectFoldableOperands(Instruction *I) {
8479   switch (I->getOpcode()) {
8480   case Instruction::Add:
8481   case Instruction::Mul:
8482   case Instruction::And:
8483   case Instruction::Or:
8484   case Instruction::Xor:
8485     return 3;              // Can fold through either operand.
8486   case Instruction::Sub:   // Can only fold on the amount subtracted.
8487   case Instruction::Shl:   // Can only fold on the shift amount.
8488   case Instruction::LShr:
8489   case Instruction::AShr:
8490     return 1;
8491   default:
8492     return 0;              // Cannot fold
8493   }
8494 }
8495
8496 /// GetSelectFoldableConstant - For the same transformation as the previous
8497 /// function, return the identity constant that goes into the select.
8498 static Constant *GetSelectFoldableConstant(Instruction *I) {
8499   switch (I->getOpcode()) {
8500   default: assert(0 && "This cannot happen!"); abort();
8501   case Instruction::Add:
8502   case Instruction::Sub:
8503   case Instruction::Or:
8504   case Instruction::Xor:
8505   case Instruction::Shl:
8506   case Instruction::LShr:
8507   case Instruction::AShr:
8508     return Constant::getNullValue(I->getType());
8509   case Instruction::And:
8510     return Constant::getAllOnesValue(I->getType());
8511   case Instruction::Mul:
8512     return ConstantInt::get(I->getType(), 1);
8513   }
8514 }
8515
8516 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8517 /// have the same opcode and only one use each.  Try to simplify this.
8518 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8519                                           Instruction *FI) {
8520   if (TI->getNumOperands() == 1) {
8521     // If this is a non-volatile load or a cast from the same type,
8522     // merge.
8523     if (TI->isCast()) {
8524       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8525         return 0;
8526     } else {
8527       return 0;  // unknown unary op.
8528     }
8529
8530     // Fold this by inserting a select from the input values.
8531     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8532                                            FI->getOperand(0), SI.getName()+".v");
8533     InsertNewInstBefore(NewSI, SI);
8534     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8535                             TI->getType());
8536   }
8537
8538   // Only handle binary operators here.
8539   if (!isa<BinaryOperator>(TI))
8540     return 0;
8541
8542   // Figure out if the operations have any operands in common.
8543   Value *MatchOp, *OtherOpT, *OtherOpF;
8544   bool MatchIsOpZero;
8545   if (TI->getOperand(0) == FI->getOperand(0)) {
8546     MatchOp  = TI->getOperand(0);
8547     OtherOpT = TI->getOperand(1);
8548     OtherOpF = FI->getOperand(1);
8549     MatchIsOpZero = true;
8550   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8551     MatchOp  = TI->getOperand(1);
8552     OtherOpT = TI->getOperand(0);
8553     OtherOpF = FI->getOperand(0);
8554     MatchIsOpZero = false;
8555   } else if (!TI->isCommutative()) {
8556     return 0;
8557   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8558     MatchOp  = TI->getOperand(0);
8559     OtherOpT = TI->getOperand(1);
8560     OtherOpF = FI->getOperand(0);
8561     MatchIsOpZero = true;
8562   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8563     MatchOp  = TI->getOperand(1);
8564     OtherOpT = TI->getOperand(0);
8565     OtherOpF = FI->getOperand(1);
8566     MatchIsOpZero = true;
8567   } else {
8568     return 0;
8569   }
8570
8571   // If we reach here, they do have operations in common.
8572   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8573                                          OtherOpF, SI.getName()+".v");
8574   InsertNewInstBefore(NewSI, SI);
8575
8576   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8577     if (MatchIsOpZero)
8578       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8579     else
8580       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8581   }
8582   assert(0 && "Shouldn't get here");
8583   return 0;
8584 }
8585
8586 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8587   Value *CondVal = SI.getCondition();
8588   Value *TrueVal = SI.getTrueValue();
8589   Value *FalseVal = SI.getFalseValue();
8590
8591   // select true, X, Y  -> X
8592   // select false, X, Y -> Y
8593   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8594     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8595
8596   // select C, X, X -> X
8597   if (TrueVal == FalseVal)
8598     return ReplaceInstUsesWith(SI, TrueVal);
8599
8600   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8601     return ReplaceInstUsesWith(SI, FalseVal);
8602   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8603     return ReplaceInstUsesWith(SI, TrueVal);
8604   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8605     if (isa<Constant>(TrueVal))
8606       return ReplaceInstUsesWith(SI, TrueVal);
8607     else
8608       return ReplaceInstUsesWith(SI, FalseVal);
8609   }
8610
8611   if (SI.getType() == Type::Int1Ty) {
8612     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8613       if (C->getZExtValue()) {
8614         // Change: A = select B, true, C --> A = or B, C
8615         return BinaryOperator::CreateOr(CondVal, FalseVal);
8616       } else {
8617         // Change: A = select B, false, C --> A = and !B, C
8618         Value *NotCond =
8619           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8620                                              "not."+CondVal->getName()), SI);
8621         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8622       }
8623     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8624       if (C->getZExtValue() == false) {
8625         // Change: A = select B, C, false --> A = and B, C
8626         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8627       } else {
8628         // Change: A = select B, C, true --> A = or !B, C
8629         Value *NotCond =
8630           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8631                                              "not."+CondVal->getName()), SI);
8632         return BinaryOperator::CreateOr(NotCond, TrueVal);
8633       }
8634     }
8635     
8636     // select a, b, a  -> a&b
8637     // select a, a, b  -> a|b
8638     if (CondVal == TrueVal)
8639       return BinaryOperator::CreateOr(CondVal, FalseVal);
8640     else if (CondVal == FalseVal)
8641       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8642   }
8643
8644   // Selecting between two integer constants?
8645   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8646     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8647       // select C, 1, 0 -> zext C to int
8648       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8649         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8650       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8651         // select C, 0, 1 -> zext !C to int
8652         Value *NotCond =
8653           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8654                                                "not."+CondVal->getName()), SI);
8655         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8656       }
8657       
8658       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8659
8660       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8661
8662         // (x <s 0) ? -1 : 0 -> ashr x, 31
8663         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8664           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8665             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8666               // The comparison constant and the result are not neccessarily the
8667               // same width. Make an all-ones value by inserting a AShr.
8668               Value *X = IC->getOperand(0);
8669               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8670               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8671               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8672                                                         ShAmt, "ones");
8673               InsertNewInstBefore(SRA, SI);
8674               
8675               // Finally, convert to the type of the select RHS.  We figure out
8676               // if this requires a SExt, Trunc or BitCast based on the sizes.
8677               Instruction::CastOps opc = Instruction::BitCast;
8678               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8679               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8680               if (SRASize < SISize)
8681                 opc = Instruction::SExt;
8682               else if (SRASize > SISize)
8683                 opc = Instruction::Trunc;
8684               return CastInst::Create(opc, SRA, SI.getType());
8685             }
8686           }
8687
8688
8689         // If one of the constants is zero (we know they can't both be) and we
8690         // have an icmp instruction with zero, and we have an 'and' with the
8691         // non-constant value, eliminate this whole mess.  This corresponds to
8692         // cases like this: ((X & 27) ? 27 : 0)
8693         if (TrueValC->isZero() || FalseValC->isZero())
8694           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8695               cast<Constant>(IC->getOperand(1))->isNullValue())
8696             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8697               if (ICA->getOpcode() == Instruction::And &&
8698                   isa<ConstantInt>(ICA->getOperand(1)) &&
8699                   (ICA->getOperand(1) == TrueValC ||
8700                    ICA->getOperand(1) == FalseValC) &&
8701                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8702                 // Okay, now we know that everything is set up, we just don't
8703                 // know whether we have a icmp_ne or icmp_eq and whether the 
8704                 // true or false val is the zero.
8705                 bool ShouldNotVal = !TrueValC->isZero();
8706                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8707                 Value *V = ICA;
8708                 if (ShouldNotVal)
8709                   V = InsertNewInstBefore(BinaryOperator::Create(
8710                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8711                 return ReplaceInstUsesWith(SI, V);
8712               }
8713       }
8714     }
8715
8716   // See if we are selecting two values based on a comparison of the two values.
8717   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8718     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8719       // Transform (X == Y) ? X : Y  -> Y
8720       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8721         // This is not safe in general for floating point:  
8722         // consider X== -0, Y== +0.
8723         // It becomes safe if either operand is a nonzero constant.
8724         ConstantFP *CFPt, *CFPf;
8725         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8726               !CFPt->getValueAPF().isZero()) ||
8727             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8728              !CFPf->getValueAPF().isZero()))
8729         return ReplaceInstUsesWith(SI, FalseVal);
8730       }
8731       // Transform (X != Y) ? X : Y  -> X
8732       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8733         return ReplaceInstUsesWith(SI, TrueVal);
8734       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8735
8736     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8737       // Transform (X == Y) ? Y : X  -> X
8738       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8739         // This is not safe in general for floating point:  
8740         // consider X== -0, Y== +0.
8741         // It becomes safe if either operand is a nonzero constant.
8742         ConstantFP *CFPt, *CFPf;
8743         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8744               !CFPt->getValueAPF().isZero()) ||
8745             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8746              !CFPf->getValueAPF().isZero()))
8747           return ReplaceInstUsesWith(SI, FalseVal);
8748       }
8749       // Transform (X != Y) ? Y : X  -> Y
8750       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8751         return ReplaceInstUsesWith(SI, TrueVal);
8752       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8753     }
8754   }
8755
8756   // See if we are selecting two values based on a comparison of the two values.
8757   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8758     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8759       // Transform (X == Y) ? X : Y  -> Y
8760       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8761         return ReplaceInstUsesWith(SI, FalseVal);
8762       // Transform (X != Y) ? X : Y  -> X
8763       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8764         return ReplaceInstUsesWith(SI, TrueVal);
8765       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8766
8767     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8768       // Transform (X == Y) ? Y : X  -> X
8769       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8770         return ReplaceInstUsesWith(SI, FalseVal);
8771       // Transform (X != Y) ? Y : X  -> Y
8772       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8773         return ReplaceInstUsesWith(SI, TrueVal);
8774       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8775     }
8776   }
8777
8778   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8779     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8780       if (TI->hasOneUse() && FI->hasOneUse()) {
8781         Instruction *AddOp = 0, *SubOp = 0;
8782
8783         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8784         if (TI->getOpcode() == FI->getOpcode())
8785           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8786             return IV;
8787
8788         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8789         // even legal for FP.
8790         if (TI->getOpcode() == Instruction::Sub &&
8791             FI->getOpcode() == Instruction::Add) {
8792           AddOp = FI; SubOp = TI;
8793         } else if (FI->getOpcode() == Instruction::Sub &&
8794                    TI->getOpcode() == Instruction::Add) {
8795           AddOp = TI; SubOp = FI;
8796         }
8797
8798         if (AddOp) {
8799           Value *OtherAddOp = 0;
8800           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8801             OtherAddOp = AddOp->getOperand(1);
8802           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8803             OtherAddOp = AddOp->getOperand(0);
8804           }
8805
8806           if (OtherAddOp) {
8807             // So at this point we know we have (Y -> OtherAddOp):
8808             //        select C, (add X, Y), (sub X, Z)
8809             Value *NegVal;  // Compute -Z
8810             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8811               NegVal = ConstantExpr::getNeg(C);
8812             } else {
8813               NegVal = InsertNewInstBefore(
8814                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8815             }
8816
8817             Value *NewTrueOp = OtherAddOp;
8818             Value *NewFalseOp = NegVal;
8819             if (AddOp != TI)
8820               std::swap(NewTrueOp, NewFalseOp);
8821             Instruction *NewSel =
8822               SelectInst::Create(CondVal, NewTrueOp,
8823                                  NewFalseOp, SI.getName() + ".p");
8824
8825             NewSel = InsertNewInstBefore(NewSel, SI);
8826             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8827           }
8828         }
8829       }
8830
8831   // See if we can fold the select into one of our operands.
8832   if (SI.getType()->isInteger()) {
8833     // See the comment above GetSelectFoldableOperands for a description of the
8834     // transformation we are doing here.
8835     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8836       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8837           !isa<Constant>(FalseVal))
8838         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8839           unsigned OpToFold = 0;
8840           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8841             OpToFold = 1;
8842           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8843             OpToFold = 2;
8844           }
8845
8846           if (OpToFold) {
8847             Constant *C = GetSelectFoldableConstant(TVI);
8848             Instruction *NewSel =
8849               SelectInst::Create(SI.getCondition(),
8850                                  TVI->getOperand(2-OpToFold), C);
8851             InsertNewInstBefore(NewSel, SI);
8852             NewSel->takeName(TVI);
8853             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8854               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8855             else {
8856               assert(0 && "Unknown instruction!!");
8857             }
8858           }
8859         }
8860
8861     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8862       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8863           !isa<Constant>(TrueVal))
8864         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8865           unsigned OpToFold = 0;
8866           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8867             OpToFold = 1;
8868           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8869             OpToFold = 2;
8870           }
8871
8872           if (OpToFold) {
8873             Constant *C = GetSelectFoldableConstant(FVI);
8874             Instruction *NewSel =
8875               SelectInst::Create(SI.getCondition(), C,
8876                                  FVI->getOperand(2-OpToFold));
8877             InsertNewInstBefore(NewSel, SI);
8878             NewSel->takeName(FVI);
8879             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8880               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8881             else
8882               assert(0 && "Unknown instruction!!");
8883           }
8884         }
8885   }
8886
8887   if (BinaryOperator::isNot(CondVal)) {
8888     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8889     SI.setOperand(1, FalseVal);
8890     SI.setOperand(2, TrueVal);
8891     return &SI;
8892   }
8893
8894   return 0;
8895 }
8896
8897 /// EnforceKnownAlignment - If the specified pointer points to an object that
8898 /// we control, modify the object's alignment to PrefAlign. This isn't
8899 /// often possible though. If alignment is important, a more reliable approach
8900 /// is to simply align all global variables and allocation instructions to
8901 /// their preferred alignment from the beginning.
8902 ///
8903 static unsigned EnforceKnownAlignment(Value *V,
8904                                       unsigned Align, unsigned PrefAlign) {
8905
8906   User *U = dyn_cast<User>(V);
8907   if (!U) return Align;
8908
8909   switch (getOpcode(U)) {
8910   default: break;
8911   case Instruction::BitCast:
8912     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8913   case Instruction::GetElementPtr: {
8914     // If all indexes are zero, it is just the alignment of the base pointer.
8915     bool AllZeroOperands = true;
8916     for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8917       if (!isa<Constant>(U->getOperand(i)) ||
8918           !cast<Constant>(U->getOperand(i))->isNullValue()) {
8919         AllZeroOperands = false;
8920         break;
8921       }
8922
8923     if (AllZeroOperands) {
8924       // Treat this like a bitcast.
8925       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8926     }
8927     break;
8928   }
8929   }
8930
8931   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8932     // If there is a large requested alignment and we can, bump up the alignment
8933     // of the global.
8934     if (!GV->isDeclaration()) {
8935       GV->setAlignment(PrefAlign);
8936       Align = PrefAlign;
8937     }
8938   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8939     // If there is a requested alignment and if this is an alloca, round up.  We
8940     // don't do this for malloc, because some systems can't respect the request.
8941     if (isa<AllocaInst>(AI)) {
8942       AI->setAlignment(PrefAlign);
8943       Align = PrefAlign;
8944     }
8945   }
8946
8947   return Align;
8948 }
8949
8950 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8951 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8952 /// and it is more than the alignment of the ultimate object, see if we can
8953 /// increase the alignment of the ultimate object, making this check succeed.
8954 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8955                                                   unsigned PrefAlign) {
8956   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8957                       sizeof(PrefAlign) * CHAR_BIT;
8958   APInt Mask = APInt::getAllOnesValue(BitWidth);
8959   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8960   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8961   unsigned TrailZ = KnownZero.countTrailingOnes();
8962   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8963
8964   if (PrefAlign > Align)
8965     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8966   
8967     // We don't need to make any adjustment.
8968   return Align;
8969 }
8970
8971 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8972   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8973   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8974   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8975   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8976
8977   if (CopyAlign < MinAlign) {
8978     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8979     return MI;
8980   }
8981   
8982   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8983   // load/store.
8984   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8985   if (MemOpLength == 0) return 0;
8986   
8987   // Source and destination pointer types are always "i8*" for intrinsic.  See
8988   // if the size is something we can handle with a single primitive load/store.
8989   // A single load+store correctly handles overlapping memory in the memmove
8990   // case.
8991   unsigned Size = MemOpLength->getZExtValue();
8992   if (Size == 0) return MI;  // Delete this mem transfer.
8993   
8994   if (Size > 8 || (Size&(Size-1)))
8995     return 0;  // If not 1/2/4/8 bytes, exit.
8996   
8997   // Use an integer load+store unless we can find something better.
8998   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8999   
9000   // Memcpy forces the use of i8* for the source and destination.  That means
9001   // that if you're using memcpy to move one double around, you'll get a cast
9002   // from double* to i8*.  We'd much rather use a double load+store rather than
9003   // an i64 load+store, here because this improves the odds that the source or
9004   // dest address will be promotable.  See if we can find a better type than the
9005   // integer datatype.
9006   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9007     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9008     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9009       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9010       // down through these levels if so.
9011       while (!SrcETy->isSingleValueType()) {
9012         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9013           if (STy->getNumElements() == 1)
9014             SrcETy = STy->getElementType(0);
9015           else
9016             break;
9017         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9018           if (ATy->getNumElements() == 1)
9019             SrcETy = ATy->getElementType();
9020           else
9021             break;
9022         } else
9023           break;
9024       }
9025       
9026       if (SrcETy->isSingleValueType())
9027         NewPtrTy = PointerType::getUnqual(SrcETy);
9028     }
9029   }
9030   
9031   
9032   // If the memcpy/memmove provides better alignment info than we can
9033   // infer, use it.
9034   SrcAlign = std::max(SrcAlign, CopyAlign);
9035   DstAlign = std::max(DstAlign, CopyAlign);
9036   
9037   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9038   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9039   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9040   InsertNewInstBefore(L, *MI);
9041   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9042
9043   // Set the size of the copy to 0, it will be deleted on the next iteration.
9044   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9045   return MI;
9046 }
9047
9048 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9049   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9050   if (MI->getAlignment()->getZExtValue() < Alignment) {
9051     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9052     return MI;
9053   }
9054   
9055   // Extract the length and alignment and fill if they are constant.
9056   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9057   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9058   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9059     return 0;
9060   uint64_t Len = LenC->getZExtValue();
9061   Alignment = MI->getAlignment()->getZExtValue();
9062   
9063   // If the length is zero, this is a no-op
9064   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9065   
9066   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9067   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9068     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9069     
9070     Value *Dest = MI->getDest();
9071     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9072
9073     // Alignment 0 is identity for alignment 1 for memset, but not store.
9074     if (Alignment == 0) Alignment = 1;
9075     
9076     // Extract the fill value and store.
9077     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9078     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9079                                       Alignment), *MI);
9080     
9081     // Set the size of the copy to 0, it will be deleted on the next iteration.
9082     MI->setLength(Constant::getNullValue(LenC->getType()));
9083     return MI;
9084   }
9085
9086   return 0;
9087 }
9088
9089
9090 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9091 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9092 /// the heavy lifting.
9093 ///
9094 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9095   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9096   if (!II) return visitCallSite(&CI);
9097   
9098   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9099   // visitCallSite.
9100   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9101     bool Changed = false;
9102
9103     // memmove/cpy/set of zero bytes is a noop.
9104     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9105       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9106
9107       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9108         if (CI->getZExtValue() == 1) {
9109           // Replace the instruction with just byte operations.  We would
9110           // transform other cases to loads/stores, but we don't know if
9111           // alignment is sufficient.
9112         }
9113     }
9114
9115     // If we have a memmove and the source operation is a constant global,
9116     // then the source and dest pointers can't alias, so we can change this
9117     // into a call to memcpy.
9118     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9119       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9120         if (GVSrc->isConstant()) {
9121           Module *M = CI.getParent()->getParent()->getParent();
9122           Intrinsic::ID MemCpyID;
9123           if (CI.getOperand(3)->getType() == Type::Int32Ty)
9124             MemCpyID = Intrinsic::memcpy_i32;
9125           else
9126             MemCpyID = Intrinsic::memcpy_i64;
9127           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
9128           Changed = true;
9129         }
9130     }
9131
9132     // If we can determine a pointer alignment that is bigger than currently
9133     // set, update the alignment.
9134     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9135       if (Instruction *I = SimplifyMemTransfer(MI))
9136         return I;
9137     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9138       if (Instruction *I = SimplifyMemSet(MSI))
9139         return I;
9140     }
9141           
9142     if (Changed) return II;
9143   } else {
9144     switch (II->getIntrinsicID()) {
9145     default: break;
9146     case Intrinsic::ppc_altivec_lvx:
9147     case Intrinsic::ppc_altivec_lvxl:
9148     case Intrinsic::x86_sse_loadu_ps:
9149     case Intrinsic::x86_sse2_loadu_pd:
9150     case Intrinsic::x86_sse2_loadu_dq:
9151       // Turn PPC lvx     -> load if the pointer is known aligned.
9152       // Turn X86 loadups -> load if the pointer is known aligned.
9153       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9154         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9155                                          PointerType::getUnqual(II->getType()),
9156                                          CI);
9157         return new LoadInst(Ptr);
9158       }
9159       break;
9160     case Intrinsic::ppc_altivec_stvx:
9161     case Intrinsic::ppc_altivec_stvxl:
9162       // Turn stvx -> store if the pointer is known aligned.
9163       if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9164         const Type *OpPtrTy = 
9165           PointerType::getUnqual(II->getOperand(1)->getType());
9166         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9167         return new StoreInst(II->getOperand(1), Ptr);
9168       }
9169       break;
9170     case Intrinsic::x86_sse_storeu_ps:
9171     case Intrinsic::x86_sse2_storeu_pd:
9172     case Intrinsic::x86_sse2_storeu_dq:
9173     case Intrinsic::x86_sse2_storel_dq:
9174       // Turn X86 storeu -> store if the pointer is known aligned.
9175       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9176         const Type *OpPtrTy = 
9177           PointerType::getUnqual(II->getOperand(2)->getType());
9178         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9179         return new StoreInst(II->getOperand(2), Ptr);
9180       }
9181       break;
9182       
9183     case Intrinsic::x86_sse_cvttss2si: {
9184       // These intrinsics only demands the 0th element of its input vector.  If
9185       // we can simplify the input based on that, do so now.
9186       uint64_t UndefElts;
9187       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9188                                                 UndefElts)) {
9189         II->setOperand(1, V);
9190         return II;
9191       }
9192       break;
9193     }
9194       
9195     case Intrinsic::ppc_altivec_vperm:
9196       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9197       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9198         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9199         
9200         // Check that all of the elements are integer constants or undefs.
9201         bool AllEltsOk = true;
9202         for (unsigned i = 0; i != 16; ++i) {
9203           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9204               !isa<UndefValue>(Mask->getOperand(i))) {
9205             AllEltsOk = false;
9206             break;
9207           }
9208         }
9209         
9210         if (AllEltsOk) {
9211           // Cast the input vectors to byte vectors.
9212           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9213           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9214           Value *Result = UndefValue::get(Op0->getType());
9215           
9216           // Only extract each element once.
9217           Value *ExtractedElts[32];
9218           memset(ExtractedElts, 0, sizeof(ExtractedElts));
9219           
9220           for (unsigned i = 0; i != 16; ++i) {
9221             if (isa<UndefValue>(Mask->getOperand(i)))
9222               continue;
9223             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9224             Idx &= 31;  // Match the hardware behavior.
9225             
9226             if (ExtractedElts[Idx] == 0) {
9227               Instruction *Elt = 
9228                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9229               InsertNewInstBefore(Elt, CI);
9230               ExtractedElts[Idx] = Elt;
9231             }
9232           
9233             // Insert this value into the result vector.
9234             Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9235                                                i, "tmp");
9236             InsertNewInstBefore(cast<Instruction>(Result), CI);
9237           }
9238           return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9239         }
9240       }
9241       break;
9242
9243     case Intrinsic::stackrestore: {
9244       // If the save is right next to the restore, remove the restore.  This can
9245       // happen when variable allocas are DCE'd.
9246       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9247         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9248           BasicBlock::iterator BI = SS;
9249           if (&*++BI == II)
9250             return EraseInstFromFunction(CI);
9251         }
9252       }
9253       
9254       // Scan down this block to see if there is another stack restore in the
9255       // same block without an intervening call/alloca.
9256       BasicBlock::iterator BI = II;
9257       TerminatorInst *TI = II->getParent()->getTerminator();
9258       bool CannotRemove = false;
9259       for (++BI; &*BI != TI; ++BI) {
9260         if (isa<AllocaInst>(BI)) {
9261           CannotRemove = true;
9262           break;
9263         }
9264         if (isa<CallInst>(BI)) {
9265           if (!isa<IntrinsicInst>(BI)) {
9266             CannotRemove = true;
9267             break;
9268           }
9269           // If there is a stackrestore below this one, remove this one.
9270           return EraseInstFromFunction(CI);
9271         }
9272       }
9273       
9274       // If the stack restore is in a return/unwind block and if there are no
9275       // allocas or calls between the restore and the return, nuke the restore.
9276       if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9277         return EraseInstFromFunction(CI);
9278       break;
9279     }
9280     }
9281   }
9282
9283   return visitCallSite(II);
9284 }
9285
9286 // InvokeInst simplification
9287 //
9288 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9289   return visitCallSite(&II);
9290 }
9291
9292 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9293 /// passed through the varargs area, we can eliminate the use of the cast.
9294 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9295                                          const CastInst * const CI,
9296                                          const TargetData * const TD,
9297                                          const int ix) {
9298   if (!CI->isLosslessCast())
9299     return false;
9300
9301   // The size of ByVal arguments is derived from the type, so we
9302   // can't change to a type with a different size.  If the size were
9303   // passed explicitly we could avoid this check.
9304   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9305     return true;
9306
9307   const Type* SrcTy = 
9308             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9309   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9310   if (!SrcTy->isSized() || !DstTy->isSized())
9311     return false;
9312   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9313     return false;
9314   return true;
9315 }
9316
9317 // visitCallSite - Improvements for call and invoke instructions.
9318 //
9319 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9320   bool Changed = false;
9321
9322   // If the callee is a constexpr cast of a function, attempt to move the cast
9323   // to the arguments of the call/invoke.
9324   if (transformConstExprCastCall(CS)) return 0;
9325
9326   Value *Callee = CS.getCalledValue();
9327
9328   if (Function *CalleeF = dyn_cast<Function>(Callee))
9329     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9330       Instruction *OldCall = CS.getInstruction();
9331       // If the call and callee calling conventions don't match, this call must
9332       // be unreachable, as the call is undefined.
9333       new StoreInst(ConstantInt::getTrue(),
9334                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9335                                     OldCall);
9336       if (!OldCall->use_empty())
9337         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9338       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9339         return EraseInstFromFunction(*OldCall);
9340       return 0;
9341     }
9342
9343   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9344     // This instruction is not reachable, just remove it.  We insert a store to
9345     // undef so that we know that this code is not reachable, despite the fact
9346     // that we can't modify the CFG here.
9347     new StoreInst(ConstantInt::getTrue(),
9348                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9349                   CS.getInstruction());
9350
9351     if (!CS.getInstruction()->use_empty())
9352       CS.getInstruction()->
9353         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9354
9355     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9356       // Don't break the CFG, insert a dummy cond branch.
9357       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9358                          ConstantInt::getTrue(), II);
9359     }
9360     return EraseInstFromFunction(*CS.getInstruction());
9361   }
9362
9363   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9364     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9365       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9366         return transformCallThroughTrampoline(CS);
9367
9368   const PointerType *PTy = cast<PointerType>(Callee->getType());
9369   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9370   if (FTy->isVarArg()) {
9371     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9372     // See if we can optimize any arguments passed through the varargs area of
9373     // the call.
9374     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9375            E = CS.arg_end(); I != E; ++I, ++ix) {
9376       CastInst *CI = dyn_cast<CastInst>(*I);
9377       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9378         *I = CI->getOperand(0);
9379         Changed = true;
9380       }
9381     }
9382   }
9383
9384   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9385     // Inline asm calls cannot throw - mark them 'nounwind'.
9386     CS.setDoesNotThrow();
9387     Changed = true;
9388   }
9389
9390   return Changed ? CS.getInstruction() : 0;
9391 }
9392
9393 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9394 // attempt to move the cast to the arguments of the call/invoke.
9395 //
9396 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9397   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9398   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9399   if (CE->getOpcode() != Instruction::BitCast || 
9400       !isa<Function>(CE->getOperand(0)))
9401     return false;
9402   Function *Callee = cast<Function>(CE->getOperand(0));
9403   Instruction *Caller = CS.getInstruction();
9404   const PAListPtr &CallerPAL = CS.getParamAttrs();
9405
9406   // Okay, this is a cast from a function to a different type.  Unless doing so
9407   // would cause a type conversion of one of our arguments, change this call to
9408   // be a direct call with arguments casted to the appropriate types.
9409   //
9410   const FunctionType *FT = Callee->getFunctionType();
9411   const Type *OldRetTy = Caller->getType();
9412
9413   if (isa<StructType>(FT->getReturnType()))
9414     return false; // TODO: Handle multiple return values.
9415
9416   // Check to see if we are changing the return type...
9417   if (OldRetTy != FT->getReturnType()) {
9418     if (Callee->isDeclaration() &&
9419         // Conversion is ok if changing from pointer to int of same size.
9420         !(isa<PointerType>(FT->getReturnType()) &&
9421           TD->getIntPtrType() == OldRetTy))
9422       return false;   // Cannot transform this return value.
9423
9424     if (!Caller->use_empty() &&
9425         // void -> non-void is handled specially
9426         FT->getReturnType() != Type::VoidTy &&
9427         !CastInst::isCastable(FT->getReturnType(), OldRetTy))
9428       return false;   // Cannot transform this return value.
9429
9430     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9431       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9432       if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9433         return false;   // Attribute not compatible with transformed value.
9434     }
9435
9436     // If the callsite is an invoke instruction, and the return value is used by
9437     // a PHI node in a successor, we cannot change the return type of the call
9438     // because there is no place to put the cast instruction (without breaking
9439     // the critical edge).  Bail out in this case.
9440     if (!Caller->use_empty())
9441       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9442         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9443              UI != E; ++UI)
9444           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9445             if (PN->getParent() == II->getNormalDest() ||
9446                 PN->getParent() == II->getUnwindDest())
9447               return false;
9448   }
9449
9450   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9451   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9452
9453   CallSite::arg_iterator AI = CS.arg_begin();
9454   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9455     const Type *ParamTy = FT->getParamType(i);
9456     const Type *ActTy = (*AI)->getType();
9457
9458     if (!CastInst::isCastable(ActTy, ParamTy))
9459       return false;   // Cannot transform this parameter value.
9460
9461     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9462       return false;   // Attribute not compatible with transformed value.
9463
9464     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
9465     // Some conversions are safe even if we do not have a body.
9466     // Either we can cast directly, or we can upconvert the argument
9467     bool isConvertible = ActTy == ParamTy ||
9468       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
9469       (ParamTy->isInteger() && ActTy->isInteger() &&
9470        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9471       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
9472        && c->getValue().isStrictlyPositive());
9473     if (Callee->isDeclaration() && !isConvertible) return false;
9474   }
9475
9476   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9477       Callee->isDeclaration())
9478     return false;   // Do not delete arguments unless we have a function body.
9479
9480   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9481       !CallerPAL.isEmpty())
9482     // In this case we have more arguments than the new function type, but we
9483     // won't be dropping them.  Check that these extra arguments have attributes
9484     // that are compatible with being a vararg call argument.
9485     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9486       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9487         break;
9488       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9489       if (PAttrs & ParamAttr::VarArgsIncompatible)
9490         return false;
9491     }
9492
9493   // Okay, we decided that this is a safe thing to do: go ahead and start
9494   // inserting cast instructions as necessary...
9495   std::vector<Value*> Args;
9496   Args.reserve(NumActualArgs);
9497   SmallVector<ParamAttrsWithIndex, 8> attrVec;
9498   attrVec.reserve(NumCommonArgs);
9499
9500   // Get any return attributes.
9501   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9502
9503   // If the return value is not being used, the type may not be compatible
9504   // with the existing attributes.  Wipe out any problematic attributes.
9505   RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
9506
9507   // Add the new return attributes.
9508   if (RAttrs)
9509     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
9510
9511   AI = CS.arg_begin();
9512   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9513     const Type *ParamTy = FT->getParamType(i);
9514     if ((*AI)->getType() == ParamTy) {
9515       Args.push_back(*AI);
9516     } else {
9517       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9518           false, ParamTy, false);
9519       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9520       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9521     }
9522
9523     // Add any parameter attributes.
9524     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9525       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9526   }
9527
9528   // If the function takes more arguments than the call was taking, add them
9529   // now...
9530   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9531     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9532
9533   // If we are removing arguments to the function, emit an obnoxious warning...
9534   if (FT->getNumParams() < NumActualArgs) {
9535     if (!FT->isVarArg()) {
9536       cerr << "WARNING: While resolving call to function '"
9537            << Callee->getName() << "' arguments were dropped!\n";
9538     } else {
9539       // Add all of the arguments in their promoted form to the arg list...
9540       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9541         const Type *PTy = getPromotedType((*AI)->getType());
9542         if (PTy != (*AI)->getType()) {
9543           // Must promote to pass through va_arg area!
9544           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9545                                                                 PTy, false);
9546           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9547           InsertNewInstBefore(Cast, *Caller);
9548           Args.push_back(Cast);
9549         } else {
9550           Args.push_back(*AI);
9551         }
9552
9553         // Add any parameter attributes.
9554         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9555           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9556       }
9557     }
9558   }
9559
9560   if (FT->getReturnType() == Type::VoidTy)
9561     Caller->setName("");   // Void type should not have a name.
9562
9563   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9564
9565   Instruction *NC;
9566   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9567     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9568                             Args.begin(), Args.end(),
9569                             Caller->getName(), Caller);
9570     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9571     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9572   } else {
9573     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9574                           Caller->getName(), Caller);
9575     CallInst *CI = cast<CallInst>(Caller);
9576     if (CI->isTailCall())
9577       cast<CallInst>(NC)->setTailCall();
9578     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9579     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9580   }
9581
9582   // Insert a cast of the return type as necessary.
9583   Value *NV = NC;
9584   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9585     if (NV->getType() != Type::VoidTy) {
9586       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9587                                                             OldRetTy, false);
9588       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9589
9590       // If this is an invoke instruction, we should insert it after the first
9591       // non-phi, instruction in the normal successor block.
9592       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9593         BasicBlock::iterator I = II->getNormalDest()->begin();
9594         while (isa<PHINode>(I)) ++I;
9595         InsertNewInstBefore(NC, *I);
9596       } else {
9597         // Otherwise, it's a call, just insert cast right after the call instr
9598         InsertNewInstBefore(NC, *Caller);
9599       }
9600       AddUsersToWorkList(*Caller);
9601     } else {
9602       NV = UndefValue::get(Caller->getType());
9603     }
9604   }
9605
9606   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9607     Caller->replaceAllUsesWith(NV);
9608   Caller->eraseFromParent();
9609   RemoveFromWorkList(Caller);
9610   return true;
9611 }
9612
9613 // transformCallThroughTrampoline - Turn a call to a function created by the
9614 // init_trampoline intrinsic into a direct call to the underlying function.
9615 //
9616 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9617   Value *Callee = CS.getCalledValue();
9618   const PointerType *PTy = cast<PointerType>(Callee->getType());
9619   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9620   const PAListPtr &Attrs = CS.getParamAttrs();
9621
9622   // If the call already has the 'nest' attribute somewhere then give up -
9623   // otherwise 'nest' would occur twice after splicing in the chain.
9624   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9625     return 0;
9626
9627   IntrinsicInst *Tramp =
9628     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9629
9630   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9631   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9632   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9633
9634   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9635   if (!NestAttrs.isEmpty()) {
9636     unsigned NestIdx = 1;
9637     const Type *NestTy = 0;
9638     ParameterAttributes NestAttr = ParamAttr::None;
9639
9640     // Look for a parameter marked with the 'nest' attribute.
9641     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9642          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9643       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9644         // Record the parameter type and any other attributes.
9645         NestTy = *I;
9646         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9647         break;
9648       }
9649
9650     if (NestTy) {
9651       Instruction *Caller = CS.getInstruction();
9652       std::vector<Value*> NewArgs;
9653       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9654
9655       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9656       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9657
9658       // Insert the nest argument into the call argument list, which may
9659       // mean appending it.  Likewise for attributes.
9660
9661       // Add any function result attributes.
9662       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9663         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9664
9665       {
9666         unsigned Idx = 1;
9667         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9668         do {
9669           if (Idx == NestIdx) {
9670             // Add the chain argument and attributes.
9671             Value *NestVal = Tramp->getOperand(3);
9672             if (NestVal->getType() != NestTy)
9673               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9674             NewArgs.push_back(NestVal);
9675             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9676           }
9677
9678           if (I == E)
9679             break;
9680
9681           // Add the original argument and attributes.
9682           NewArgs.push_back(*I);
9683           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9684             NewAttrs.push_back
9685               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9686
9687           ++Idx, ++I;
9688         } while (1);
9689       }
9690
9691       // The trampoline may have been bitcast to a bogus type (FTy).
9692       // Handle this by synthesizing a new function type, equal to FTy
9693       // with the chain parameter inserted.
9694
9695       std::vector<const Type*> NewTypes;
9696       NewTypes.reserve(FTy->getNumParams()+1);
9697
9698       // Insert the chain's type into the list of parameter types, which may
9699       // mean appending it.
9700       {
9701         unsigned Idx = 1;
9702         FunctionType::param_iterator I = FTy->param_begin(),
9703           E = FTy->param_end();
9704
9705         do {
9706           if (Idx == NestIdx)
9707             // Add the chain's type.
9708             NewTypes.push_back(NestTy);
9709
9710           if (I == E)
9711             break;
9712
9713           // Add the original type.
9714           NewTypes.push_back(*I);
9715
9716           ++Idx, ++I;
9717         } while (1);
9718       }
9719
9720       // Replace the trampoline call with a direct call.  Let the generic
9721       // code sort out any function type mismatches.
9722       FunctionType *NewFTy =
9723         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9724       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9725         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9726       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9727
9728       Instruction *NewCaller;
9729       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9730         NewCaller = InvokeInst::Create(NewCallee,
9731                                        II->getNormalDest(), II->getUnwindDest(),
9732                                        NewArgs.begin(), NewArgs.end(),
9733                                        Caller->getName(), Caller);
9734         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9735         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9736       } else {
9737         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9738                                      Caller->getName(), Caller);
9739         if (cast<CallInst>(Caller)->isTailCall())
9740           cast<CallInst>(NewCaller)->setTailCall();
9741         cast<CallInst>(NewCaller)->
9742           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9743         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9744       }
9745       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9746         Caller->replaceAllUsesWith(NewCaller);
9747       Caller->eraseFromParent();
9748       RemoveFromWorkList(Caller);
9749       return 0;
9750     }
9751   }
9752
9753   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9754   // parameter, there is no need to adjust the argument list.  Let the generic
9755   // code sort out any function type mismatches.
9756   Constant *NewCallee =
9757     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9758   CS.setCalledFunction(NewCallee);
9759   return CS.getInstruction();
9760 }
9761
9762 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9763 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9764 /// and a single binop.
9765 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9766   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9767   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9768          isa<CmpInst>(FirstInst));
9769   unsigned Opc = FirstInst->getOpcode();
9770   Value *LHSVal = FirstInst->getOperand(0);
9771   Value *RHSVal = FirstInst->getOperand(1);
9772     
9773   const Type *LHSType = LHSVal->getType();
9774   const Type *RHSType = RHSVal->getType();
9775   
9776   // Scan to see if all operands are the same opcode, all have one use, and all
9777   // kill their operands (i.e. the operands have one use).
9778   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9779     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9780     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9781         // Verify type of the LHS matches so we don't fold cmp's of different
9782         // types or GEP's with different index types.
9783         I->getOperand(0)->getType() != LHSType ||
9784         I->getOperand(1)->getType() != RHSType)
9785       return 0;
9786
9787     // If they are CmpInst instructions, check their predicates
9788     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9789       if (cast<CmpInst>(I)->getPredicate() !=
9790           cast<CmpInst>(FirstInst)->getPredicate())
9791         return 0;
9792     
9793     // Keep track of which operand needs a phi node.
9794     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9795     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9796   }
9797   
9798   // Otherwise, this is safe to transform, determine if it is profitable.
9799
9800   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9801   // Indexes are often folded into load/store instructions, so we don't want to
9802   // hide them behind a phi.
9803   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9804     return 0;
9805   
9806   Value *InLHS = FirstInst->getOperand(0);
9807   Value *InRHS = FirstInst->getOperand(1);
9808   PHINode *NewLHS = 0, *NewRHS = 0;
9809   if (LHSVal == 0) {
9810     NewLHS = PHINode::Create(LHSType,
9811                              FirstInst->getOperand(0)->getName() + ".pn");
9812     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9813     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9814     InsertNewInstBefore(NewLHS, PN);
9815     LHSVal = NewLHS;
9816   }
9817   
9818   if (RHSVal == 0) {
9819     NewRHS = PHINode::Create(RHSType,
9820                              FirstInst->getOperand(1)->getName() + ".pn");
9821     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9822     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9823     InsertNewInstBefore(NewRHS, PN);
9824     RHSVal = NewRHS;
9825   }
9826   
9827   // Add all operands to the new PHIs.
9828   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9829     if (NewLHS) {
9830       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9831       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9832     }
9833     if (NewRHS) {
9834       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9835       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9836     }
9837   }
9838     
9839   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9840     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9841   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9842     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9843                            RHSVal);
9844   else {
9845     assert(isa<GetElementPtrInst>(FirstInst));
9846     return GetElementPtrInst::Create(LHSVal, RHSVal);
9847   }
9848 }
9849
9850 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9851 /// of the block that defines it.  This means that it must be obvious the value
9852 /// of the load is not changed from the point of the load to the end of the
9853 /// block it is in.
9854 ///
9855 /// Finally, it is safe, but not profitable, to sink a load targetting a
9856 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9857 /// to a register.
9858 static bool isSafeToSinkLoad(LoadInst *L) {
9859   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9860   
9861   for (++BBI; BBI != E; ++BBI)
9862     if (BBI->mayWriteToMemory())
9863       return false;
9864   
9865   // Check for non-address taken alloca.  If not address-taken already, it isn't
9866   // profitable to do this xform.
9867   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9868     bool isAddressTaken = false;
9869     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9870          UI != E; ++UI) {
9871       if (isa<LoadInst>(UI)) continue;
9872       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9873         // If storing TO the alloca, then the address isn't taken.
9874         if (SI->getOperand(1) == AI) continue;
9875       }
9876       isAddressTaken = true;
9877       break;
9878     }
9879     
9880     if (!isAddressTaken)
9881       return false;
9882   }
9883   
9884   return true;
9885 }
9886
9887
9888 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9889 // operator and they all are only used by the PHI, PHI together their
9890 // inputs, and do the operation once, to the result of the PHI.
9891 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9892   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9893
9894   // Scan the instruction, looking for input operations that can be folded away.
9895   // If all input operands to the phi are the same instruction (e.g. a cast from
9896   // the same type or "+42") we can pull the operation through the PHI, reducing
9897   // code size and simplifying code.
9898   Constant *ConstantOp = 0;
9899   const Type *CastSrcTy = 0;
9900   bool isVolatile = false;
9901   if (isa<CastInst>(FirstInst)) {
9902     CastSrcTy = FirstInst->getOperand(0)->getType();
9903   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9904     // Can fold binop, compare or shift here if the RHS is a constant, 
9905     // otherwise call FoldPHIArgBinOpIntoPHI.
9906     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9907     if (ConstantOp == 0)
9908       return FoldPHIArgBinOpIntoPHI(PN);
9909   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9910     isVolatile = LI->isVolatile();
9911     // We can't sink the load if the loaded value could be modified between the
9912     // load and the PHI.
9913     if (LI->getParent() != PN.getIncomingBlock(0) ||
9914         !isSafeToSinkLoad(LI))
9915       return 0;
9916   } else if (isa<GetElementPtrInst>(FirstInst)) {
9917     if (FirstInst->getNumOperands() == 2)
9918       return FoldPHIArgBinOpIntoPHI(PN);
9919     // Can't handle general GEPs yet.
9920     return 0;
9921   } else {
9922     return 0;  // Cannot fold this operation.
9923   }
9924
9925   // Check to see if all arguments are the same operation.
9926   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9927     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9928     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9929     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9930       return 0;
9931     if (CastSrcTy) {
9932       if (I->getOperand(0)->getType() != CastSrcTy)
9933         return 0;  // Cast operation must match.
9934     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9935       // We can't sink the load if the loaded value could be modified between 
9936       // the load and the PHI.
9937       if (LI->isVolatile() != isVolatile ||
9938           LI->getParent() != PN.getIncomingBlock(i) ||
9939           !isSafeToSinkLoad(LI))
9940         return 0;
9941       
9942       // If the PHI is volatile and its block has multiple successors, sinking
9943       // it would remove a load of the volatile value from the path through the
9944       // other successor.
9945       if (isVolatile &&
9946           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9947         return 0;
9948
9949       
9950     } else if (I->getOperand(1) != ConstantOp) {
9951       return 0;
9952     }
9953   }
9954
9955   // Okay, they are all the same operation.  Create a new PHI node of the
9956   // correct type, and PHI together all of the LHS's of the instructions.
9957   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9958                                    PN.getName()+".in");
9959   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9960
9961   Value *InVal = FirstInst->getOperand(0);
9962   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9963
9964   // Add all operands to the new PHI.
9965   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9966     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9967     if (NewInVal != InVal)
9968       InVal = 0;
9969     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9970   }
9971
9972   Value *PhiVal;
9973   if (InVal) {
9974     // The new PHI unions all of the same values together.  This is really
9975     // common, so we handle it intelligently here for compile-time speed.
9976     PhiVal = InVal;
9977     delete NewPN;
9978   } else {
9979     InsertNewInstBefore(NewPN, PN);
9980     PhiVal = NewPN;
9981   }
9982
9983   // Insert and return the new operation.
9984   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9985     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9986   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9987     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9988   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9989     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9990                            PhiVal, ConstantOp);
9991   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9992   
9993   // If this was a volatile load that we are merging, make sure to loop through
9994   // and mark all the input loads as non-volatile.  If we don't do this, we will
9995   // insert a new volatile load and the old ones will not be deletable.
9996   if (isVolatile)
9997     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9998       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9999   
10000   return new LoadInst(PhiVal, "", isVolatile);
10001 }
10002
10003 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10004 /// that is dead.
10005 static bool DeadPHICycle(PHINode *PN,
10006                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10007   if (PN->use_empty()) return true;
10008   if (!PN->hasOneUse()) return false;
10009
10010   // Remember this node, and if we find the cycle, return.
10011   if (!PotentiallyDeadPHIs.insert(PN))
10012     return true;
10013   
10014   // Don't scan crazily complex things.
10015   if (PotentiallyDeadPHIs.size() == 16)
10016     return false;
10017
10018   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10019     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10020
10021   return false;
10022 }
10023
10024 /// PHIsEqualValue - Return true if this phi node is always equal to
10025 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10026 ///   z = some value; x = phi (y, z); y = phi (x, z)
10027 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10028                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10029   // See if we already saw this PHI node.
10030   if (!ValueEqualPHIs.insert(PN))
10031     return true;
10032   
10033   // Don't scan crazily complex things.
10034   if (ValueEqualPHIs.size() == 16)
10035     return false;
10036  
10037   // Scan the operands to see if they are either phi nodes or are equal to
10038   // the value.
10039   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10040     Value *Op = PN->getIncomingValue(i);
10041     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10042       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10043         return false;
10044     } else if (Op != NonPhiInVal)
10045       return false;
10046   }
10047   
10048   return true;
10049 }
10050
10051
10052 // PHINode simplification
10053 //
10054 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10055   // If LCSSA is around, don't mess with Phi nodes
10056   if (MustPreserveLCSSA) return 0;
10057   
10058   if (Value *V = PN.hasConstantValue())
10059     return ReplaceInstUsesWith(PN, V);
10060
10061   // If all PHI operands are the same operation, pull them through the PHI,
10062   // reducing code size.
10063   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10064       PN.getIncomingValue(0)->hasOneUse())
10065     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10066       return Result;
10067
10068   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10069   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10070   // PHI)... break the cycle.
10071   if (PN.hasOneUse()) {
10072     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10073     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10074       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10075       PotentiallyDeadPHIs.insert(&PN);
10076       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10077         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10078     }
10079    
10080     // If this phi has a single use, and if that use just computes a value for
10081     // the next iteration of a loop, delete the phi.  This occurs with unused
10082     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10083     // common case here is good because the only other things that catch this
10084     // are induction variable analysis (sometimes) and ADCE, which is only run
10085     // late.
10086     if (PHIUser->hasOneUse() &&
10087         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10088         PHIUser->use_back() == &PN) {
10089       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10090     }
10091   }
10092
10093   // We sometimes end up with phi cycles that non-obviously end up being the
10094   // same value, for example:
10095   //   z = some value; x = phi (y, z); y = phi (x, z)
10096   // where the phi nodes don't necessarily need to be in the same block.  Do a
10097   // quick check to see if the PHI node only contains a single non-phi value, if
10098   // so, scan to see if the phi cycle is actually equal to that value.
10099   {
10100     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10101     // Scan for the first non-phi operand.
10102     while (InValNo != NumOperandVals && 
10103            isa<PHINode>(PN.getIncomingValue(InValNo)))
10104       ++InValNo;
10105
10106     if (InValNo != NumOperandVals) {
10107       Value *NonPhiInVal = PN.getOperand(InValNo);
10108       
10109       // Scan the rest of the operands to see if there are any conflicts, if so
10110       // there is no need to recursively scan other phis.
10111       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10112         Value *OpVal = PN.getIncomingValue(InValNo);
10113         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10114           break;
10115       }
10116       
10117       // If we scanned over all operands, then we have one unique value plus
10118       // phi values.  Scan PHI nodes to see if they all merge in each other or
10119       // the value.
10120       if (InValNo == NumOperandVals) {
10121         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10122         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10123           return ReplaceInstUsesWith(PN, NonPhiInVal);
10124       }
10125     }
10126   }
10127   return 0;
10128 }
10129
10130 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10131                                    Instruction *InsertPoint,
10132                                    InstCombiner *IC) {
10133   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10134   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10135   // We must cast correctly to the pointer type. Ensure that we
10136   // sign extend the integer value if it is smaller as this is
10137   // used for address computation.
10138   Instruction::CastOps opcode = 
10139      (VTySize < PtrSize ? Instruction::SExt :
10140       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10141   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10142 }
10143
10144
10145 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10146   Value *PtrOp = GEP.getOperand(0);
10147   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10148   // If so, eliminate the noop.
10149   if (GEP.getNumOperands() == 1)
10150     return ReplaceInstUsesWith(GEP, PtrOp);
10151
10152   if (isa<UndefValue>(GEP.getOperand(0)))
10153     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10154
10155   bool HasZeroPointerIndex = false;
10156   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10157     HasZeroPointerIndex = C->isNullValue();
10158
10159   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10160     return ReplaceInstUsesWith(GEP, PtrOp);
10161
10162   // Eliminate unneeded casts for indices.
10163   bool MadeChange = false;
10164   
10165   gep_type_iterator GTI = gep_type_begin(GEP);
10166   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
10167     if (isa<SequentialType>(*GTI)) {
10168       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
10169         if (CI->getOpcode() == Instruction::ZExt ||
10170             CI->getOpcode() == Instruction::SExt) {
10171           const Type *SrcTy = CI->getOperand(0)->getType();
10172           // We can eliminate a cast from i32 to i64 iff the target 
10173           // is a 32-bit pointer target.
10174           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10175             MadeChange = true;
10176             GEP.setOperand(i, CI->getOperand(0));
10177           }
10178         }
10179       }
10180       // If we are using a wider index than needed for this platform, shrink it
10181       // to what we need.  If the incoming value needs a cast instruction,
10182       // insert it.  This explicit cast can make subsequent optimizations more
10183       // obvious.
10184       Value *Op = GEP.getOperand(i);
10185       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10186         if (Constant *C = dyn_cast<Constant>(Op)) {
10187           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
10188           MadeChange = true;
10189         } else {
10190           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10191                                 GEP);
10192           GEP.setOperand(i, Op);
10193           MadeChange = true;
10194         }
10195       }
10196     }
10197   }
10198   if (MadeChange) return &GEP;
10199
10200   // If this GEP instruction doesn't move the pointer, and if the input operand
10201   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10202   // real input to the dest type.
10203   if (GEP.hasAllZeroIndices()) {
10204     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10205       // If the bitcast is of an allocation, and the allocation will be
10206       // converted to match the type of the cast, don't touch this.
10207       if (isa<AllocationInst>(BCI->getOperand(0))) {
10208         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10209         if (Instruction *I = visitBitCast(*BCI)) {
10210           if (I != BCI) {
10211             I->takeName(BCI);
10212             BCI->getParent()->getInstList().insert(BCI, I);
10213             ReplaceInstUsesWith(*BCI, I);
10214           }
10215           return &GEP;
10216         }
10217       }
10218       return new BitCastInst(BCI->getOperand(0), GEP.getType());
10219     }
10220   }
10221   
10222   // Combine Indices - If the source pointer to this getelementptr instruction
10223   // is a getelementptr instruction, combine the indices of the two
10224   // getelementptr instructions into a single instruction.
10225   //
10226   SmallVector<Value*, 8> SrcGEPOperands;
10227   if (User *Src = dyn_castGetElementPtr(PtrOp))
10228     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10229
10230   if (!SrcGEPOperands.empty()) {
10231     // Note that if our source is a gep chain itself that we wait for that
10232     // chain to be resolved before we perform this transformation.  This
10233     // avoids us creating a TON of code in some cases.
10234     //
10235     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10236         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10237       return 0;   // Wait until our source is folded to completion.
10238
10239     SmallVector<Value*, 8> Indices;
10240
10241     // Find out whether the last index in the source GEP is a sequential idx.
10242     bool EndsWithSequential = false;
10243     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10244            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10245       EndsWithSequential = !isa<StructType>(*I);
10246
10247     // Can we combine the two pointer arithmetics offsets?
10248     if (EndsWithSequential) {
10249       // Replace: gep (gep %P, long B), long A, ...
10250       // With:    T = long A+B; gep %P, T, ...
10251       //
10252       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10253       if (SO1 == Constant::getNullValue(SO1->getType())) {
10254         Sum = GO1;
10255       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10256         Sum = SO1;
10257       } else {
10258         // If they aren't the same type, convert both to an integer of the
10259         // target's pointer size.
10260         if (SO1->getType() != GO1->getType()) {
10261           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10262             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10263           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10264             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10265           } else {
10266             unsigned PS = TD->getPointerSizeInBits();
10267             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10268               // Convert GO1 to SO1's type.
10269               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10270
10271             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10272               // Convert SO1 to GO1's type.
10273               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10274             } else {
10275               const Type *PT = TD->getIntPtrType();
10276               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10277               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10278             }
10279           }
10280         }
10281         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10282           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10283         else {
10284           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10285           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10286         }
10287       }
10288
10289       // Recycle the GEP we already have if possible.
10290       if (SrcGEPOperands.size() == 2) {
10291         GEP.setOperand(0, SrcGEPOperands[0]);
10292         GEP.setOperand(1, Sum);
10293         return &GEP;
10294       } else {
10295         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10296                        SrcGEPOperands.end()-1);
10297         Indices.push_back(Sum);
10298         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10299       }
10300     } else if (isa<Constant>(*GEP.idx_begin()) &&
10301                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10302                SrcGEPOperands.size() != 1) {
10303       // Otherwise we can do the fold if the first index of the GEP is a zero
10304       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10305                      SrcGEPOperands.end());
10306       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10307     }
10308
10309     if (!Indices.empty())
10310       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10311                                        Indices.end(), GEP.getName());
10312
10313   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10314     // GEP of global variable.  If all of the indices for this GEP are
10315     // constants, we can promote this to a constexpr instead of an instruction.
10316
10317     // Scan for nonconstants...
10318     SmallVector<Constant*, 8> Indices;
10319     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10320     for (; I != E && isa<Constant>(*I); ++I)
10321       Indices.push_back(cast<Constant>(*I));
10322
10323     if (I == E) {  // If they are all constants...
10324       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10325                                                     &Indices[0],Indices.size());
10326
10327       // Replace all uses of the GEP with the new constexpr...
10328       return ReplaceInstUsesWith(GEP, CE);
10329     }
10330   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10331     if (!isa<PointerType>(X->getType())) {
10332       // Not interesting.  Source pointer must be a cast from pointer.
10333     } else if (HasZeroPointerIndex) {
10334       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10335       // into     : GEP [10 x i8]* X, i32 0, ...
10336       //
10337       // This occurs when the program declares an array extern like "int X[];"
10338       //
10339       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10340       const PointerType *XTy = cast<PointerType>(X->getType());
10341       if (const ArrayType *XATy =
10342           dyn_cast<ArrayType>(XTy->getElementType()))
10343         if (const ArrayType *CATy =
10344             dyn_cast<ArrayType>(CPTy->getElementType()))
10345           if (CATy->getElementType() == XATy->getElementType()) {
10346             // At this point, we know that the cast source type is a pointer
10347             // to an array of the same type as the destination pointer
10348             // array.  Because the array type is never stepped over (there
10349             // is a leading zero) we can fold the cast into this GEP.
10350             GEP.setOperand(0, X);
10351             return &GEP;
10352           }
10353     } else if (GEP.getNumOperands() == 2) {
10354       // Transform things like:
10355       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10356       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10357       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10358       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10359       if (isa<ArrayType>(SrcElTy) &&
10360           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10361           TD->getABITypeSize(ResElTy)) {
10362         Value *Idx[2];
10363         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10364         Idx[1] = GEP.getOperand(1);
10365         Value *V = InsertNewInstBefore(
10366                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10367         // V and GEP are both pointer types --> BitCast
10368         return new BitCastInst(V, GEP.getType());
10369       }
10370       
10371       // Transform things like:
10372       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10373       //   (where tmp = 8*tmp2) into:
10374       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10375       
10376       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10377         uint64_t ArrayEltSize =
10378             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10379         
10380         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10381         // allow either a mul, shift, or constant here.
10382         Value *NewIdx = 0;
10383         ConstantInt *Scale = 0;
10384         if (ArrayEltSize == 1) {
10385           NewIdx = GEP.getOperand(1);
10386           Scale = ConstantInt::get(NewIdx->getType(), 1);
10387         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10388           NewIdx = ConstantInt::get(CI->getType(), 1);
10389           Scale = CI;
10390         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10391           if (Inst->getOpcode() == Instruction::Shl &&
10392               isa<ConstantInt>(Inst->getOperand(1))) {
10393             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10394             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10395             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10396             NewIdx = Inst->getOperand(0);
10397           } else if (Inst->getOpcode() == Instruction::Mul &&
10398                      isa<ConstantInt>(Inst->getOperand(1))) {
10399             Scale = cast<ConstantInt>(Inst->getOperand(1));
10400             NewIdx = Inst->getOperand(0);
10401           }
10402         }
10403         
10404         // If the index will be to exactly the right offset with the scale taken
10405         // out, perform the transformation. Note, we don't know whether Scale is
10406         // signed or not. We'll use unsigned version of division/modulo
10407         // operation after making sure Scale doesn't have the sign bit set.
10408         if (Scale && Scale->getSExtValue() >= 0LL &&
10409             Scale->getZExtValue() % ArrayEltSize == 0) {
10410           Scale = ConstantInt::get(Scale->getType(),
10411                                    Scale->getZExtValue() / ArrayEltSize);
10412           if (Scale->getZExtValue() != 1) {
10413             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10414                                                        false /*ZExt*/);
10415             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10416             NewIdx = InsertNewInstBefore(Sc, GEP);
10417           }
10418
10419           // Insert the new GEP instruction.
10420           Value *Idx[2];
10421           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10422           Idx[1] = NewIdx;
10423           Instruction *NewGEP =
10424             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10425           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10426           // The NewGEP must be pointer typed, so must the old one -> BitCast
10427           return new BitCastInst(NewGEP, GEP.getType());
10428         }
10429       }
10430     }
10431   }
10432
10433   return 0;
10434 }
10435
10436 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10437   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10438   if (AI.isArrayAllocation()) {  // Check C != 1
10439     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10440       const Type *NewTy = 
10441         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10442       AllocationInst *New = 0;
10443
10444       // Create and insert the replacement instruction...
10445       if (isa<MallocInst>(AI))
10446         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10447       else {
10448         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10449         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10450       }
10451
10452       InsertNewInstBefore(New, AI);
10453
10454       // Scan to the end of the allocation instructions, to skip over a block of
10455       // allocas if possible...
10456       //
10457       BasicBlock::iterator It = New;
10458       while (isa<AllocationInst>(*It)) ++It;
10459
10460       // Now that I is pointing to the first non-allocation-inst in the block,
10461       // insert our getelementptr instruction...
10462       //
10463       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10464       Value *Idx[2];
10465       Idx[0] = NullIdx;
10466       Idx[1] = NullIdx;
10467       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10468                                            New->getName()+".sub", It);
10469
10470       // Now make everything use the getelementptr instead of the original
10471       // allocation.
10472       return ReplaceInstUsesWith(AI, V);
10473     } else if (isa<UndefValue>(AI.getArraySize())) {
10474       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10475     }
10476   }
10477
10478   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10479   // Note that we only do this for alloca's, because malloc should allocate and
10480   // return a unique pointer, even for a zero byte allocation.
10481   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10482       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10483     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10484
10485   return 0;
10486 }
10487
10488 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10489   Value *Op = FI.getOperand(0);
10490
10491   // free undef -> unreachable.
10492   if (isa<UndefValue>(Op)) {
10493     // Insert a new store to null because we cannot modify the CFG here.
10494     new StoreInst(ConstantInt::getTrue(),
10495                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10496     return EraseInstFromFunction(FI);
10497   }
10498   
10499   // If we have 'free null' delete the instruction.  This can happen in stl code
10500   // when lots of inlining happens.
10501   if (isa<ConstantPointerNull>(Op))
10502     return EraseInstFromFunction(FI);
10503   
10504   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10505   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10506     FI.setOperand(0, CI->getOperand(0));
10507     return &FI;
10508   }
10509   
10510   // Change free (gep X, 0,0,0,0) into free(X)
10511   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10512     if (GEPI->hasAllZeroIndices()) {
10513       AddToWorkList(GEPI);
10514       FI.setOperand(0, GEPI->getOperand(0));
10515       return &FI;
10516     }
10517   }
10518   
10519   // Change free(malloc) into nothing, if the malloc has a single use.
10520   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10521     if (MI->hasOneUse()) {
10522       EraseInstFromFunction(FI);
10523       return EraseInstFromFunction(*MI);
10524     }
10525
10526   return 0;
10527 }
10528
10529
10530 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10531 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10532                                         const TargetData *TD) {
10533   User *CI = cast<User>(LI.getOperand(0));
10534   Value *CastOp = CI->getOperand(0);
10535
10536   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10537     // Instead of loading constant c string, use corresponding integer value
10538     // directly if string length is small enough.
10539     const std::string &Str = CE->getOperand(0)->getStringValue();
10540     if (!Str.empty()) {
10541       unsigned len = Str.length();
10542       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10543       unsigned numBits = Ty->getPrimitiveSizeInBits();
10544       // Replace LI with immediate integer store.
10545       if ((numBits >> 3) == len + 1) {
10546         APInt StrVal(numBits, 0);
10547         APInt SingleChar(numBits, 0);
10548         if (TD->isLittleEndian()) {
10549           for (signed i = len-1; i >= 0; i--) {
10550             SingleChar = (uint64_t) Str[i];
10551             StrVal = (StrVal << 8) | SingleChar;
10552           }
10553         } else {
10554           for (unsigned i = 0; i < len; i++) {
10555             SingleChar = (uint64_t) Str[i];
10556             StrVal = (StrVal << 8) | SingleChar;
10557           }
10558           // Append NULL at the end.
10559           SingleChar = 0;
10560           StrVal = (StrVal << 8) | SingleChar;
10561         }
10562         Value *NL = ConstantInt::get(StrVal);
10563         return IC.ReplaceInstUsesWith(LI, NL);
10564       }
10565     }
10566   }
10567
10568   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10569   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10570     const Type *SrcPTy = SrcTy->getElementType();
10571
10572     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10573          isa<VectorType>(DestPTy)) {
10574       // If the source is an array, the code below will not succeed.  Check to
10575       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10576       // constants.
10577       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10578         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10579           if (ASrcTy->getNumElements() != 0) {
10580             Value *Idxs[2];
10581             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10582             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10583             SrcTy = cast<PointerType>(CastOp->getType());
10584             SrcPTy = SrcTy->getElementType();
10585           }
10586
10587       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10588             isa<VectorType>(SrcPTy)) &&
10589           // Do not allow turning this into a load of an integer, which is then
10590           // casted to a pointer, this pessimizes pointer analysis a lot.
10591           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10592           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10593                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10594
10595         // Okay, we are casting from one integer or pointer type to another of
10596         // the same size.  Instead of casting the pointer before the load, cast
10597         // the result of the loaded value.
10598         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10599                                                              CI->getName(),
10600                                                          LI.isVolatile()),LI);
10601         // Now cast the result of the load.
10602         return new BitCastInst(NewLoad, LI.getType());
10603       }
10604     }
10605   }
10606   return 0;
10607 }
10608
10609 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10610 /// from this value cannot trap.  If it is not obviously safe to load from the
10611 /// specified pointer, we do a quick local scan of the basic block containing
10612 /// ScanFrom, to determine if the address is already accessed.
10613 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10614   // If it is an alloca it is always safe to load from.
10615   if (isa<AllocaInst>(V)) return true;
10616
10617   // If it is a global variable it is mostly safe to load from.
10618   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10619     // Don't try to evaluate aliases.  External weak GV can be null.
10620     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10621
10622   // Otherwise, be a little bit agressive by scanning the local block where we
10623   // want to check to see if the pointer is already being loaded or stored
10624   // from/to.  If so, the previous load or store would have already trapped,
10625   // so there is no harm doing an extra load (also, CSE will later eliminate
10626   // the load entirely).
10627   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10628
10629   while (BBI != E) {
10630     --BBI;
10631
10632     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10633       if (LI->getOperand(0) == V) return true;
10634     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10635       if (SI->getOperand(1) == V) return true;
10636
10637   }
10638   return false;
10639 }
10640
10641 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10642 /// until we find the underlying object a pointer is referring to or something
10643 /// we don't understand.  Note that the returned pointer may be offset from the
10644 /// input, because we ignore GEP indices.
10645 static Value *GetUnderlyingObject(Value *Ptr) {
10646   while (1) {
10647     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10648       if (CE->getOpcode() == Instruction::BitCast ||
10649           CE->getOpcode() == Instruction::GetElementPtr)
10650         Ptr = CE->getOperand(0);
10651       else
10652         return Ptr;
10653     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10654       Ptr = BCI->getOperand(0);
10655     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10656       Ptr = GEP->getOperand(0);
10657     } else {
10658       return Ptr;
10659     }
10660   }
10661 }
10662
10663 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10664   Value *Op = LI.getOperand(0);
10665
10666   // Attempt to improve the alignment.
10667   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10668   if (KnownAlign >
10669       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10670                                 LI.getAlignment()))
10671     LI.setAlignment(KnownAlign);
10672
10673   // load (cast X) --> cast (load X) iff safe
10674   if (isa<CastInst>(Op))
10675     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10676       return Res;
10677
10678   // None of the following transforms are legal for volatile loads.
10679   if (LI.isVolatile()) return 0;
10680   
10681   if (&LI.getParent()->front() != &LI) {
10682     BasicBlock::iterator BBI = &LI; --BBI;
10683     // If the instruction immediately before this is a store to the same
10684     // address, do a simple form of store->load forwarding.
10685     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10686       if (SI->getOperand(1) == LI.getOperand(0))
10687         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10688     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10689       if (LIB->getOperand(0) == LI.getOperand(0))
10690         return ReplaceInstUsesWith(LI, LIB);
10691   }
10692
10693   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10694     const Value *GEPI0 = GEPI->getOperand(0);
10695     // TODO: Consider a target hook for valid address spaces for this xform.
10696     if (isa<ConstantPointerNull>(GEPI0) &&
10697         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10698       // Insert a new store to null instruction before the load to indicate
10699       // that this code is not reachable.  We do this instead of inserting
10700       // an unreachable instruction directly because we cannot modify the
10701       // CFG.
10702       new StoreInst(UndefValue::get(LI.getType()),
10703                     Constant::getNullValue(Op->getType()), &LI);
10704       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10705     }
10706   } 
10707
10708   if (Constant *C = dyn_cast<Constant>(Op)) {
10709     // load null/undef -> undef
10710     // TODO: Consider a target hook for valid address spaces for this xform.
10711     if (isa<UndefValue>(C) || (C->isNullValue() && 
10712         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10713       // Insert a new store to null instruction before the load to indicate that
10714       // this code is not reachable.  We do this instead of inserting an
10715       // unreachable instruction directly because we cannot modify the CFG.
10716       new StoreInst(UndefValue::get(LI.getType()),
10717                     Constant::getNullValue(Op->getType()), &LI);
10718       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10719     }
10720
10721     // Instcombine load (constant global) into the value loaded.
10722     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10723       if (GV->isConstant() && !GV->isDeclaration())
10724         return ReplaceInstUsesWith(LI, GV->getInitializer());
10725
10726     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10727     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10728       if (CE->getOpcode() == Instruction::GetElementPtr) {
10729         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10730           if (GV->isConstant() && !GV->isDeclaration())
10731             if (Constant *V = 
10732                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10733               return ReplaceInstUsesWith(LI, V);
10734         if (CE->getOperand(0)->isNullValue()) {
10735           // Insert a new store to null instruction before the load to indicate
10736           // that this code is not reachable.  We do this instead of inserting
10737           // an unreachable instruction directly because we cannot modify the
10738           // CFG.
10739           new StoreInst(UndefValue::get(LI.getType()),
10740                         Constant::getNullValue(Op->getType()), &LI);
10741           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10742         }
10743
10744       } else if (CE->isCast()) {
10745         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10746           return Res;
10747       }
10748     }
10749   }
10750     
10751   // If this load comes from anywhere in a constant global, and if the global
10752   // is all undef or zero, we know what it loads.
10753   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10754     if (GV->isConstant() && GV->hasInitializer()) {
10755       if (GV->getInitializer()->isNullValue())
10756         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10757       else if (isa<UndefValue>(GV->getInitializer()))
10758         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10759     }
10760   }
10761
10762   if (Op->hasOneUse()) {
10763     // Change select and PHI nodes to select values instead of addresses: this
10764     // helps alias analysis out a lot, allows many others simplifications, and
10765     // exposes redundancy in the code.
10766     //
10767     // Note that we cannot do the transformation unless we know that the
10768     // introduced loads cannot trap!  Something like this is valid as long as
10769     // the condition is always false: load (select bool %C, int* null, int* %G),
10770     // but it would not be valid if we transformed it to load from null
10771     // unconditionally.
10772     //
10773     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10774       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10775       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10776           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10777         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10778                                      SI->getOperand(1)->getName()+".val"), LI);
10779         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10780                                      SI->getOperand(2)->getName()+".val"), LI);
10781         return SelectInst::Create(SI->getCondition(), V1, V2);
10782       }
10783
10784       // load (select (cond, null, P)) -> load P
10785       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10786         if (C->isNullValue()) {
10787           LI.setOperand(0, SI->getOperand(2));
10788           return &LI;
10789         }
10790
10791       // load (select (cond, P, null)) -> load P
10792       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10793         if (C->isNullValue()) {
10794           LI.setOperand(0, SI->getOperand(1));
10795           return &LI;
10796         }
10797     }
10798   }
10799   return 0;
10800 }
10801
10802 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10803 /// when possible.
10804 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10805   User *CI = cast<User>(SI.getOperand(1));
10806   Value *CastOp = CI->getOperand(0);
10807
10808   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10809   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10810     const Type *SrcPTy = SrcTy->getElementType();
10811
10812     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10813       // If the source is an array, the code below will not succeed.  Check to
10814       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10815       // constants.
10816       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10817         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10818           if (ASrcTy->getNumElements() != 0) {
10819             Value* Idxs[2];
10820             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10821             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10822             SrcTy = cast<PointerType>(CastOp->getType());
10823             SrcPTy = SrcTy->getElementType();
10824           }
10825
10826       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10827           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10828                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10829
10830         // Okay, we are casting from one integer or pointer type to another of
10831         // the same size.  Instead of casting the pointer before 
10832         // the store, cast the value to be stored.
10833         Value *NewCast;
10834         Value *SIOp0 = SI.getOperand(0);
10835         Instruction::CastOps opcode = Instruction::BitCast;
10836         const Type* CastSrcTy = SIOp0->getType();
10837         const Type* CastDstTy = SrcPTy;
10838         if (isa<PointerType>(CastDstTy)) {
10839           if (CastSrcTy->isInteger())
10840             opcode = Instruction::IntToPtr;
10841         } else if (isa<IntegerType>(CastDstTy)) {
10842           if (isa<PointerType>(SIOp0->getType()))
10843             opcode = Instruction::PtrToInt;
10844         }
10845         if (Constant *C = dyn_cast<Constant>(SIOp0))
10846           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10847         else
10848           NewCast = IC.InsertNewInstBefore(
10849             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10850             SI);
10851         return new StoreInst(NewCast, CastOp);
10852       }
10853     }
10854   }
10855   return 0;
10856 }
10857
10858 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10859   Value *Val = SI.getOperand(0);
10860   Value *Ptr = SI.getOperand(1);
10861
10862   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10863     EraseInstFromFunction(SI);
10864     ++NumCombined;
10865     return 0;
10866   }
10867   
10868   // If the RHS is an alloca with a single use, zapify the store, making the
10869   // alloca dead.
10870   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10871     if (isa<AllocaInst>(Ptr)) {
10872       EraseInstFromFunction(SI);
10873       ++NumCombined;
10874       return 0;
10875     }
10876     
10877     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10878       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10879           GEP->getOperand(0)->hasOneUse()) {
10880         EraseInstFromFunction(SI);
10881         ++NumCombined;
10882         return 0;
10883       }
10884   }
10885
10886   // Attempt to improve the alignment.
10887   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10888   if (KnownAlign >
10889       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10890                                 SI.getAlignment()))
10891     SI.setAlignment(KnownAlign);
10892
10893   // Do really simple DSE, to catch cases where there are several consequtive
10894   // stores to the same location, separated by a few arithmetic operations. This
10895   // situation often occurs with bitfield accesses.
10896   BasicBlock::iterator BBI = &SI;
10897   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10898        --ScanInsts) {
10899     --BBI;
10900     
10901     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10902       // Prev store isn't volatile, and stores to the same location?
10903       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10904         ++NumDeadStore;
10905         ++BBI;
10906         EraseInstFromFunction(*PrevSI);
10907         continue;
10908       }
10909       break;
10910     }
10911     
10912     // If this is a load, we have to stop.  However, if the loaded value is from
10913     // the pointer we're loading and is producing the pointer we're storing,
10914     // then *this* store is dead (X = load P; store X -> P).
10915     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10916       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10917         EraseInstFromFunction(SI);
10918         ++NumCombined;
10919         return 0;
10920       }
10921       // Otherwise, this is a load from some other location.  Stores before it
10922       // may not be dead.
10923       break;
10924     }
10925     
10926     // Don't skip over loads or things that can modify memory.
10927     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10928       break;
10929   }
10930   
10931   
10932   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10933
10934   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10935   if (isa<ConstantPointerNull>(Ptr)) {
10936     if (!isa<UndefValue>(Val)) {
10937       SI.setOperand(0, UndefValue::get(Val->getType()));
10938       if (Instruction *U = dyn_cast<Instruction>(Val))
10939         AddToWorkList(U);  // Dropped a use.
10940       ++NumCombined;
10941     }
10942     return 0;  // Do not modify these!
10943   }
10944
10945   // store undef, Ptr -> noop
10946   if (isa<UndefValue>(Val)) {
10947     EraseInstFromFunction(SI);
10948     ++NumCombined;
10949     return 0;
10950   }
10951
10952   // If the pointer destination is a cast, see if we can fold the cast into the
10953   // source instead.
10954   if (isa<CastInst>(Ptr))
10955     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10956       return Res;
10957   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10958     if (CE->isCast())
10959       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10960         return Res;
10961
10962   
10963   // If this store is the last instruction in the basic block, and if the block
10964   // ends with an unconditional branch, try to move it to the successor block.
10965   BBI = &SI; ++BBI;
10966   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10967     if (BI->isUnconditional())
10968       if (SimplifyStoreAtEndOfBlock(SI))
10969         return 0;  // xform done!
10970   
10971   return 0;
10972 }
10973
10974 /// SimplifyStoreAtEndOfBlock - Turn things like:
10975 ///   if () { *P = v1; } else { *P = v2 }
10976 /// into a phi node with a store in the successor.
10977 ///
10978 /// Simplify things like:
10979 ///   *P = v1; if () { *P = v2; }
10980 /// into a phi node with a store in the successor.
10981 ///
10982 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10983   BasicBlock *StoreBB = SI.getParent();
10984   
10985   // Check to see if the successor block has exactly two incoming edges.  If
10986   // so, see if the other predecessor contains a store to the same location.
10987   // if so, insert a PHI node (if needed) and move the stores down.
10988   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10989   
10990   // Determine whether Dest has exactly two predecessors and, if so, compute
10991   // the other predecessor.
10992   pred_iterator PI = pred_begin(DestBB);
10993   BasicBlock *OtherBB = 0;
10994   if (*PI != StoreBB)
10995     OtherBB = *PI;
10996   ++PI;
10997   if (PI == pred_end(DestBB))
10998     return false;
10999   
11000   if (*PI != StoreBB) {
11001     if (OtherBB)
11002       return false;
11003     OtherBB = *PI;
11004   }
11005   if (++PI != pred_end(DestBB))
11006     return false;
11007   
11008   
11009   // Verify that the other block ends in a branch and is not otherwise empty.
11010   BasicBlock::iterator BBI = OtherBB->getTerminator();
11011   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11012   if (!OtherBr || BBI == OtherBB->begin())
11013     return false;
11014   
11015   // If the other block ends in an unconditional branch, check for the 'if then
11016   // else' case.  there is an instruction before the branch.
11017   StoreInst *OtherStore = 0;
11018   if (OtherBr->isUnconditional()) {
11019     // If this isn't a store, or isn't a store to the same location, bail out.
11020     --BBI;
11021     OtherStore = dyn_cast<StoreInst>(BBI);
11022     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11023       return false;
11024   } else {
11025     // Otherwise, the other block ended with a conditional branch. If one of the
11026     // destinations is StoreBB, then we have the if/then case.
11027     if (OtherBr->getSuccessor(0) != StoreBB && 
11028         OtherBr->getSuccessor(1) != StoreBB)
11029       return false;
11030     
11031     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11032     // if/then triangle.  See if there is a store to the same ptr as SI that
11033     // lives in OtherBB.
11034     for (;; --BBI) {
11035       // Check to see if we find the matching store.
11036       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11037         if (OtherStore->getOperand(1) != SI.getOperand(1))
11038           return false;
11039         break;
11040       }
11041       // If we find something that may be using the stored value, or if we run
11042       // out of instructions, we can't do the xform.
11043       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11044           BBI == OtherBB->begin())
11045         return false;
11046     }
11047     
11048     // In order to eliminate the store in OtherBr, we have to
11049     // make sure nothing reads the stored value in StoreBB.
11050     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11051       // FIXME: This should really be AA driven.
11052       if (isa<LoadInst>(I) || I->mayWriteToMemory())
11053         return false;
11054     }
11055   }
11056   
11057   // Insert a PHI node now if we need it.
11058   Value *MergedVal = OtherStore->getOperand(0);
11059   if (MergedVal != SI.getOperand(0)) {
11060     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11061     PN->reserveOperandSpace(2);
11062     PN->addIncoming(SI.getOperand(0), SI.getParent());
11063     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11064     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11065   }
11066   
11067   // Advance to a place where it is safe to insert the new store and
11068   // insert it.
11069   BBI = DestBB->begin();
11070   while (isa<PHINode>(BBI)) ++BBI;
11071   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11072                                     OtherStore->isVolatile()), *BBI);
11073   
11074   // Nuke the old stores.
11075   EraseInstFromFunction(SI);
11076   EraseInstFromFunction(*OtherStore);
11077   ++NumCombined;
11078   return true;
11079 }
11080
11081
11082 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11083   // Change br (not X), label True, label False to: br X, label False, True
11084   Value *X = 0;
11085   BasicBlock *TrueDest;
11086   BasicBlock *FalseDest;
11087   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11088       !isa<Constant>(X)) {
11089     // Swap Destinations and condition...
11090     BI.setCondition(X);
11091     BI.setSuccessor(0, FalseDest);
11092     BI.setSuccessor(1, TrueDest);
11093     return &BI;
11094   }
11095
11096   // Cannonicalize fcmp_one -> fcmp_oeq
11097   FCmpInst::Predicate FPred; Value *Y;
11098   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11099                              TrueDest, FalseDest)))
11100     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11101          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11102       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11103       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11104       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11105       NewSCC->takeName(I);
11106       // Swap Destinations and condition...
11107       BI.setCondition(NewSCC);
11108       BI.setSuccessor(0, FalseDest);
11109       BI.setSuccessor(1, TrueDest);
11110       RemoveFromWorkList(I);
11111       I->eraseFromParent();
11112       AddToWorkList(NewSCC);
11113       return &BI;
11114     }
11115
11116   // Cannonicalize icmp_ne -> icmp_eq
11117   ICmpInst::Predicate IPred;
11118   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11119                       TrueDest, FalseDest)))
11120     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11121          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11122          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11123       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11124       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11125       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11126       NewSCC->takeName(I);
11127       // Swap Destinations and condition...
11128       BI.setCondition(NewSCC);
11129       BI.setSuccessor(0, FalseDest);
11130       BI.setSuccessor(1, TrueDest);
11131       RemoveFromWorkList(I);
11132       I->eraseFromParent();;
11133       AddToWorkList(NewSCC);
11134       return &BI;
11135     }
11136
11137   return 0;
11138 }
11139
11140 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11141   Value *Cond = SI.getCondition();
11142   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11143     if (I->getOpcode() == Instruction::Add)
11144       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11145         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11146         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11147           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11148                                                 AddRHS));
11149         SI.setOperand(0, I->getOperand(0));
11150         AddToWorkList(I);
11151         return &SI;
11152       }
11153   }
11154   return 0;
11155 }
11156
11157 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11158 /// is to leave as a vector operation.
11159 static bool CheapToScalarize(Value *V, bool isConstant) {
11160   if (isa<ConstantAggregateZero>(V)) 
11161     return true;
11162   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11163     if (isConstant) return true;
11164     // If all elts are the same, we can extract.
11165     Constant *Op0 = C->getOperand(0);
11166     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11167       if (C->getOperand(i) != Op0)
11168         return false;
11169     return true;
11170   }
11171   Instruction *I = dyn_cast<Instruction>(V);
11172   if (!I) return false;
11173   
11174   // Insert element gets simplified to the inserted element or is deleted if
11175   // this is constant idx extract element and its a constant idx insertelt.
11176   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11177       isa<ConstantInt>(I->getOperand(2)))
11178     return true;
11179   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11180     return true;
11181   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11182     if (BO->hasOneUse() &&
11183         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11184          CheapToScalarize(BO->getOperand(1), isConstant)))
11185       return true;
11186   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11187     if (CI->hasOneUse() &&
11188         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11189          CheapToScalarize(CI->getOperand(1), isConstant)))
11190       return true;
11191   
11192   return false;
11193 }
11194
11195 /// Read and decode a shufflevector mask.
11196 ///
11197 /// It turns undef elements into values that are larger than the number of
11198 /// elements in the input.
11199 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11200   unsigned NElts = SVI->getType()->getNumElements();
11201   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11202     return std::vector<unsigned>(NElts, 0);
11203   if (isa<UndefValue>(SVI->getOperand(2)))
11204     return std::vector<unsigned>(NElts, 2*NElts);
11205
11206   std::vector<unsigned> Result;
11207   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11208   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11209     if (isa<UndefValue>(CP->getOperand(i)))
11210       Result.push_back(NElts*2);  // undef -> 8
11211     else
11212       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
11213   return Result;
11214 }
11215
11216 /// FindScalarElement - Given a vector and an element number, see if the scalar
11217 /// value is already around as a register, for example if it were inserted then
11218 /// extracted from the vector.
11219 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11220   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11221   const VectorType *PTy = cast<VectorType>(V->getType());
11222   unsigned Width = PTy->getNumElements();
11223   if (EltNo >= Width)  // Out of range access.
11224     return UndefValue::get(PTy->getElementType());
11225   
11226   if (isa<UndefValue>(V))
11227     return UndefValue::get(PTy->getElementType());
11228   else if (isa<ConstantAggregateZero>(V))
11229     return Constant::getNullValue(PTy->getElementType());
11230   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11231     return CP->getOperand(EltNo);
11232   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11233     // If this is an insert to a variable element, we don't know what it is.
11234     if (!isa<ConstantInt>(III->getOperand(2))) 
11235       return 0;
11236     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11237     
11238     // If this is an insert to the element we are looking for, return the
11239     // inserted value.
11240     if (EltNo == IIElt) 
11241       return III->getOperand(1);
11242     
11243     // Otherwise, the insertelement doesn't modify the value, recurse on its
11244     // vector input.
11245     return FindScalarElement(III->getOperand(0), EltNo);
11246   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11247     unsigned InEl = getShuffleMask(SVI)[EltNo];
11248     if (InEl < Width)
11249       return FindScalarElement(SVI->getOperand(0), InEl);
11250     else if (InEl < Width*2)
11251       return FindScalarElement(SVI->getOperand(1), InEl - Width);
11252     else
11253       return UndefValue::get(PTy->getElementType());
11254   }
11255   
11256   // Otherwise, we don't know.
11257   return 0;
11258 }
11259
11260 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11261
11262   // If vector val is undef, replace extract with scalar undef.
11263   if (isa<UndefValue>(EI.getOperand(0)))
11264     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11265
11266   // If vector val is constant 0, replace extract with scalar 0.
11267   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11268     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11269   
11270   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11271     // If vector val is constant with uniform operands, replace EI
11272     // with that operand
11273     Constant *op0 = C->getOperand(0);
11274     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11275       if (C->getOperand(i) != op0) {
11276         op0 = 0; 
11277         break;
11278       }
11279     if (op0)
11280       return ReplaceInstUsesWith(EI, op0);
11281   }
11282   
11283   // If extracting a specified index from the vector, see if we can recursively
11284   // find a previously computed scalar that was inserted into the vector.
11285   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11286     unsigned IndexVal = IdxC->getZExtValue();
11287     unsigned VectorWidth = 
11288       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11289       
11290     // If this is extracting an invalid index, turn this into undef, to avoid
11291     // crashing the code below.
11292     if (IndexVal >= VectorWidth)
11293       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11294     
11295     // This instruction only demands the single element from the input vector.
11296     // If the input vector has a single use, simplify it based on this use
11297     // property.
11298     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11299       uint64_t UndefElts;
11300       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11301                                                 1 << IndexVal,
11302                                                 UndefElts)) {
11303         EI.setOperand(0, V);
11304         return &EI;
11305       }
11306     }
11307     
11308     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11309       return ReplaceInstUsesWith(EI, Elt);
11310     
11311     // If the this extractelement is directly using a bitcast from a vector of
11312     // the same number of elements, see if we can find the source element from
11313     // it.  In this case, we will end up needing to bitcast the scalars.
11314     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11315       if (const VectorType *VT = 
11316               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11317         if (VT->getNumElements() == VectorWidth)
11318           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11319             return new BitCastInst(Elt, EI.getType());
11320     }
11321   }
11322   
11323   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11324     if (I->hasOneUse()) {
11325       // Push extractelement into predecessor operation if legal and
11326       // profitable to do so
11327       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11328         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11329         if (CheapToScalarize(BO, isConstantElt)) {
11330           ExtractElementInst *newEI0 = 
11331             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11332                                    EI.getName()+".lhs");
11333           ExtractElementInst *newEI1 =
11334             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11335                                    EI.getName()+".rhs");
11336           InsertNewInstBefore(newEI0, EI);
11337           InsertNewInstBefore(newEI1, EI);
11338           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11339         }
11340       } else if (isa<LoadInst>(I)) {
11341         unsigned AS = 
11342           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11343         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11344                                          PointerType::get(EI.getType(), AS),EI);
11345         GetElementPtrInst *GEP =
11346           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11347         InsertNewInstBefore(GEP, EI);
11348         return new LoadInst(GEP);
11349       }
11350     }
11351     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11352       // Extracting the inserted element?
11353       if (IE->getOperand(2) == EI.getOperand(1))
11354         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11355       // If the inserted and extracted elements are constants, they must not
11356       // be the same value, extract from the pre-inserted value instead.
11357       if (isa<Constant>(IE->getOperand(2)) &&
11358           isa<Constant>(EI.getOperand(1))) {
11359         AddUsesToWorkList(EI);
11360         EI.setOperand(0, IE->getOperand(0));
11361         return &EI;
11362       }
11363     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11364       // If this is extracting an element from a shufflevector, figure out where
11365       // it came from and extract from the appropriate input element instead.
11366       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11367         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11368         Value *Src;
11369         if (SrcIdx < SVI->getType()->getNumElements())
11370           Src = SVI->getOperand(0);
11371         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11372           SrcIdx -= SVI->getType()->getNumElements();
11373           Src = SVI->getOperand(1);
11374         } else {
11375           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11376         }
11377         return new ExtractElementInst(Src, SrcIdx);
11378       }
11379     }
11380   }
11381   return 0;
11382 }
11383
11384 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11385 /// elements from either LHS or RHS, return the shuffle mask and true. 
11386 /// Otherwise, return false.
11387 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11388                                          std::vector<Constant*> &Mask) {
11389   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11390          "Invalid CollectSingleShuffleElements");
11391   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11392
11393   if (isa<UndefValue>(V)) {
11394     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11395     return true;
11396   } else if (V == LHS) {
11397     for (unsigned i = 0; i != NumElts; ++i)
11398       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11399     return true;
11400   } else if (V == RHS) {
11401     for (unsigned i = 0; i != NumElts; ++i)
11402       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11403     return true;
11404   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11405     // If this is an insert of an extract from some other vector, include it.
11406     Value *VecOp    = IEI->getOperand(0);
11407     Value *ScalarOp = IEI->getOperand(1);
11408     Value *IdxOp    = IEI->getOperand(2);
11409     
11410     if (!isa<ConstantInt>(IdxOp))
11411       return false;
11412     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11413     
11414     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11415       // Okay, we can handle this if the vector we are insertinting into is
11416       // transitively ok.
11417       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11418         // If so, update the mask to reflect the inserted undef.
11419         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11420         return true;
11421       }      
11422     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11423       if (isa<ConstantInt>(EI->getOperand(1)) &&
11424           EI->getOperand(0)->getType() == V->getType()) {
11425         unsigned ExtractedIdx =
11426           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11427         
11428         // This must be extracting from either LHS or RHS.
11429         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11430           // Okay, we can handle this if the vector we are insertinting into is
11431           // transitively ok.
11432           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11433             // If so, update the mask to reflect the inserted value.
11434             if (EI->getOperand(0) == LHS) {
11435               Mask[InsertedIdx & (NumElts-1)] = 
11436                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11437             } else {
11438               assert(EI->getOperand(0) == RHS);
11439               Mask[InsertedIdx & (NumElts-1)] = 
11440                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11441               
11442             }
11443             return true;
11444           }
11445         }
11446       }
11447     }
11448   }
11449   // TODO: Handle shufflevector here!
11450   
11451   return false;
11452 }
11453
11454 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11455 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11456 /// that computes V and the LHS value of the shuffle.
11457 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11458                                      Value *&RHS) {
11459   assert(isa<VectorType>(V->getType()) && 
11460          (RHS == 0 || V->getType() == RHS->getType()) &&
11461          "Invalid shuffle!");
11462   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11463
11464   if (isa<UndefValue>(V)) {
11465     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11466     return V;
11467   } else if (isa<ConstantAggregateZero>(V)) {
11468     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11469     return V;
11470   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11471     // If this is an insert of an extract from some other vector, include it.
11472     Value *VecOp    = IEI->getOperand(0);
11473     Value *ScalarOp = IEI->getOperand(1);
11474     Value *IdxOp    = IEI->getOperand(2);
11475     
11476     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11477       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11478           EI->getOperand(0)->getType() == V->getType()) {
11479         unsigned ExtractedIdx =
11480           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11481         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11482         
11483         // Either the extracted from or inserted into vector must be RHSVec,
11484         // otherwise we'd end up with a shuffle of three inputs.
11485         if (EI->getOperand(0) == RHS || RHS == 0) {
11486           RHS = EI->getOperand(0);
11487           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11488           Mask[InsertedIdx & (NumElts-1)] = 
11489             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11490           return V;
11491         }
11492         
11493         if (VecOp == RHS) {
11494           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11495           // Everything but the extracted element is replaced with the RHS.
11496           for (unsigned i = 0; i != NumElts; ++i) {
11497             if (i != InsertedIdx)
11498               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11499           }
11500           return V;
11501         }
11502         
11503         // If this insertelement is a chain that comes from exactly these two
11504         // vectors, return the vector and the effective shuffle.
11505         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11506           return EI->getOperand(0);
11507         
11508       }
11509     }
11510   }
11511   // TODO: Handle shufflevector here!
11512   
11513   // Otherwise, can't do anything fancy.  Return an identity vector.
11514   for (unsigned i = 0; i != NumElts; ++i)
11515     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11516   return V;
11517 }
11518
11519 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11520   Value *VecOp    = IE.getOperand(0);
11521   Value *ScalarOp = IE.getOperand(1);
11522   Value *IdxOp    = IE.getOperand(2);
11523   
11524   // Inserting an undef or into an undefined place, remove this.
11525   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11526     ReplaceInstUsesWith(IE, VecOp);
11527   
11528   // If the inserted element was extracted from some other vector, and if the 
11529   // indexes are constant, try to turn this into a shufflevector operation.
11530   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11531     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11532         EI->getOperand(0)->getType() == IE.getType()) {
11533       unsigned NumVectorElts = IE.getType()->getNumElements();
11534       unsigned ExtractedIdx =
11535         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11536       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11537       
11538       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11539         return ReplaceInstUsesWith(IE, VecOp);
11540       
11541       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11542         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11543       
11544       // If we are extracting a value from a vector, then inserting it right
11545       // back into the same place, just use the input vector.
11546       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11547         return ReplaceInstUsesWith(IE, VecOp);      
11548       
11549       // We could theoretically do this for ANY input.  However, doing so could
11550       // turn chains of insertelement instructions into a chain of shufflevector
11551       // instructions, and right now we do not merge shufflevectors.  As such,
11552       // only do this in a situation where it is clear that there is benefit.
11553       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11554         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11555         // the values of VecOp, except then one read from EIOp0.
11556         // Build a new shuffle mask.
11557         std::vector<Constant*> Mask;
11558         if (isa<UndefValue>(VecOp))
11559           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11560         else {
11561           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11562           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11563                                                        NumVectorElts));
11564         } 
11565         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11566         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11567                                      ConstantVector::get(Mask));
11568       }
11569       
11570       // If this insertelement isn't used by some other insertelement, turn it
11571       // (and any insertelements it points to), into one big shuffle.
11572       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11573         std::vector<Constant*> Mask;
11574         Value *RHS = 0;
11575         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11576         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11577         // We now have a shuffle of LHS, RHS, Mask.
11578         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11579       }
11580     }
11581   }
11582
11583   return 0;
11584 }
11585
11586
11587 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11588   Value *LHS = SVI.getOperand(0);
11589   Value *RHS = SVI.getOperand(1);
11590   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11591
11592   bool MadeChange = false;
11593   
11594   // Undefined shuffle mask -> undefined value.
11595   if (isa<UndefValue>(SVI.getOperand(2)))
11596     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11597   
11598   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11599   // the undef, change them to undefs.
11600   if (isa<UndefValue>(SVI.getOperand(1))) {
11601     // Scan to see if there are any references to the RHS.  If so, replace them
11602     // with undef element refs and set MadeChange to true.
11603     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11604       if (Mask[i] >= e && Mask[i] != 2*e) {
11605         Mask[i] = 2*e;
11606         MadeChange = true;
11607       }
11608     }
11609     
11610     if (MadeChange) {
11611       // Remap any references to RHS to use LHS.
11612       std::vector<Constant*> Elts;
11613       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11614         if (Mask[i] == 2*e)
11615           Elts.push_back(UndefValue::get(Type::Int32Ty));
11616         else
11617           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11618       }
11619       SVI.setOperand(2, ConstantVector::get(Elts));
11620     }
11621   }
11622   
11623   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11624   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11625   if (LHS == RHS || isa<UndefValue>(LHS)) {
11626     if (isa<UndefValue>(LHS) && LHS == RHS) {
11627       // shuffle(undef,undef,mask) -> undef.
11628       return ReplaceInstUsesWith(SVI, LHS);
11629     }
11630     
11631     // Remap any references to RHS to use LHS.
11632     std::vector<Constant*> Elts;
11633     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11634       if (Mask[i] >= 2*e)
11635         Elts.push_back(UndefValue::get(Type::Int32Ty));
11636       else {
11637         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11638             (Mask[i] <  e && isa<UndefValue>(LHS)))
11639           Mask[i] = 2*e;     // Turn into undef.
11640         else
11641           Mask[i] &= (e-1);  // Force to LHS.
11642         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11643       }
11644     }
11645     SVI.setOperand(0, SVI.getOperand(1));
11646     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11647     SVI.setOperand(2, ConstantVector::get(Elts));
11648     LHS = SVI.getOperand(0);
11649     RHS = SVI.getOperand(1);
11650     MadeChange = true;
11651   }
11652   
11653   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11654   bool isLHSID = true, isRHSID = true;
11655     
11656   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11657     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11658     // Is this an identity shuffle of the LHS value?
11659     isLHSID &= (Mask[i] == i);
11660       
11661     // Is this an identity shuffle of the RHS value?
11662     isRHSID &= (Mask[i]-e == i);
11663   }
11664
11665   // Eliminate identity shuffles.
11666   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11667   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11668   
11669   // If the LHS is a shufflevector itself, see if we can combine it with this
11670   // one without producing an unusual shuffle.  Here we are really conservative:
11671   // we are absolutely afraid of producing a shuffle mask not in the input
11672   // program, because the code gen may not be smart enough to turn a merged
11673   // shuffle into two specific shuffles: it may produce worse code.  As such,
11674   // we only merge two shuffles if the result is one of the two input shuffle
11675   // masks.  In this case, merging the shuffles just removes one instruction,
11676   // which we know is safe.  This is good for things like turning:
11677   // (splat(splat)) -> splat.
11678   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11679     if (isa<UndefValue>(RHS)) {
11680       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11681
11682       std::vector<unsigned> NewMask;
11683       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11684         if (Mask[i] >= 2*e)
11685           NewMask.push_back(2*e);
11686         else
11687           NewMask.push_back(LHSMask[Mask[i]]);
11688       
11689       // If the result mask is equal to the src shuffle or this shuffle mask, do
11690       // the replacement.
11691       if (NewMask == LHSMask || NewMask == Mask) {
11692         std::vector<Constant*> Elts;
11693         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11694           if (NewMask[i] >= e*2) {
11695             Elts.push_back(UndefValue::get(Type::Int32Ty));
11696           } else {
11697             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11698           }
11699         }
11700         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11701                                      LHSSVI->getOperand(1),
11702                                      ConstantVector::get(Elts));
11703       }
11704     }
11705   }
11706
11707   return MadeChange ? &SVI : 0;
11708 }
11709
11710
11711
11712
11713 /// TryToSinkInstruction - Try to move the specified instruction from its
11714 /// current block into the beginning of DestBlock, which can only happen if it's
11715 /// safe to move the instruction past all of the instructions between it and the
11716 /// end of its block.
11717 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11718   assert(I->hasOneUse() && "Invariants didn't hold!");
11719
11720   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11721   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11722     return false;
11723
11724   // Do not sink alloca instructions out of the entry block.
11725   if (isa<AllocaInst>(I) && I->getParent() ==
11726         &DestBlock->getParent()->getEntryBlock())
11727     return false;
11728
11729   // We can only sink load instructions if there is nothing between the load and
11730   // the end of block that could change the value.
11731   if (I->mayReadFromMemory()) {
11732     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11733          Scan != E; ++Scan)
11734       if (Scan->mayWriteToMemory())
11735         return false;
11736   }
11737
11738   BasicBlock::iterator InsertPos = DestBlock->begin();
11739   while (isa<PHINode>(InsertPos)) ++InsertPos;
11740
11741   I->moveBefore(InsertPos);
11742   ++NumSunkInst;
11743   return true;
11744 }
11745
11746
11747 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11748 /// all reachable code to the worklist.
11749 ///
11750 /// This has a couple of tricks to make the code faster and more powerful.  In
11751 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11752 /// them to the worklist (this significantly speeds up instcombine on code where
11753 /// many instructions are dead or constant).  Additionally, if we find a branch
11754 /// whose condition is a known constant, we only visit the reachable successors.
11755 ///
11756 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11757                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11758                                        InstCombiner &IC,
11759                                        const TargetData *TD) {
11760   std::vector<BasicBlock*> Worklist;
11761   Worklist.push_back(BB);
11762
11763   while (!Worklist.empty()) {
11764     BB = Worklist.back();
11765     Worklist.pop_back();
11766     
11767     // We have now visited this block!  If we've already been here, ignore it.
11768     if (!Visited.insert(BB)) continue;
11769     
11770     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11771       Instruction *Inst = BBI++;
11772       
11773       // DCE instruction if trivially dead.
11774       if (isInstructionTriviallyDead(Inst)) {
11775         ++NumDeadInst;
11776         DOUT << "IC: DCE: " << *Inst;
11777         Inst->eraseFromParent();
11778         continue;
11779       }
11780       
11781       // ConstantProp instruction if trivially constant.
11782       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11783         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11784         Inst->replaceAllUsesWith(C);
11785         ++NumConstProp;
11786         Inst->eraseFromParent();
11787         continue;
11788       }
11789      
11790       IC.AddToWorkList(Inst);
11791     }
11792
11793     // Recursively visit successors.  If this is a branch or switch on a
11794     // constant, only visit the reachable successor.
11795     TerminatorInst *TI = BB->getTerminator();
11796     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11797       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11798         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11799         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11800         Worklist.push_back(ReachableBB);
11801         continue;
11802       }
11803     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11804       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11805         // See if this is an explicit destination.
11806         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11807           if (SI->getCaseValue(i) == Cond) {
11808             BasicBlock *ReachableBB = SI->getSuccessor(i);
11809             Worklist.push_back(ReachableBB);
11810             continue;
11811           }
11812         
11813         // Otherwise it is the default destination.
11814         Worklist.push_back(SI->getSuccessor(0));
11815         continue;
11816       }
11817     }
11818     
11819     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11820       Worklist.push_back(TI->getSuccessor(i));
11821   }
11822 }
11823
11824 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11825   bool Changed = false;
11826   TD = &getAnalysis<TargetData>();
11827   
11828   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11829              << F.getNameStr() << "\n");
11830
11831   {
11832     // Do a depth-first traversal of the function, populate the worklist with
11833     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11834     // track of which blocks we visit.
11835     SmallPtrSet<BasicBlock*, 64> Visited;
11836     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11837
11838     // Do a quick scan over the function.  If we find any blocks that are
11839     // unreachable, remove any instructions inside of them.  This prevents
11840     // the instcombine code from having to deal with some bad special cases.
11841     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11842       if (!Visited.count(BB)) {
11843         Instruction *Term = BB->getTerminator();
11844         while (Term != BB->begin()) {   // Remove instrs bottom-up
11845           BasicBlock::iterator I = Term; --I;
11846
11847           DOUT << "IC: DCE: " << *I;
11848           ++NumDeadInst;
11849
11850           if (!I->use_empty())
11851             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11852           I->eraseFromParent();
11853         }
11854       }
11855   }
11856
11857   while (!Worklist.empty()) {
11858     Instruction *I = RemoveOneFromWorkList();
11859     if (I == 0) continue;  // skip null values.
11860
11861     // Check to see if we can DCE the instruction.
11862     if (isInstructionTriviallyDead(I)) {
11863       // Add operands to the worklist.
11864       if (I->getNumOperands() < 4)
11865         AddUsesToWorkList(*I);
11866       ++NumDeadInst;
11867
11868       DOUT << "IC: DCE: " << *I;
11869
11870       I->eraseFromParent();
11871       RemoveFromWorkList(I);
11872       continue;
11873     }
11874
11875     // Instruction isn't dead, see if we can constant propagate it.
11876     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11877       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11878
11879       // Add operands to the worklist.
11880       AddUsesToWorkList(*I);
11881       ReplaceInstUsesWith(*I, C);
11882
11883       ++NumConstProp;
11884       I->eraseFromParent();
11885       RemoveFromWorkList(I);
11886       continue;
11887     }
11888
11889     // See if we can trivially sink this instruction to a successor basic block.
11890     // FIXME: Remove GetResultInst test when first class support for aggregates
11891     // is implemented.
11892     if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11893       BasicBlock *BB = I->getParent();
11894       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11895       if (UserParent != BB) {
11896         bool UserIsSuccessor = false;
11897         // See if the user is one of our successors.
11898         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11899           if (*SI == UserParent) {
11900             UserIsSuccessor = true;
11901             break;
11902           }
11903
11904         // If the user is one of our immediate successors, and if that successor
11905         // only has us as a predecessors (we'd have to split the critical edge
11906         // otherwise), we can keep going.
11907         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11908             next(pred_begin(UserParent)) == pred_end(UserParent))
11909           // Okay, the CFG is simple enough, try to sink this instruction.
11910           Changed |= TryToSinkInstruction(I, UserParent);
11911       }
11912     }
11913
11914     // Now that we have an instruction, try combining it to simplify it...
11915 #ifndef NDEBUG
11916     std::string OrigI;
11917 #endif
11918     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11919     if (Instruction *Result = visit(*I)) {
11920       ++NumCombined;
11921       // Should we replace the old instruction with a new one?
11922       if (Result != I) {
11923         DOUT << "IC: Old = " << *I
11924              << "    New = " << *Result;
11925
11926         // Everything uses the new instruction now.
11927         I->replaceAllUsesWith(Result);
11928
11929         // Push the new instruction and any users onto the worklist.
11930         AddToWorkList(Result);
11931         AddUsersToWorkList(*Result);
11932
11933         // Move the name to the new instruction first.
11934         Result->takeName(I);
11935
11936         // Insert the new instruction into the basic block...
11937         BasicBlock *InstParent = I->getParent();
11938         BasicBlock::iterator InsertPos = I;
11939
11940         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11941           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11942             ++InsertPos;
11943
11944         InstParent->getInstList().insert(InsertPos, Result);
11945
11946         // Make sure that we reprocess all operands now that we reduced their
11947         // use counts.
11948         AddUsesToWorkList(*I);
11949
11950         // Instructions can end up on the worklist more than once.  Make sure
11951         // we do not process an instruction that has been deleted.
11952         RemoveFromWorkList(I);
11953
11954         // Erase the old instruction.
11955         InstParent->getInstList().erase(I);
11956       } else {
11957 #ifndef NDEBUG
11958         DOUT << "IC: Mod = " << OrigI
11959              << "    New = " << *I;
11960 #endif
11961
11962         // If the instruction was modified, it's possible that it is now dead.
11963         // if so, remove it.
11964         if (isInstructionTriviallyDead(I)) {
11965           // Make sure we process all operands now that we are reducing their
11966           // use counts.
11967           AddUsesToWorkList(*I);
11968
11969           // Instructions may end up in the worklist more than once.  Erase all
11970           // occurrences of this instruction.
11971           RemoveFromWorkList(I);
11972           I->eraseFromParent();
11973         } else {
11974           AddToWorkList(I);
11975           AddUsersToWorkList(*I);
11976         }
11977       }
11978       Changed = true;
11979     }
11980   }
11981
11982   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11983     
11984   // Do an explicit clear, this shrinks the map if needed.
11985   WorklistMap.clear();
11986   return Changed;
11987 }
11988
11989
11990 bool InstCombiner::runOnFunction(Function &F) {
11991   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11992   
11993   bool EverMadeChange = false;
11994
11995   // Iterate while there is work to do.
11996   unsigned Iteration = 0;
11997   while (DoOneIteration(F, Iteration++))
11998     EverMadeChange = true;
11999   return EverMadeChange;
12000 }
12001
12002 FunctionPass *llvm::createInstructionCombiningPass() {
12003   return new InstCombiner();
12004 }
12005