Fix PR2358 by resolving calls with undef arguments to overdefined.
[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         if (!LU)
1100           continue;
1101         unsigned Opcode = getOpcode(LU);
1102         // Check for operations that have the property that if
1103         // both their operands have low zero bits, the result
1104         // will have low zero bits.
1105         if (Opcode == Instruction::Add ||
1106             Opcode == Instruction::Sub ||
1107             Opcode == Instruction::And ||
1108             Opcode == Instruction::Or ||
1109             Opcode == Instruction::Mul) {
1110           Value *LL = LU->getOperand(0);
1111           Value *LR = LU->getOperand(1);
1112           // Find a recurrence.
1113           if (LL == I)
1114             L = LR;
1115           else if (LR == I)
1116             L = LL;
1117           else
1118             break;
1119           // Ok, we have a PHI of the form L op= R. Check for low
1120           // zero bits.
1121           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1122           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1123           Mask2 = APInt::getLowBitsSet(BitWidth,
1124                                        KnownZero2.countTrailingOnes());
1125           KnownOne2.clear();
1126           KnownZero2.clear();
1127           ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1128           KnownZero = Mask &
1129                       APInt::getLowBitsSet(BitWidth,
1130                                            KnownZero2.countTrailingOnes());
1131           break;
1132         }
1133       }
1134     }
1135     break;
1136   }
1137   case Instruction::Call:
1138     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1139       switch (II->getIntrinsicID()) {
1140       default: break;
1141       case Intrinsic::ctpop:
1142       case Intrinsic::ctlz:
1143       case Intrinsic::cttz: {
1144         unsigned LowBits = Log2_32(BitWidth)+1;
1145         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1146         break;
1147       }
1148       }
1149     }
1150     break;
1151   }
1152 }
1153
1154 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1155 /// this predicate to simplify operations downstream.  Mask is known to be zero
1156 /// for bits that V cannot have.
1157 bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1158                                      unsigned Depth) {
1159   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1160   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1161   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1162   return (KnownZero & Mask) == Mask;
1163 }
1164
1165 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
1166 /// specified instruction is a constant integer.  If so, check to see if there
1167 /// are any bits set in the constant that are not demanded.  If so, shrink the
1168 /// constant and return true.
1169 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
1170                                    APInt Demanded) {
1171   assert(I && "No instruction?");
1172   assert(OpNo < I->getNumOperands() && "Operand index too large");
1173
1174   // If the operand is not a constant integer, nothing to do.
1175   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1176   if (!OpC) return false;
1177
1178   // If there are no bits set that aren't demanded, nothing to do.
1179   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1180   if ((~Demanded & OpC->getValue()) == 0)
1181     return false;
1182
1183   // This instruction is producing bits that are not demanded. Shrink the RHS.
1184   Demanded &= OpC->getValue();
1185   I->setOperand(OpNo, ConstantInt::get(Demanded));
1186   return true;
1187 }
1188
1189 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
1190 // set of known zero and one bits, compute the maximum and minimum values that
1191 // could have the specified known zero and known one bits, returning them in
1192 // min/max.
1193 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1194                                                    const APInt& KnownZero,
1195                                                    const APInt& KnownOne,
1196                                                    APInt& Min, APInt& Max) {
1197   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1198   assert(KnownZero.getBitWidth() == BitWidth && 
1199          KnownOne.getBitWidth() == BitWidth &&
1200          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1201          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1202   APInt UnknownBits = ~(KnownZero|KnownOne);
1203
1204   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1205   // bit if it is unknown.
1206   Min = KnownOne;
1207   Max = KnownOne|UnknownBits;
1208   
1209   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1210     Min.set(BitWidth-1);
1211     Max.clear(BitWidth-1);
1212   }
1213 }
1214
1215 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1216 // a set of known zero and one bits, compute the maximum and minimum values that
1217 // could have the specified known zero and known one bits, returning them in
1218 // min/max.
1219 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1220                                                      const APInt &KnownZero,
1221                                                      const APInt &KnownOne,
1222                                                      APInt &Min, APInt &Max) {
1223   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
1224   assert(KnownZero.getBitWidth() == BitWidth && 
1225          KnownOne.getBitWidth() == BitWidth &&
1226          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1227          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1228   APInt UnknownBits = ~(KnownZero|KnownOne);
1229   
1230   // The minimum value is when the unknown bits are all zeros.
1231   Min = KnownOne;
1232   // The maximum value is when the unknown bits are all ones.
1233   Max = KnownOne|UnknownBits;
1234 }
1235
1236 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
1237 /// value based on the demanded bits. When this function is called, it is known
1238 /// that only the bits set in DemandedMask of the result of V are ever used
1239 /// downstream. Consequently, depending on the mask and V, it may be possible
1240 /// to replace V with a constant or one of its operands. In such cases, this
1241 /// function does the replacement and returns true. In all other cases, it
1242 /// returns false after analyzing the expression and setting KnownOne and known
1243 /// to be one in the expression. KnownZero contains all the bits that are known
1244 /// to be zero in the expression. These are provided to potentially allow the
1245 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1246 /// the expression. KnownOne and KnownZero always follow the invariant that 
1247 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1248 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
1249 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1250 /// and KnownOne must all be the same.
1251 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1252                                         APInt& KnownZero, APInt& KnownOne,
1253                                         unsigned Depth) {
1254   assert(V != 0 && "Null pointer of Value???");
1255   assert(Depth <= 6 && "Limit Search Depth");
1256   uint32_t BitWidth = DemandedMask.getBitWidth();
1257   const IntegerType *VTy = cast<IntegerType>(V->getType());
1258   assert(VTy->getBitWidth() == BitWidth && 
1259          KnownZero.getBitWidth() == BitWidth && 
1260          KnownOne.getBitWidth() == BitWidth &&
1261          "Value *V, DemandedMask, KnownZero and KnownOne \
1262           must have same BitWidth");
1263   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1264     // We know all of the bits for a constant!
1265     KnownOne = CI->getValue() & DemandedMask;
1266     KnownZero = ~KnownOne & DemandedMask;
1267     return false;
1268   }
1269   
1270   KnownZero.clear(); 
1271   KnownOne.clear();
1272   if (!V->hasOneUse()) {    // Other users may use these bits.
1273     if (Depth != 0) {       // Not at the root.
1274       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1275       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1276       return false;
1277     }
1278     // If this is the root being simplified, allow it to have multiple uses,
1279     // just set the DemandedMask to all bits.
1280     DemandedMask = APInt::getAllOnesValue(BitWidth);
1281   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
1282     if (V != UndefValue::get(VTy))
1283       return UpdateValueUsesWith(V, UndefValue::get(VTy));
1284     return false;
1285   } else if (Depth == 6) {        // Limit search depth.
1286     return false;
1287   }
1288   
1289   Instruction *I = dyn_cast<Instruction>(V);
1290   if (!I) return false;        // Only analyze instructions.
1291
1292   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1293   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1294   switch (I->getOpcode()) {
1295   default:
1296     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1297     break;
1298   case Instruction::And:
1299     // If either the LHS or the RHS are Zero, the result is zero.
1300     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1301                              RHSKnownZero, RHSKnownOne, Depth+1))
1302       return true;
1303     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1304            "Bits known to be one AND zero?"); 
1305
1306     // If something is known zero on the RHS, the bits aren't demanded on the
1307     // LHS.
1308     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1309                              LHSKnownZero, LHSKnownOne, Depth+1))
1310       return true;
1311     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1312            "Bits known to be one AND zero?"); 
1313
1314     // If all of the demanded bits are known 1 on one side, return the other.
1315     // These bits cannot contribute to the result of the 'and'.
1316     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1317         (DemandedMask & ~LHSKnownZero))
1318       return UpdateValueUsesWith(I, I->getOperand(0));
1319     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1320         (DemandedMask & ~RHSKnownZero))
1321       return UpdateValueUsesWith(I, I->getOperand(1));
1322     
1323     // If all of the demanded bits in the inputs are known zeros, return zero.
1324     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1325       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1326       
1327     // If the RHS is a constant, see if we can simplify it.
1328     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1329       return UpdateValueUsesWith(I, I);
1330       
1331     // Output known-1 bits are only known if set in both the LHS & RHS.
1332     RHSKnownOne &= LHSKnownOne;
1333     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1334     RHSKnownZero |= LHSKnownZero;
1335     break;
1336   case Instruction::Or:
1337     // If either the LHS or the RHS are One, the result is One.
1338     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1339                              RHSKnownZero, RHSKnownOne, Depth+1))
1340       return true;
1341     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1342            "Bits known to be one AND zero?"); 
1343     // If something is known one on the RHS, the bits aren't demanded on the
1344     // LHS.
1345     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1346                              LHSKnownZero, LHSKnownOne, Depth+1))
1347       return true;
1348     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1349            "Bits known to be one AND zero?"); 
1350     
1351     // If all of the demanded bits are known zero on one side, return the other.
1352     // These bits cannot contribute to the result of the 'or'.
1353     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1354         (DemandedMask & ~LHSKnownOne))
1355       return UpdateValueUsesWith(I, I->getOperand(0));
1356     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1357         (DemandedMask & ~RHSKnownOne))
1358       return UpdateValueUsesWith(I, I->getOperand(1));
1359
1360     // If all of the potentially set bits on one side are known to be set on
1361     // the other side, just use the 'other' side.
1362     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1363         (DemandedMask & (~RHSKnownZero)))
1364       return UpdateValueUsesWith(I, I->getOperand(0));
1365     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1366         (DemandedMask & (~LHSKnownZero)))
1367       return UpdateValueUsesWith(I, I->getOperand(1));
1368         
1369     // If the RHS is a constant, see if we can simplify it.
1370     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1371       return UpdateValueUsesWith(I, I);
1372           
1373     // Output known-0 bits are only known if clear in both the LHS & RHS.
1374     RHSKnownZero &= LHSKnownZero;
1375     // Output known-1 are known to be set if set in either the LHS | RHS.
1376     RHSKnownOne |= LHSKnownOne;
1377     break;
1378   case Instruction::Xor: {
1379     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1380                              RHSKnownZero, RHSKnownOne, Depth+1))
1381       return true;
1382     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1383            "Bits known to be one AND zero?"); 
1384     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1385                              LHSKnownZero, LHSKnownOne, Depth+1))
1386       return true;
1387     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1388            "Bits known to be one AND zero?"); 
1389     
1390     // If all of the demanded bits are known zero on one side, return the other.
1391     // These bits cannot contribute to the result of the 'xor'.
1392     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1393       return UpdateValueUsesWith(I, I->getOperand(0));
1394     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1395       return UpdateValueUsesWith(I, I->getOperand(1));
1396     
1397     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1398     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1399                          (RHSKnownOne & LHSKnownOne);
1400     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1401     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1402                         (RHSKnownOne & LHSKnownZero);
1403     
1404     // If all of the demanded bits are known to be zero on one side or the
1405     // other, turn this into an *inclusive* or.
1406     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1407     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1408       Instruction *Or =
1409         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1410                                  I->getName());
1411       InsertNewInstBefore(Or, *I);
1412       return UpdateValueUsesWith(I, Or);
1413     }
1414     
1415     // If all of the demanded bits on one side are known, and all of the set
1416     // bits on that side are also known to be set on the other side, turn this
1417     // into an AND, as we know the bits will be cleared.
1418     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1419     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1420       // all known
1421       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1422         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1423         Instruction *And = 
1424           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1425         InsertNewInstBefore(And, *I);
1426         return UpdateValueUsesWith(I, And);
1427       }
1428     }
1429     
1430     // If the RHS is a constant, see if we can simplify it.
1431     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1432     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1433       return UpdateValueUsesWith(I, I);
1434     
1435     RHSKnownZero = KnownZeroOut;
1436     RHSKnownOne  = KnownOneOut;
1437     break;
1438   }
1439   case Instruction::Select:
1440     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1441                              RHSKnownZero, RHSKnownOne, Depth+1))
1442       return true;
1443     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1444                              LHSKnownZero, LHSKnownOne, Depth+1))
1445       return true;
1446     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1447            "Bits known to be one AND zero?"); 
1448     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1449            "Bits known to be one AND zero?"); 
1450     
1451     // If the operands are constants, see if we can simplify them.
1452     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1453       return UpdateValueUsesWith(I, I);
1454     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1455       return UpdateValueUsesWith(I, I);
1456     
1457     // Only known if known in both the LHS and RHS.
1458     RHSKnownOne &= LHSKnownOne;
1459     RHSKnownZero &= LHSKnownZero;
1460     break;
1461   case Instruction::Trunc: {
1462     uint32_t truncBf = 
1463       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1464     DemandedMask.zext(truncBf);
1465     RHSKnownZero.zext(truncBf);
1466     RHSKnownOne.zext(truncBf);
1467     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1468                              RHSKnownZero, RHSKnownOne, Depth+1))
1469       return true;
1470     DemandedMask.trunc(BitWidth);
1471     RHSKnownZero.trunc(BitWidth);
1472     RHSKnownOne.trunc(BitWidth);
1473     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1474            "Bits known to be one AND zero?"); 
1475     break;
1476   }
1477   case Instruction::BitCast:
1478     if (!I->getOperand(0)->getType()->isInteger())
1479       return false;
1480       
1481     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1482                              RHSKnownZero, RHSKnownOne, Depth+1))
1483       return true;
1484     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1485            "Bits known to be one AND zero?"); 
1486     break;
1487   case Instruction::ZExt: {
1488     // Compute the bits in the result that are not present in the input.
1489     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1490     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1491     
1492     DemandedMask.trunc(SrcBitWidth);
1493     RHSKnownZero.trunc(SrcBitWidth);
1494     RHSKnownOne.trunc(SrcBitWidth);
1495     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1496                              RHSKnownZero, RHSKnownOne, Depth+1))
1497       return true;
1498     DemandedMask.zext(BitWidth);
1499     RHSKnownZero.zext(BitWidth);
1500     RHSKnownOne.zext(BitWidth);
1501     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1502            "Bits known to be one AND zero?"); 
1503     // The top bits are known to be zero.
1504     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1505     break;
1506   }
1507   case Instruction::SExt: {
1508     // Compute the bits in the result that are not present in the input.
1509     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1510     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1511     
1512     APInt InputDemandedBits = DemandedMask & 
1513                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1514
1515     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1516     // If any of the sign extended bits are demanded, we know that the sign
1517     // bit is demanded.
1518     if ((NewBits & DemandedMask) != 0)
1519       InputDemandedBits.set(SrcBitWidth-1);
1520       
1521     InputDemandedBits.trunc(SrcBitWidth);
1522     RHSKnownZero.trunc(SrcBitWidth);
1523     RHSKnownOne.trunc(SrcBitWidth);
1524     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1525                              RHSKnownZero, RHSKnownOne, Depth+1))
1526       return true;
1527     InputDemandedBits.zext(BitWidth);
1528     RHSKnownZero.zext(BitWidth);
1529     RHSKnownOne.zext(BitWidth);
1530     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1531            "Bits known to be one AND zero?"); 
1532       
1533     // If the sign bit of the input is known set or clear, then we know the
1534     // top bits of the result.
1535
1536     // If the input sign bit is known zero, or if the NewBits are not demanded
1537     // convert this into a zero extension.
1538     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1539     {
1540       // Convert to ZExt cast
1541       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1542       return UpdateValueUsesWith(I, NewCast);
1543     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1544       RHSKnownOne |= NewBits;
1545     }
1546     break;
1547   }
1548   case Instruction::Add: {
1549     // Figure out what the input bits are.  If the top bits of the and result
1550     // are not demanded, then the add doesn't demand them from its input
1551     // either.
1552     uint32_t NLZ = DemandedMask.countLeadingZeros();
1553       
1554     // If there is a constant on the RHS, there are a variety of xformations
1555     // we can do.
1556     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1557       // If null, this should be simplified elsewhere.  Some of the xforms here
1558       // won't work if the RHS is zero.
1559       if (RHS->isZero())
1560         break;
1561       
1562       // If the top bit of the output is demanded, demand everything from the
1563       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1564       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1565
1566       // Find information about known zero/one bits in the input.
1567       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1568                                LHSKnownZero, LHSKnownOne, Depth+1))
1569         return true;
1570
1571       // If the RHS of the add has bits set that can't affect the input, reduce
1572       // the constant.
1573       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1574         return UpdateValueUsesWith(I, I);
1575       
1576       // Avoid excess work.
1577       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1578         break;
1579       
1580       // Turn it into OR if input bits are zero.
1581       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1582         Instruction *Or =
1583           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1584                                    I->getName());
1585         InsertNewInstBefore(Or, *I);
1586         return UpdateValueUsesWith(I, Or);
1587       }
1588       
1589       // We can say something about the output known-zero and known-one bits,
1590       // depending on potential carries from the input constant and the
1591       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1592       // bits set and the RHS constant is 0x01001, then we know we have a known
1593       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1594       
1595       // To compute this, we first compute the potential carry bits.  These are
1596       // the bits which may be modified.  I'm not aware of a better way to do
1597       // this scan.
1598       const APInt& RHSVal = RHS->getValue();
1599       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1600       
1601       // Now that we know which bits have carries, compute the known-1/0 sets.
1602       
1603       // Bits are known one if they are known zero in one operand and one in the
1604       // other, and there is no input carry.
1605       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1606                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1607       
1608       // Bits are known zero if they are known zero in both operands and there
1609       // is no input carry.
1610       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1611     } else {
1612       // If the high-bits of this ADD are not demanded, then it does not demand
1613       // the high bits of its LHS or RHS.
1614       if (DemandedMask[BitWidth-1] == 0) {
1615         // Right fill the mask of bits for this ADD to demand the most
1616         // significant bit and all those below it.
1617         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1618         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1619                                  LHSKnownZero, LHSKnownOne, Depth+1))
1620           return true;
1621         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1622                                  LHSKnownZero, LHSKnownOne, Depth+1))
1623           return true;
1624       }
1625     }
1626     break;
1627   }
1628   case Instruction::Sub:
1629     // If the high-bits of this SUB are not demanded, then it does not demand
1630     // the high bits of its LHS or RHS.
1631     if (DemandedMask[BitWidth-1] == 0) {
1632       // Right fill the mask of bits for this SUB to demand the most
1633       // significant bit and all those below it.
1634       uint32_t NLZ = DemandedMask.countLeadingZeros();
1635       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1636       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1637                                LHSKnownZero, LHSKnownOne, Depth+1))
1638         return true;
1639       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1640                                LHSKnownZero, LHSKnownOne, Depth+1))
1641         return true;
1642     }
1643     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1644     // the known zeros and ones.
1645     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1646     break;
1647   case Instruction::Shl:
1648     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1649       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1650       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1651       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1652                                RHSKnownZero, RHSKnownOne, Depth+1))
1653         return true;
1654       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1655              "Bits known to be one AND zero?"); 
1656       RHSKnownZero <<= ShiftAmt;
1657       RHSKnownOne  <<= ShiftAmt;
1658       // low bits known zero.
1659       if (ShiftAmt)
1660         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1661     }
1662     break;
1663   case Instruction::LShr:
1664     // For a logical shift right
1665     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1666       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1667       
1668       // Unsigned shift right.
1669       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1670       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1671                                RHSKnownZero, RHSKnownOne, Depth+1))
1672         return true;
1673       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1674              "Bits known to be one AND zero?"); 
1675       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1676       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1677       if (ShiftAmt) {
1678         // Compute the new bits that are at the top now.
1679         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1680         RHSKnownZero |= HighBits;  // high bits known zero.
1681       }
1682     }
1683     break;
1684   case Instruction::AShr:
1685     // If this is an arithmetic shift right and only the low-bit is set, we can
1686     // always convert this into a logical shr, even if the shift amount is
1687     // variable.  The low bit of the shift cannot be an input sign bit unless
1688     // the shift amount is >= the size of the datatype, which is undefined.
1689     if (DemandedMask == 1) {
1690       // Perform the logical shift right.
1691       Value *NewVal = BinaryOperator::CreateLShr(
1692                         I->getOperand(0), I->getOperand(1), I->getName());
1693       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1694       return UpdateValueUsesWith(I, NewVal);
1695     }    
1696
1697     // If the sign bit is the only bit demanded by this ashr, then there is no
1698     // need to do it, the shift doesn't change the high bit.
1699     if (DemandedMask.isSignBit())
1700       return UpdateValueUsesWith(I, I->getOperand(0));
1701     
1702     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1703       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1704       
1705       // Signed shift right.
1706       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1707       // If any of the "high bits" are demanded, we should set the sign bit as
1708       // demanded.
1709       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1710         DemandedMaskIn.set(BitWidth-1);
1711       if (SimplifyDemandedBits(I->getOperand(0),
1712                                DemandedMaskIn,
1713                                RHSKnownZero, RHSKnownOne, Depth+1))
1714         return true;
1715       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1716              "Bits known to be one AND zero?"); 
1717       // Compute the new bits that are at the top now.
1718       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1719       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1720       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1721         
1722       // Handle the sign bits.
1723       APInt SignBit(APInt::getSignBit(BitWidth));
1724       // Adjust to where it is now in the mask.
1725       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1726         
1727       // If the input sign bit is known to be zero, or if none of the top bits
1728       // are demanded, turn this into an unsigned shift right.
1729       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1730           (HighBits & ~DemandedMask) == HighBits) {
1731         // Perform the logical shift right.
1732         Value *NewVal = BinaryOperator::CreateLShr(
1733                           I->getOperand(0), SA, I->getName());
1734         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1735         return UpdateValueUsesWith(I, NewVal);
1736       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1737         RHSKnownOne |= HighBits;
1738       }
1739     }
1740     break;
1741   case Instruction::SRem:
1742     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1743       APInt RA = Rem->getValue();
1744       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1745         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1746         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1747         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1748                                  LHSKnownZero, LHSKnownOne, Depth+1))
1749           return true;
1750
1751         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1752           LHSKnownZero |= ~LowBits;
1753         else if (LHSKnownOne[BitWidth-1])
1754           LHSKnownOne |= ~LowBits;
1755
1756         KnownZero |= LHSKnownZero & DemandedMask;
1757         KnownOne |= LHSKnownOne & DemandedMask;
1758
1759         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1760       }
1761     }
1762     break;
1763   case Instruction::URem: {
1764     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1765       APInt RA = Rem->getValue();
1766       if (RA.isPowerOf2()) {
1767         APInt LowBits = (RA - 1);
1768         APInt Mask2 = LowBits & DemandedMask;
1769         KnownZero |= ~LowBits & DemandedMask;
1770         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1771                                  KnownZero, KnownOne, Depth+1))
1772           return true;
1773
1774         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1775         break;
1776       }
1777     }
1778
1779     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1780     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1781     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1782                              KnownZero2, KnownOne2, Depth+1))
1783       return true;
1784
1785     uint32_t Leaders = KnownZero2.countLeadingOnes();
1786     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1787                              KnownZero2, KnownOne2, Depth+1))
1788       return true;
1789
1790     Leaders = std::max(Leaders,
1791                        KnownZero2.countLeadingOnes());
1792     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1793     break;
1794   }
1795   }
1796   
1797   // If the client is only demanding bits that we know, return the known
1798   // constant.
1799   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1800     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1801   return false;
1802 }
1803
1804
1805 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1806 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1807 /// actually used by the caller.  This method analyzes which elements of the
1808 /// operand are undef and returns that information in UndefElts.
1809 ///
1810 /// If the information about demanded elements can be used to simplify the
1811 /// operation, the operation is simplified, then the resultant value is
1812 /// returned.  This returns null if no change was made.
1813 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1814                                                 uint64_t &UndefElts,
1815                                                 unsigned Depth) {
1816   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1817   assert(VWidth <= 64 && "Vector too wide to analyze!");
1818   uint64_t EltMask = ~0ULL >> (64-VWidth);
1819   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1820          "Invalid DemandedElts!");
1821
1822   if (isa<UndefValue>(V)) {
1823     // If the entire vector is undefined, just return this info.
1824     UndefElts = EltMask;
1825     return 0;
1826   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1827     UndefElts = EltMask;
1828     return UndefValue::get(V->getType());
1829   }
1830   
1831   UndefElts = 0;
1832   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1833     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1834     Constant *Undef = UndefValue::get(EltTy);
1835
1836     std::vector<Constant*> Elts;
1837     for (unsigned i = 0; i != VWidth; ++i)
1838       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1839         Elts.push_back(Undef);
1840         UndefElts |= (1ULL << i);
1841       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1842         Elts.push_back(Undef);
1843         UndefElts |= (1ULL << i);
1844       } else {                               // Otherwise, defined.
1845         Elts.push_back(CP->getOperand(i));
1846       }
1847         
1848     // If we changed the constant, return it.
1849     Constant *NewCP = ConstantVector::get(Elts);
1850     return NewCP != CP ? NewCP : 0;
1851   } else if (isa<ConstantAggregateZero>(V)) {
1852     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1853     // set to undef.
1854     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1855     Constant *Zero = Constant::getNullValue(EltTy);
1856     Constant *Undef = UndefValue::get(EltTy);
1857     std::vector<Constant*> Elts;
1858     for (unsigned i = 0; i != VWidth; ++i)
1859       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1860     UndefElts = DemandedElts ^ EltMask;
1861     return ConstantVector::get(Elts);
1862   }
1863   
1864   if (!V->hasOneUse()) {    // Other users may use these bits.
1865     if (Depth != 0) {       // Not at the root.
1866       // TODO: Just compute the UndefElts information recursively.
1867       return false;
1868     }
1869     return false;
1870   } else if (Depth == 10) {        // Limit search depth.
1871     return false;
1872   }
1873   
1874   Instruction *I = dyn_cast<Instruction>(V);
1875   if (!I) return false;        // Only analyze instructions.
1876   
1877   bool MadeChange = false;
1878   uint64_t UndefElts2;
1879   Value *TmpV;
1880   switch (I->getOpcode()) {
1881   default: break;
1882     
1883   case Instruction::InsertElement: {
1884     // If this is a variable index, we don't know which element it overwrites.
1885     // demand exactly the same input as we produce.
1886     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1887     if (Idx == 0) {
1888       // Note that we can't propagate undef elt info, because we don't know
1889       // which elt is getting updated.
1890       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1891                                         UndefElts2, Depth+1);
1892       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1893       break;
1894     }
1895     
1896     // If this is inserting an element that isn't demanded, remove this
1897     // insertelement.
1898     unsigned IdxNo = Idx->getZExtValue();
1899     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1900       return AddSoonDeadInstToWorklist(*I, 0);
1901     
1902     // Otherwise, the element inserted overwrites whatever was there, so the
1903     // input demanded set is simpler than the output set.
1904     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1905                                       DemandedElts & ~(1ULL << IdxNo),
1906                                       UndefElts, Depth+1);
1907     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1908
1909     // The inserted element is defined.
1910     UndefElts |= 1ULL << IdxNo;
1911     break;
1912   }
1913   case Instruction::BitCast: {
1914     // Vector->vector casts only.
1915     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1916     if (!VTy) break;
1917     unsigned InVWidth = VTy->getNumElements();
1918     uint64_t InputDemandedElts = 0;
1919     unsigned Ratio;
1920
1921     if (VWidth == InVWidth) {
1922       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1923       // elements as are demanded of us.
1924       Ratio = 1;
1925       InputDemandedElts = DemandedElts;
1926     } else if (VWidth > InVWidth) {
1927       // Untested so far.
1928       break;
1929       
1930       // If there are more elements in the result than there are in the source,
1931       // then an input element is live if any of the corresponding output
1932       // elements are live.
1933       Ratio = VWidth/InVWidth;
1934       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1935         if (DemandedElts & (1ULL << OutIdx))
1936           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1937       }
1938     } else {
1939       // Untested so far.
1940       break;
1941       
1942       // If there are more elements in the source than there are in the result,
1943       // then an input element is live if the corresponding output element is
1944       // live.
1945       Ratio = InVWidth/VWidth;
1946       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1947         if (DemandedElts & (1ULL << InIdx/Ratio))
1948           InputDemandedElts |= 1ULL << InIdx;
1949     }
1950     
1951     // div/rem demand all inputs, because they don't want divide by zero.
1952     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1953                                       UndefElts2, Depth+1);
1954     if (TmpV) {
1955       I->setOperand(0, TmpV);
1956       MadeChange = true;
1957     }
1958     
1959     UndefElts = UndefElts2;
1960     if (VWidth > InVWidth) {
1961       assert(0 && "Unimp");
1962       // If there are more elements in the result than there are in the source,
1963       // then an output element is undef if the corresponding input element is
1964       // undef.
1965       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1966         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1967           UndefElts |= 1ULL << OutIdx;
1968     } else if (VWidth < InVWidth) {
1969       assert(0 && "Unimp");
1970       // If there are more elements in the source than there are in the result,
1971       // then a result element is undef if all of the corresponding input
1972       // elements are undef.
1973       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1974       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1975         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1976           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1977     }
1978     break;
1979   }
1980   case Instruction::And:
1981   case Instruction::Or:
1982   case Instruction::Xor:
1983   case Instruction::Add:
1984   case Instruction::Sub:
1985   case Instruction::Mul:
1986     // div/rem demand all inputs, because they don't want divide by zero.
1987     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1988                                       UndefElts, Depth+1);
1989     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1990     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1991                                       UndefElts2, Depth+1);
1992     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1993       
1994     // Output elements are undefined if both are undefined.  Consider things
1995     // like undef&0.  The result is known zero, not undef.
1996     UndefElts &= UndefElts2;
1997     break;
1998     
1999   case Instruction::Call: {
2000     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2001     if (!II) break;
2002     switch (II->getIntrinsicID()) {
2003     default: break;
2004       
2005     // Binary vector operations that work column-wise.  A dest element is a
2006     // function of the corresponding input elements from the two inputs.
2007     case Intrinsic::x86_sse_sub_ss:
2008     case Intrinsic::x86_sse_mul_ss:
2009     case Intrinsic::x86_sse_min_ss:
2010     case Intrinsic::x86_sse_max_ss:
2011     case Intrinsic::x86_sse2_sub_sd:
2012     case Intrinsic::x86_sse2_mul_sd:
2013     case Intrinsic::x86_sse2_min_sd:
2014     case Intrinsic::x86_sse2_max_sd:
2015       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2016                                         UndefElts, Depth+1);
2017       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2018       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2019                                         UndefElts2, Depth+1);
2020       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2021
2022       // If only the low elt is demanded and this is a scalarizable intrinsic,
2023       // scalarize it now.
2024       if (DemandedElts == 1) {
2025         switch (II->getIntrinsicID()) {
2026         default: break;
2027         case Intrinsic::x86_sse_sub_ss:
2028         case Intrinsic::x86_sse_mul_ss:
2029         case Intrinsic::x86_sse2_sub_sd:
2030         case Intrinsic::x86_sse2_mul_sd:
2031           // TODO: Lower MIN/MAX/ABS/etc
2032           Value *LHS = II->getOperand(1);
2033           Value *RHS = II->getOperand(2);
2034           // Extract the element as scalars.
2035           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2036           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2037           
2038           switch (II->getIntrinsicID()) {
2039           default: assert(0 && "Case stmts out of sync!");
2040           case Intrinsic::x86_sse_sub_ss:
2041           case Intrinsic::x86_sse2_sub_sd:
2042             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
2043                                                         II->getName()), *II);
2044             break;
2045           case Intrinsic::x86_sse_mul_ss:
2046           case Intrinsic::x86_sse2_mul_sd:
2047             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
2048                                                          II->getName()), *II);
2049             break;
2050           }
2051           
2052           Instruction *New =
2053             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2054                                       II->getName());
2055           InsertNewInstBefore(New, *II);
2056           AddSoonDeadInstToWorklist(*II, 0);
2057           return New;
2058         }            
2059       }
2060         
2061       // Output elements are undefined if both are undefined.  Consider things
2062       // like undef&0.  The result is known zero, not undef.
2063       UndefElts &= UndefElts2;
2064       break;
2065     }
2066     break;
2067   }
2068   }
2069   return MadeChange ? I : 0;
2070 }
2071
2072 /// ComputeNumSignBits - Return the number of times the sign bit of the
2073 /// register is replicated into the other bits.  We know that at least 1 bit
2074 /// is always equal to the sign bit (itself), but other cases can give us
2075 /// information.  For example, immediately after an "ashr X, 2", we know that
2076 /// the top 3 bits are all equal to each other, so we return 3.
2077 ///
2078 unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2079   const IntegerType *Ty = cast<IntegerType>(V->getType());
2080   unsigned TyBits = Ty->getBitWidth();
2081   unsigned Tmp, Tmp2;
2082   unsigned FirstAnswer = 1;
2083
2084   if (Depth == 6)
2085     return 1;  // Limit search depth.
2086
2087   User *U = dyn_cast<User>(V);
2088   switch (getOpcode(V)) {
2089   default: break;
2090   case Instruction::SExt:
2091     Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2092     return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2093     
2094   case Instruction::AShr:
2095     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2096     // ashr X, C   -> adds C sign bits.
2097     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2098       Tmp += C->getZExtValue();
2099       if (Tmp > TyBits) Tmp = TyBits;
2100     }
2101     return Tmp;
2102   case Instruction::Shl:
2103     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2104       // shl destroys sign bits.
2105       Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2106       if (C->getZExtValue() >= TyBits ||      // Bad shift.
2107           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
2108       return Tmp - C->getZExtValue();
2109     }
2110     break;
2111   case Instruction::And:
2112   case Instruction::Or:
2113   case Instruction::Xor:    // NOT is handled here.
2114     // Logical binary ops preserve the number of sign bits at the worst.
2115     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2116     if (Tmp != 1) {
2117       Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2118       FirstAnswer = std::min(Tmp, Tmp2);
2119       // We computed what we know about the sign bits as our first
2120       // answer. Now proceed to the generic code that uses
2121       // ComputeMaskedBits, and pick whichever answer is better.
2122     }
2123     break;
2124
2125   case Instruction::Select:
2126     Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
2127     if (Tmp == 1) return 1;  // Early out.
2128     Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
2129     return std::min(Tmp, Tmp2);
2130     
2131   case Instruction::Add:
2132     // Add can have at most one carry bit.  Thus we know that the output
2133     // is, at worst, one more bit than the inputs.
2134     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2135     if (Tmp == 1) return 1;  // Early out.
2136       
2137     // Special case decrementing a value (ADD X, -1):
2138     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2139       if (CRHS->isAllOnesValue()) {
2140         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2141         APInt Mask = APInt::getAllOnesValue(TyBits);
2142         ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2143         
2144         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2145         // sign bits set.
2146         if ((KnownZero | APInt(TyBits, 1)) == Mask)
2147           return TyBits;
2148         
2149         // If we are subtracting one from a positive number, there is no carry
2150         // out of the result.
2151         if (KnownZero.isNegative())
2152           return Tmp;
2153       }
2154       
2155     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2156     if (Tmp2 == 1) return 1;
2157       return std::min(Tmp, Tmp2)-1;
2158     break;
2159     
2160   case Instruction::Sub:
2161     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2162     if (Tmp2 == 1) return 1;
2163       
2164     // Handle NEG.
2165     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2166       if (CLHS->isNullValue()) {
2167         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2168         APInt Mask = APInt::getAllOnesValue(TyBits);
2169         ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2170         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2171         // sign bits set.
2172         if ((KnownZero | APInt(TyBits, 1)) == Mask)
2173           return TyBits;
2174         
2175         // If the input is known to be positive (the sign bit is known clear),
2176         // the output of the NEG has the same number of sign bits as the input.
2177         if (KnownZero.isNegative())
2178           return Tmp2;
2179         
2180         // Otherwise, we treat this like a SUB.
2181       }
2182     
2183     // Sub can have at most one carry bit.  Thus we know that the output
2184     // is, at worst, one more bit than the inputs.
2185     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2186     if (Tmp == 1) return 1;  // Early out.
2187       return std::min(Tmp, Tmp2)-1;
2188     break;
2189   case Instruction::Trunc:
2190     // FIXME: it's tricky to do anything useful for this, but it is an important
2191     // case for targets like X86.
2192     break;
2193   }
2194   
2195   // Finally, if we can prove that the top bits of the result are 0's or 1's,
2196   // use this information.
2197   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2198   APInt Mask = APInt::getAllOnesValue(TyBits);
2199   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2200   
2201   if (KnownZero.isNegative()) {        // sign bit is 0
2202     Mask = KnownZero;
2203   } else if (KnownOne.isNegative()) {  // sign bit is 1;
2204     Mask = KnownOne;
2205   } else {
2206     // Nothing known.
2207     return FirstAnswer;
2208   }
2209   
2210   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
2211   // the number of identical bits in the top of the input value.
2212   Mask = ~Mask;
2213   Mask <<= Mask.getBitWidth()-TyBits;
2214   // Return # leading zeros.  We use 'min' here in case Val was zero before
2215   // shifting.  We don't want to return '64' as for an i32 "0".
2216   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2217 }
2218
2219
2220 /// AssociativeOpt - Perform an optimization on an associative operator.  This
2221 /// function is designed to check a chain of associative operators for a
2222 /// potential to apply a certain optimization.  Since the optimization may be
2223 /// applicable if the expression was reassociated, this checks the chain, then
2224 /// reassociates the expression as necessary to expose the optimization
2225 /// opportunity.  This makes use of a special Functor, which must define
2226 /// 'shouldApply' and 'apply' methods.
2227 ///
2228 template<typename Functor>
2229 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2230   unsigned Opcode = Root.getOpcode();
2231   Value *LHS = Root.getOperand(0);
2232
2233   // Quick check, see if the immediate LHS matches...
2234   if (F.shouldApply(LHS))
2235     return F.apply(Root);
2236
2237   // Otherwise, if the LHS is not of the same opcode as the root, return.
2238   Instruction *LHSI = dyn_cast<Instruction>(LHS);
2239   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2240     // Should we apply this transform to the RHS?
2241     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2242
2243     // If not to the RHS, check to see if we should apply to the LHS...
2244     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2245       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
2246       ShouldApply = true;
2247     }
2248
2249     // If the functor wants to apply the optimization to the RHS of LHSI,
2250     // reassociate the expression from ((? op A) op B) to (? op (A op B))
2251     if (ShouldApply) {
2252       BasicBlock *BB = Root.getParent();
2253
2254       // Now all of the instructions are in the current basic block, go ahead
2255       // and perform the reassociation.
2256       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2257
2258       // First move the selected RHS to the LHS of the root...
2259       Root.setOperand(0, LHSI->getOperand(1));
2260
2261       // Make what used to be the LHS of the root be the user of the root...
2262       Value *ExtraOperand = TmpLHSI->getOperand(1);
2263       if (&Root == TmpLHSI) {
2264         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2265         return 0;
2266       }
2267       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
2268       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
2269       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2270       BasicBlock::iterator ARI = &Root; ++ARI;
2271       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
2272       ARI = Root;
2273
2274       // Now propagate the ExtraOperand down the chain of instructions until we
2275       // get to LHSI.
2276       while (TmpLHSI != LHSI) {
2277         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2278         // Move the instruction to immediately before the chain we are
2279         // constructing to avoid breaking dominance properties.
2280         NextLHSI->getParent()->getInstList().remove(NextLHSI);
2281         BB->getInstList().insert(ARI, NextLHSI);
2282         ARI = NextLHSI;
2283
2284         Value *NextOp = NextLHSI->getOperand(1);
2285         NextLHSI->setOperand(1, ExtraOperand);
2286         TmpLHSI = NextLHSI;
2287         ExtraOperand = NextOp;
2288       }
2289
2290       // Now that the instructions are reassociated, have the functor perform
2291       // the transformation...
2292       return F.apply(Root);
2293     }
2294
2295     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2296   }
2297   return 0;
2298 }
2299
2300 namespace {
2301
2302 // AddRHS - Implements: X + X --> X << 1
2303 struct AddRHS {
2304   Value *RHS;
2305   AddRHS(Value *rhs) : RHS(rhs) {}
2306   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2307   Instruction *apply(BinaryOperator &Add) const {
2308     return BinaryOperator::CreateShl(Add.getOperand(0),
2309                                      ConstantInt::get(Add.getType(), 1));
2310   }
2311 };
2312
2313 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2314 //                 iff C1&C2 == 0
2315 struct AddMaskingAnd {
2316   Constant *C2;
2317   AddMaskingAnd(Constant *c) : C2(c) {}
2318   bool shouldApply(Value *LHS) const {
2319     ConstantInt *C1;
2320     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2321            ConstantExpr::getAnd(C1, C2)->isNullValue();
2322   }
2323   Instruction *apply(BinaryOperator &Add) const {
2324     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
2325   }
2326 };
2327
2328 }
2329
2330 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2331                                              InstCombiner *IC) {
2332   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2333     if (Constant *SOC = dyn_cast<Constant>(SO))
2334       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2335
2336     return IC->InsertNewInstBefore(CastInst::Create(
2337           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2338   }
2339
2340   // Figure out if the constant is the left or the right argument.
2341   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2342   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2343
2344   if (Constant *SOC = dyn_cast<Constant>(SO)) {
2345     if (ConstIsRHS)
2346       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2347     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2348   }
2349
2350   Value *Op0 = SO, *Op1 = ConstOperand;
2351   if (!ConstIsRHS)
2352     std::swap(Op0, Op1);
2353   Instruction *New;
2354   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2355     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
2356   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2357     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
2358                           SO->getName()+".cmp");
2359   else {
2360     assert(0 && "Unknown binary instruction type!");
2361     abort();
2362   }
2363   return IC->InsertNewInstBefore(New, I);
2364 }
2365
2366 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2367 // constant as the other operand, try to fold the binary operator into the
2368 // select arguments.  This also works for Cast instructions, which obviously do
2369 // not have a second operand.
2370 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2371                                      InstCombiner *IC) {
2372   // Don't modify shared select instructions
2373   if (!SI->hasOneUse()) return 0;
2374   Value *TV = SI->getOperand(1);
2375   Value *FV = SI->getOperand(2);
2376
2377   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2378     // Bool selects with constant operands can be folded to logical ops.
2379     if (SI->getType() == Type::Int1Ty) return 0;
2380
2381     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2382     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2383
2384     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2385                               SelectFalseVal);
2386   }
2387   return 0;
2388 }
2389
2390
2391 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2392 /// node as operand #0, see if we can fold the instruction into the PHI (which
2393 /// is only possible if all operands to the PHI are constants).
2394 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2395   PHINode *PN = cast<PHINode>(I.getOperand(0));
2396   unsigned NumPHIValues = PN->getNumIncomingValues();
2397   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2398
2399   // Check to see if all of the operands of the PHI are constants.  If there is
2400   // one non-constant value, remember the BB it is.  If there is more than one
2401   // or if *it* is a PHI, bail out.
2402   BasicBlock *NonConstBB = 0;
2403   for (unsigned i = 0; i != NumPHIValues; ++i)
2404     if (!isa<Constant>(PN->getIncomingValue(i))) {
2405       if (NonConstBB) return 0;  // More than one non-const value.
2406       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2407       NonConstBB = PN->getIncomingBlock(i);
2408       
2409       // If the incoming non-constant value is in I's block, we have an infinite
2410       // loop.
2411       if (NonConstBB == I.getParent())
2412         return 0;
2413     }
2414   
2415   // If there is exactly one non-constant value, we can insert a copy of the
2416   // operation in that block.  However, if this is a critical edge, we would be
2417   // inserting the computation one some other paths (e.g. inside a loop).  Only
2418   // do this if the pred block is unconditionally branching into the phi block.
2419   if (NonConstBB) {
2420     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2421     if (!BI || !BI->isUnconditional()) return 0;
2422   }
2423
2424   // Okay, we can do the transformation: create the new PHI node.
2425   PHINode *NewPN = PHINode::Create(I.getType(), "");
2426   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2427   InsertNewInstBefore(NewPN, *PN);
2428   NewPN->takeName(PN);
2429
2430   // Next, add all of the operands to the PHI.
2431   if (I.getNumOperands() == 2) {
2432     Constant *C = cast<Constant>(I.getOperand(1));
2433     for (unsigned i = 0; i != NumPHIValues; ++i) {
2434       Value *InV = 0;
2435       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2436         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2437           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2438         else
2439           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2440       } else {
2441         assert(PN->getIncomingBlock(i) == NonConstBB);
2442         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2443           InV = BinaryOperator::Create(BO->getOpcode(),
2444                                        PN->getIncomingValue(i), C, "phitmp",
2445                                        NonConstBB->getTerminator());
2446         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2447           InV = CmpInst::Create(CI->getOpcode(), 
2448                                 CI->getPredicate(),
2449                                 PN->getIncomingValue(i), C, "phitmp",
2450                                 NonConstBB->getTerminator());
2451         else
2452           assert(0 && "Unknown binop!");
2453         
2454         AddToWorkList(cast<Instruction>(InV));
2455       }
2456       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2457     }
2458   } else { 
2459     CastInst *CI = cast<CastInst>(&I);
2460     const Type *RetTy = CI->getType();
2461     for (unsigned i = 0; i != NumPHIValues; ++i) {
2462       Value *InV;
2463       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2464         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2465       } else {
2466         assert(PN->getIncomingBlock(i) == NonConstBB);
2467         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2468                                I.getType(), "phitmp", 
2469                                NonConstBB->getTerminator());
2470         AddToWorkList(cast<Instruction>(InV));
2471       }
2472       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2473     }
2474   }
2475   return ReplaceInstUsesWith(I, NewPN);
2476 }
2477
2478
2479 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
2480 /// value is never equal to -0.0.
2481 ///
2482 /// Note that this function will need to be revisited when we support nondefault
2483 /// rounding modes!
2484 ///
2485 static bool CannotBeNegativeZero(const Value *V) {
2486   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2487     return !CFP->getValueAPF().isNegZero();
2488
2489   if (const Instruction *I = dyn_cast<Instruction>(V)) {
2490     // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2491     if (I->getOpcode() == Instruction::Add &&
2492         isa<ConstantFP>(I->getOperand(1)) && 
2493         cast<ConstantFP>(I->getOperand(1))->isNullValue())
2494       return true;
2495     
2496     // sitofp and uitofp turn into +0.0 for zero.
2497     if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2498       return true;
2499     
2500     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2501       if (II->getIntrinsicID() == Intrinsic::sqrt)
2502         return CannotBeNegativeZero(II->getOperand(1));
2503     
2504     if (const CallInst *CI = dyn_cast<CallInst>(I))
2505       if (const Function *F = CI->getCalledFunction()) {
2506         if (F->isDeclaration()) {
2507           switch (F->getNameLen()) {
2508           case 3:  // abs(x) != -0.0
2509             if (!strcmp(F->getNameStart(), "abs")) return true;
2510             break;
2511           case 4:  // abs[lf](x) != -0.0
2512             if (!strcmp(F->getNameStart(), "absf")) return true;
2513             if (!strcmp(F->getNameStart(), "absl")) return true;
2514             break;
2515           }
2516         }
2517       }
2518   }
2519   
2520   return false;
2521 }
2522
2523 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2524 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2525 /// This basically requires proving that the add in the original type would not
2526 /// overflow to change the sign bit or have a carry out.
2527 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2528   // There are different heuristics we can use for this.  Here are some simple
2529   // ones.
2530   
2531   // Add has the property that adding any two 2's complement numbers can only 
2532   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2533   // have at least two sign bits, we know that the addition of the two values will
2534   // sign extend fine.
2535   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2536     return true;
2537   
2538   
2539   // If one of the operands only has one non-zero bit, and if the other operand
2540   // has a known-zero bit in a more significant place than it (not including the
2541   // sign bit) the ripple may go up to and fill the zero, but won't change the
2542   // sign.  For example, (X & ~4) + 1.
2543   
2544   // TODO: Implement.
2545   
2546   return false;
2547 }
2548
2549
2550 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2551   bool Changed = SimplifyCommutative(I);
2552   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2553
2554   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2555     // X + undef -> undef
2556     if (isa<UndefValue>(RHS))
2557       return ReplaceInstUsesWith(I, RHS);
2558
2559     // X + 0 --> X
2560     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2561       if (RHSC->isNullValue())
2562         return ReplaceInstUsesWith(I, LHS);
2563     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2564       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2565                               (I.getType())->getValueAPF()))
2566         return ReplaceInstUsesWith(I, LHS);
2567     }
2568
2569     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2570       // X + (signbit) --> X ^ signbit
2571       const APInt& Val = CI->getValue();
2572       uint32_t BitWidth = Val.getBitWidth();
2573       if (Val == APInt::getSignBit(BitWidth))
2574         return BinaryOperator::CreateXor(LHS, RHS);
2575       
2576       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2577       // (X & 254)+1 -> (X&254)|1
2578       if (!isa<VectorType>(I.getType())) {
2579         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2580         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2581                                  KnownZero, KnownOne))
2582           return &I;
2583       }
2584     }
2585
2586     if (isa<PHINode>(LHS))
2587       if (Instruction *NV = FoldOpIntoPhi(I))
2588         return NV;
2589     
2590     ConstantInt *XorRHS = 0;
2591     Value *XorLHS = 0;
2592     if (isa<ConstantInt>(RHSC) &&
2593         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2594       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2595       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2596       
2597       uint32_t Size = TySizeBits / 2;
2598       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2599       APInt CFF80Val(-C0080Val);
2600       do {
2601         if (TySizeBits > Size) {
2602           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2603           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2604           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2605               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2606             // This is a sign extend if the top bits are known zero.
2607             if (!MaskedValueIsZero(XorLHS, 
2608                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2609               Size = 0;  // Not a sign ext, but can't be any others either.
2610             break;
2611           }
2612         }
2613         Size >>= 1;
2614         C0080Val = APIntOps::lshr(C0080Val, Size);
2615         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2616       } while (Size >= 1);
2617       
2618       // FIXME: This shouldn't be necessary. When the backends can handle types
2619       // with funny bit widths then this switch statement should be removed. It
2620       // is just here to get the size of the "middle" type back up to something
2621       // that the back ends can handle.
2622       const Type *MiddleType = 0;
2623       switch (Size) {
2624         default: break;
2625         case 32: MiddleType = Type::Int32Ty; break;
2626         case 16: MiddleType = Type::Int16Ty; break;
2627         case  8: MiddleType = Type::Int8Ty; break;
2628       }
2629       if (MiddleType) {
2630         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2631         InsertNewInstBefore(NewTrunc, I);
2632         return new SExtInst(NewTrunc, I.getType(), I.getName());
2633       }
2634     }
2635   }
2636
2637   // X + X --> X << 1
2638   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2639     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2640
2641     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2642       if (RHSI->getOpcode() == Instruction::Sub)
2643         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2644           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2645     }
2646     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2647       if (LHSI->getOpcode() == Instruction::Sub)
2648         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2649           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2650     }
2651   }
2652
2653   // -A + B  -->  B - A
2654   // -A + -B  -->  -(A + B)
2655   if (Value *LHSV = dyn_castNegVal(LHS)) {
2656     if (LHS->getType()->isIntOrIntVector()) {
2657       if (Value *RHSV = dyn_castNegVal(RHS)) {
2658         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2659         InsertNewInstBefore(NewAdd, I);
2660         return BinaryOperator::CreateNeg(NewAdd);
2661       }
2662     }
2663     
2664     return BinaryOperator::CreateSub(RHS, LHSV);
2665   }
2666
2667   // A + -B  -->  A - B
2668   if (!isa<Constant>(RHS))
2669     if (Value *V = dyn_castNegVal(RHS))
2670       return BinaryOperator::CreateSub(LHS, V);
2671
2672
2673   ConstantInt *C2;
2674   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2675     if (X == RHS)   // X*C + X --> X * (C+1)
2676       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2677
2678     // X*C1 + X*C2 --> X * (C1+C2)
2679     ConstantInt *C1;
2680     if (X == dyn_castFoldableMul(RHS, C1))
2681       return BinaryOperator::CreateMul(X, Add(C1, C2));
2682   }
2683
2684   // X + X*C --> X * (C+1)
2685   if (dyn_castFoldableMul(RHS, C2) == LHS)
2686     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2687
2688   // X + ~X --> -1   since   ~X = -X-1
2689   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2690     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2691   
2692
2693   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2694   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2695     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2696       return R;
2697   
2698   // A+B --> A|B iff A and B have no bits set in common.
2699   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2700     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2701     APInt LHSKnownOne(IT->getBitWidth(), 0);
2702     APInt LHSKnownZero(IT->getBitWidth(), 0);
2703     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2704     if (LHSKnownZero != 0) {
2705       APInt RHSKnownOne(IT->getBitWidth(), 0);
2706       APInt RHSKnownZero(IT->getBitWidth(), 0);
2707       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2708       
2709       // No bits in common -> bitwise or.
2710       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2711         return BinaryOperator::CreateOr(LHS, RHS);
2712     }
2713   }
2714
2715   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2716   if (I.getType()->isIntOrIntVector()) {
2717     Value *W, *X, *Y, *Z;
2718     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2719         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2720       if (W != Y) {
2721         if (W == Z) {
2722           std::swap(Y, Z);
2723         } else if (Y == X) {
2724           std::swap(W, X);
2725         } else if (X == Z) {
2726           std::swap(Y, Z);
2727           std::swap(W, X);
2728         }
2729       }
2730
2731       if (W == Y) {
2732         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2733                                                             LHS->getName()), I);
2734         return BinaryOperator::CreateMul(W, NewAdd);
2735       }
2736     }
2737   }
2738
2739   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2740     Value *X = 0;
2741     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2742       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2743
2744     // (X & FF00) + xx00  -> (X+xx00) & FF00
2745     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2746       Constant *Anded = And(CRHS, C2);
2747       if (Anded == CRHS) {
2748         // See if all bits from the first bit set in the Add RHS up are included
2749         // in the mask.  First, get the rightmost bit.
2750         const APInt& AddRHSV = CRHS->getValue();
2751
2752         // Form a mask of all bits from the lowest bit added through the top.
2753         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2754
2755         // See if the and mask includes all of these bits.
2756         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2757
2758         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2759           // Okay, the xform is safe.  Insert the new add pronto.
2760           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2761                                                             LHS->getName()), I);
2762           return BinaryOperator::CreateAnd(NewAdd, C2);
2763         }
2764       }
2765     }
2766
2767     // Try to fold constant add into select arguments.
2768     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2769       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2770         return R;
2771   }
2772
2773   // add (cast *A to intptrtype) B -> 
2774   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2775   {
2776     CastInst *CI = dyn_cast<CastInst>(LHS);
2777     Value *Other = RHS;
2778     if (!CI) {
2779       CI = dyn_cast<CastInst>(RHS);
2780       Other = LHS;
2781     }
2782     if (CI && CI->getType()->isSized() && 
2783         (CI->getType()->getPrimitiveSizeInBits() == 
2784          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2785         && isa<PointerType>(CI->getOperand(0)->getType())) {
2786       unsigned AS =
2787         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2788       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2789                                       PointerType::get(Type::Int8Ty, AS), I);
2790       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2791       return new PtrToIntInst(I2, CI->getType());
2792     }
2793   }
2794   
2795   // add (select X 0 (sub n A)) A  -->  select X A n
2796   {
2797     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2798     Value *Other = RHS;
2799     if (!SI) {
2800       SI = dyn_cast<SelectInst>(RHS);
2801       Other = LHS;
2802     }
2803     if (SI && SI->hasOneUse()) {
2804       Value *TV = SI->getTrueValue();
2805       Value *FV = SI->getFalseValue();
2806       Value *A, *N;
2807
2808       // Can we fold the add into the argument of the select?
2809       // We check both true and false select arguments for a matching subtract.
2810       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2811           A == Other)  // Fold the add into the true select value.
2812         return SelectInst::Create(SI->getCondition(), N, A);
2813       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2814           A == Other)  // Fold the add into the false select value.
2815         return SelectInst::Create(SI->getCondition(), A, N);
2816     }
2817   }
2818   
2819   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2820   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2821     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2822       return ReplaceInstUsesWith(I, LHS);
2823
2824   // Check for (add (sext x), y), see if we can merge this into an
2825   // integer add followed by a sext.
2826   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2827     // (add (sext x), cst) --> (sext (add x, cst'))
2828     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2829       Constant *CI = 
2830         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2831       if (LHSConv->hasOneUse() &&
2832           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2833           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2834         // Insert the new, smaller add.
2835         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2836                                                         CI, "addconv");
2837         InsertNewInstBefore(NewAdd, I);
2838         return new SExtInst(NewAdd, I.getType());
2839       }
2840     }
2841     
2842     // (add (sext x), (sext y)) --> (sext (add int x, y))
2843     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2844       // Only do this if x/y have the same type, if at last one of them has a
2845       // single use (so we don't increase the number of sexts), and if the
2846       // integer add will not overflow.
2847       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2848           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2849           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2850                                    RHSConv->getOperand(0))) {
2851         // Insert the new integer add.
2852         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2853                                                         RHSConv->getOperand(0),
2854                                                         "addconv");
2855         InsertNewInstBefore(NewAdd, I);
2856         return new SExtInst(NewAdd, I.getType());
2857       }
2858     }
2859   }
2860   
2861   // Check for (add double (sitofp x), y), see if we can merge this into an
2862   // integer add followed by a promotion.
2863   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2864     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2865     // ... if the constant fits in the integer value.  This is useful for things
2866     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2867     // requires a constant pool load, and generally allows the add to be better
2868     // instcombined.
2869     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2870       Constant *CI = 
2871       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2872       if (LHSConv->hasOneUse() &&
2873           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2874           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2875         // Insert the new integer add.
2876         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2877                                                         CI, "addconv");
2878         InsertNewInstBefore(NewAdd, I);
2879         return new SIToFPInst(NewAdd, I.getType());
2880       }
2881     }
2882     
2883     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2884     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2885       // Only do this if x/y have the same type, if at last one of them has a
2886       // single use (so we don't increase the number of int->fp conversions),
2887       // and if the integer add will not overflow.
2888       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2889           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2890           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2891                                    RHSConv->getOperand(0))) {
2892         // Insert the new integer add.
2893         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2894                                                         RHSConv->getOperand(0),
2895                                                         "addconv");
2896         InsertNewInstBefore(NewAdd, I);
2897         return new SIToFPInst(NewAdd, I.getType());
2898       }
2899     }
2900   }
2901   
2902   return Changed ? &I : 0;
2903 }
2904
2905 // isSignBit - Return true if the value represented by the constant only has the
2906 // highest order bit set.
2907 static bool isSignBit(ConstantInt *CI) {
2908   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2909   return CI->getValue() == APInt::getSignBit(NumBits);
2910 }
2911
2912 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2913   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2914
2915   if (Op0 == Op1)         // sub X, X  -> 0
2916     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2917
2918   // If this is a 'B = x-(-A)', change to B = x+A...
2919   if (Value *V = dyn_castNegVal(Op1))
2920     return BinaryOperator::CreateAdd(Op0, V);
2921
2922   if (isa<UndefValue>(Op0))
2923     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2924   if (isa<UndefValue>(Op1))
2925     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2926
2927   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2928     // Replace (-1 - A) with (~A)...
2929     if (C->isAllOnesValue())
2930       return BinaryOperator::CreateNot(Op1);
2931
2932     // C - ~X == X + (1+C)
2933     Value *X = 0;
2934     if (match(Op1, m_Not(m_Value(X))))
2935       return BinaryOperator::CreateAdd(X, AddOne(C));
2936
2937     // -(X >>u 31) -> (X >>s 31)
2938     // -(X >>s 31) -> (X >>u 31)
2939     if (C->isZero()) {
2940       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2941         if (SI->getOpcode() == Instruction::LShr) {
2942           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2943             // Check to see if we are shifting out everything but the sign bit.
2944             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2945                 SI->getType()->getPrimitiveSizeInBits()-1) {
2946               // Ok, the transformation is safe.  Insert AShr.
2947               return BinaryOperator::Create(Instruction::AShr, 
2948                                           SI->getOperand(0), CU, SI->getName());
2949             }
2950           }
2951         }
2952         else if (SI->getOpcode() == Instruction::AShr) {
2953           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2954             // Check to see if we are shifting out everything but the sign bit.
2955             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2956                 SI->getType()->getPrimitiveSizeInBits()-1) {
2957               // Ok, the transformation is safe.  Insert LShr. 
2958               return BinaryOperator::CreateLShr(
2959                                           SI->getOperand(0), CU, SI->getName());
2960             }
2961           }
2962         }
2963       }
2964     }
2965
2966     // Try to fold constant sub into select arguments.
2967     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2968       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2969         return R;
2970
2971     if (isa<PHINode>(Op0))
2972       if (Instruction *NV = FoldOpIntoPhi(I))
2973         return NV;
2974   }
2975
2976   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2977     if (Op1I->getOpcode() == Instruction::Add &&
2978         !Op0->getType()->isFPOrFPVector()) {
2979       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2980         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2981       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2982         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2983       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2984         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2985           // C1-(X+C2) --> (C1-C2)-X
2986           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2987                                            Op1I->getOperand(0));
2988       }
2989     }
2990
2991     if (Op1I->hasOneUse()) {
2992       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2993       // is not used by anyone else...
2994       //
2995       if (Op1I->getOpcode() == Instruction::Sub &&
2996           !Op1I->getType()->isFPOrFPVector()) {
2997         // Swap the two operands of the subexpr...
2998         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2999         Op1I->setOperand(0, IIOp1);
3000         Op1I->setOperand(1, IIOp0);
3001
3002         // Create the new top level add instruction...
3003         return BinaryOperator::CreateAdd(Op0, Op1);
3004       }
3005
3006       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3007       //
3008       if (Op1I->getOpcode() == Instruction::And &&
3009           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3010         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3011
3012         Value *NewNot =
3013           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3014         return BinaryOperator::CreateAnd(Op0, NewNot);
3015       }
3016
3017       // 0 - (X sdiv C)  -> (X sdiv -C)
3018       if (Op1I->getOpcode() == Instruction::SDiv)
3019         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3020           if (CSI->isZero())
3021             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
3022               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
3023                                                ConstantExpr::getNeg(DivRHS));
3024
3025       // X - X*C --> X * (1-C)
3026       ConstantInt *C2 = 0;
3027       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
3028         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
3029         return BinaryOperator::CreateMul(Op0, CP1);
3030       }
3031
3032       // X - ((X / Y) * Y) --> X % Y
3033       if (Op1I->getOpcode() == Instruction::Mul)
3034         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3035           if (Op0 == I->getOperand(0) &&
3036               Op1I->getOperand(1) == I->getOperand(1)) {
3037             if (I->getOpcode() == Instruction::SDiv)
3038               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
3039             if (I->getOpcode() == Instruction::UDiv)
3040               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
3041           }
3042     }
3043   }
3044
3045   if (!Op0->getType()->isFPOrFPVector())
3046     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3047       if (Op0I->getOpcode() == Instruction::Add) {
3048         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
3049           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3050         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
3051           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3052       } else if (Op0I->getOpcode() == Instruction::Sub) {
3053         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
3054           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
3055       }
3056     }
3057
3058   ConstantInt *C1;
3059   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
3060     if (X == Op1)  // X*C - X --> X * (C-1)
3061       return BinaryOperator::CreateMul(Op1, SubOne(C1));
3062
3063     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
3064     if (X == dyn_castFoldableMul(Op1, C2))
3065       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
3066   }
3067   return 0;
3068 }
3069
3070 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
3071 /// comparison only checks the sign bit.  If it only checks the sign bit, set
3072 /// TrueIfSigned if the result of the comparison is true when the input value is
3073 /// signed.
3074 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3075                            bool &TrueIfSigned) {
3076   switch (pred) {
3077   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
3078     TrueIfSigned = true;
3079     return RHS->isZero();
3080   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
3081     TrueIfSigned = true;
3082     return RHS->isAllOnesValue();
3083   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
3084     TrueIfSigned = false;
3085     return RHS->isAllOnesValue();
3086   case ICmpInst::ICMP_UGT:
3087     // True if LHS u> RHS and RHS == high-bit-mask - 1
3088     TrueIfSigned = true;
3089     return RHS->getValue() ==
3090       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3091   case ICmpInst::ICMP_UGE: 
3092     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3093     TrueIfSigned = true;
3094     return RHS->getValue() == 
3095       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
3096   default:
3097     return false;
3098   }
3099 }
3100
3101 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3102   bool Changed = SimplifyCommutative(I);
3103   Value *Op0 = I.getOperand(0);
3104
3105   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
3106     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3107
3108   // Simplify mul instructions with a constant RHS...
3109   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3110     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3111
3112       // ((X << C1)*C2) == (X * (C2 << C1))
3113       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3114         if (SI->getOpcode() == Instruction::Shl)
3115           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
3116             return BinaryOperator::CreateMul(SI->getOperand(0),
3117                                              ConstantExpr::getShl(CI, ShOp));
3118
3119       if (CI->isZero())
3120         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
3121       if (CI->equalsInt(1))                  // X * 1  == X
3122         return ReplaceInstUsesWith(I, Op0);
3123       if (CI->isAllOnesValue())              // X * -1 == 0 - X
3124         return BinaryOperator::CreateNeg(Op0, I.getName());
3125
3126       const APInt& Val = cast<ConstantInt>(CI)->getValue();
3127       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
3128         return BinaryOperator::CreateShl(Op0,
3129                  ConstantInt::get(Op0->getType(), Val.logBase2()));
3130       }
3131     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
3132       if (Op1F->isNullValue())
3133         return ReplaceInstUsesWith(I, Op1);
3134
3135       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
3136       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3137       // We need a better interface for long double here.
3138       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3139         if (Op1F->isExactlyValue(1.0))
3140           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
3141     }
3142     
3143     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3144       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
3145           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
3146         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
3147         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
3148                                                      Op1, "tmp");
3149         InsertNewInstBefore(Add, I);
3150         Value *C1C2 = ConstantExpr::getMul(Op1, 
3151                                            cast<Constant>(Op0I->getOperand(1)));
3152         return BinaryOperator::CreateAdd(Add, C1C2);
3153         
3154       }
3155
3156     // Try to fold constant mul into select arguments.
3157     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3158       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3159         return R;
3160
3161     if (isa<PHINode>(Op0))
3162       if (Instruction *NV = FoldOpIntoPhi(I))
3163         return NV;
3164   }
3165
3166   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3167     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
3168       return BinaryOperator::CreateMul(Op0v, Op1v);
3169
3170   // If one of the operands of the multiply is a cast from a boolean value, then
3171   // we know the bool is either zero or one, so this is a 'masking' multiply.
3172   // See if we can simplify things based on how the boolean was originally
3173   // formed.
3174   CastInst *BoolCast = 0;
3175   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
3176     if (CI->getOperand(0)->getType() == Type::Int1Ty)
3177       BoolCast = CI;
3178   if (!BoolCast)
3179     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
3180       if (CI->getOperand(0)->getType() == Type::Int1Ty)
3181         BoolCast = CI;
3182   if (BoolCast) {
3183     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
3184       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3185       const Type *SCOpTy = SCIOp0->getType();
3186       bool TIS = false;
3187       
3188       // If the icmp is true iff the sign bit of X is set, then convert this
3189       // multiply into a shift/and combination.
3190       if (isa<ConstantInt>(SCIOp1) &&
3191           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3192           TIS) {
3193         // Shift the X value right to turn it into "all signbits".
3194         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
3195                                           SCOpTy->getPrimitiveSizeInBits()-1);
3196         Value *V =
3197           InsertNewInstBefore(
3198             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
3199                                             BoolCast->getOperand(0)->getName()+
3200                                             ".mask"), I);
3201
3202         // If the multiply type is not the same as the source type, sign extend
3203         // or truncate to the multiply type.
3204         if (I.getType() != V->getType()) {
3205           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3206           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
3207           Instruction::CastOps opcode = 
3208             (SrcBits == DstBits ? Instruction::BitCast : 
3209              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3210           V = InsertCastBefore(opcode, V, I.getType(), I);
3211         }
3212
3213         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
3214         return BinaryOperator::CreateAnd(V, OtherOp);
3215       }
3216     }
3217   }
3218
3219   return Changed ? &I : 0;
3220 }
3221
3222 /// This function implements the transforms on div instructions that work
3223 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3224 /// used by the visitors to those instructions.
3225 /// @brief Transforms common to all three div instructions
3226 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3227   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3228
3229   // undef / X -> 0        for integer.
3230   // undef / X -> undef    for FP (the undef could be a snan).
3231   if (isa<UndefValue>(Op0)) {
3232     if (Op0->getType()->isFPOrFPVector())
3233       return ReplaceInstUsesWith(I, Op0);
3234     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3235   }
3236
3237   // X / undef -> undef
3238   if (isa<UndefValue>(Op1))
3239     return ReplaceInstUsesWith(I, Op1);
3240
3241   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3242   // This does not apply for fdiv.
3243   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3244     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
3245     // the same basic block, then we replace the select with Y, and the
3246     // condition of the select with false (if the cond value is in the same BB).
3247     // If the select has uses other than the div, this allows them to be
3248     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3249     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
3250       if (ST->isNullValue()) {
3251         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3252         if (CondI && CondI->getParent() == I.getParent())
3253           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3254         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3255           I.setOperand(1, SI->getOperand(2));
3256         else
3257           UpdateValueUsesWith(SI, SI->getOperand(2));
3258         return &I;
3259       }
3260
3261     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3262     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
3263       if (ST->isNullValue()) {
3264         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3265         if (CondI && CondI->getParent() == I.getParent())
3266           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3267         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3268           I.setOperand(1, SI->getOperand(1));
3269         else
3270           UpdateValueUsesWith(SI, SI->getOperand(1));
3271         return &I;
3272       }
3273   }
3274
3275   return 0;
3276 }
3277
3278 /// This function implements the transforms common to both integer division
3279 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3280 /// division instructions.
3281 /// @brief Common integer divide transforms
3282 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3283   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3284
3285   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3286   if (Op0 == Op1) {
3287     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3288       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
3289       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3290       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3291     }
3292
3293     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
3294     return ReplaceInstUsesWith(I, CI);
3295   }
3296   
3297   if (Instruction *Common = commonDivTransforms(I))
3298     return Common;
3299
3300   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3301     // div X, 1 == X
3302     if (RHS->equalsInt(1))
3303       return ReplaceInstUsesWith(I, Op0);
3304
3305     // (X / C1) / C2  -> X / (C1*C2)
3306     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3307       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3308         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3309           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3310             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3311           else 
3312             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3313                                           Multiply(RHS, LHSRHS));
3314         }
3315
3316     if (!RHS->isZero()) { // avoid X udiv 0
3317       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3318         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3319           return R;
3320       if (isa<PHINode>(Op0))
3321         if (Instruction *NV = FoldOpIntoPhi(I))
3322           return NV;
3323     }
3324   }
3325
3326   // 0 / X == 0, we don't need to preserve faults!
3327   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3328     if (LHS->equalsInt(0))
3329       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3330
3331   return 0;
3332 }
3333
3334 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3335   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3336
3337   // Handle the integer div common cases
3338   if (Instruction *Common = commonIDivTransforms(I))
3339     return Common;
3340
3341   // X udiv C^2 -> X >> C
3342   // Check to see if this is an unsigned division with an exact power of 2,
3343   // if so, convert to a right shift.
3344   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3345     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3346       return BinaryOperator::CreateLShr(Op0, 
3347                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3348   }
3349
3350   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3351   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3352     if (RHSI->getOpcode() == Instruction::Shl &&
3353         isa<ConstantInt>(RHSI->getOperand(0))) {
3354       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3355       if (C1.isPowerOf2()) {
3356         Value *N = RHSI->getOperand(1);
3357         const Type *NTy = N->getType();
3358         if (uint32_t C2 = C1.logBase2()) {
3359           Constant *C2V = ConstantInt::get(NTy, C2);
3360           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3361         }
3362         return BinaryOperator::CreateLShr(Op0, N);
3363       }
3364     }
3365   }
3366   
3367   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3368   // where C1&C2 are powers of two.
3369   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3370     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3371       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3372         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3373         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3374           // Compute the shift amounts
3375           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3376           // Construct the "on true" case of the select
3377           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3378           Instruction *TSI = BinaryOperator::CreateLShr(
3379                                                  Op0, TC, SI->getName()+".t");
3380           TSI = InsertNewInstBefore(TSI, I);
3381   
3382           // Construct the "on false" case of the select
3383           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3384           Instruction *FSI = BinaryOperator::CreateLShr(
3385                                                  Op0, FC, SI->getName()+".f");
3386           FSI = InsertNewInstBefore(FSI, I);
3387
3388           // construct the select instruction and return it.
3389           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3390         }
3391       }
3392   return 0;
3393 }
3394
3395 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3396   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3397
3398   // Handle the integer div common cases
3399   if (Instruction *Common = commonIDivTransforms(I))
3400     return Common;
3401
3402   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3403     // sdiv X, -1 == -X
3404     if (RHS->isAllOnesValue())
3405       return BinaryOperator::CreateNeg(Op0);
3406
3407     // -X/C -> X/-C
3408     if (Value *LHSNeg = dyn_castNegVal(Op0))
3409       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3410   }
3411
3412   // If the sign bits of both operands are zero (i.e. we can prove they are
3413   // unsigned inputs), turn this into a udiv.
3414   if (I.getType()->isInteger()) {
3415     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3416     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3417       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3418       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3419     }
3420   }      
3421   
3422   return 0;
3423 }
3424
3425 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3426   return commonDivTransforms(I);
3427 }
3428
3429 /// This function implements the transforms on rem instructions that work
3430 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3431 /// is used by the visitors to those instructions.
3432 /// @brief Transforms common to all three rem instructions
3433 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3434   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3435
3436   // 0 % X == 0 for integer, we don't need to preserve faults!
3437   if (Constant *LHS = dyn_cast<Constant>(Op0))
3438     if (LHS->isNullValue())
3439       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3440
3441   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3442     if (I.getType()->isFPOrFPVector())
3443       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3444     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3445   }
3446   if (isa<UndefValue>(Op1))
3447     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3448
3449   // Handle cases involving: rem X, (select Cond, Y, Z)
3450   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3451     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
3452     // the same basic block, then we replace the select with Y, and the
3453     // condition of the select with false (if the cond value is in the same
3454     // BB).  If the select has uses other than the div, this allows them to be
3455     // simplified also.
3456     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3457       if (ST->isNullValue()) {
3458         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3459         if (CondI && CondI->getParent() == I.getParent())
3460           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3461         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3462           I.setOperand(1, SI->getOperand(2));
3463         else
3464           UpdateValueUsesWith(SI, SI->getOperand(2));
3465         return &I;
3466       }
3467     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3468     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3469       if (ST->isNullValue()) {
3470         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3471         if (CondI && CondI->getParent() == I.getParent())
3472           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3473         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3474           I.setOperand(1, SI->getOperand(1));
3475         else
3476           UpdateValueUsesWith(SI, SI->getOperand(1));
3477         return &I;
3478       }
3479   }
3480
3481   return 0;
3482 }
3483
3484 /// This function implements the transforms common to both integer remainder
3485 /// instructions (urem and srem). It is called by the visitors to those integer
3486 /// remainder instructions.
3487 /// @brief Common integer remainder transforms
3488 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3489   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3490
3491   if (Instruction *common = commonRemTransforms(I))
3492     return common;
3493
3494   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3495     // X % 0 == undef, we don't need to preserve faults!
3496     if (RHS->equalsInt(0))
3497       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3498     
3499     if (RHS->equalsInt(1))  // X % 1 == 0
3500       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3501
3502     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3503       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3504         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3505           return R;
3506       } else if (isa<PHINode>(Op0I)) {
3507         if (Instruction *NV = FoldOpIntoPhi(I))
3508           return NV;
3509       }
3510
3511       // See if we can fold away this rem instruction.
3512       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3513       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3514       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3515                                KnownZero, KnownOne))
3516         return &I;
3517     }
3518   }
3519
3520   return 0;
3521 }
3522
3523 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3524   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3525
3526   if (Instruction *common = commonIRemTransforms(I))
3527     return common;
3528   
3529   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3530     // X urem C^2 -> X and C
3531     // Check to see if this is an unsigned remainder with an exact power of 2,
3532     // if so, convert to a bitwise and.
3533     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3534       if (C->getValue().isPowerOf2())
3535         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3536   }
3537
3538   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3539     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3540     if (RHSI->getOpcode() == Instruction::Shl &&
3541         isa<ConstantInt>(RHSI->getOperand(0))) {
3542       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3543         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3544         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3545                                                                    "tmp"), I);
3546         return BinaryOperator::CreateAnd(Op0, Add);
3547       }
3548     }
3549   }
3550
3551   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3552   // where C1&C2 are powers of two.
3553   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3554     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3555       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3556         // STO == 0 and SFO == 0 handled above.
3557         if ((STO->getValue().isPowerOf2()) && 
3558             (SFO->getValue().isPowerOf2())) {
3559           Value *TrueAnd = InsertNewInstBefore(
3560             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3561           Value *FalseAnd = InsertNewInstBefore(
3562             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3563           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3564         }
3565       }
3566   }
3567   
3568   return 0;
3569 }
3570
3571 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3572   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3573
3574   // Handle the integer rem common cases
3575   if (Instruction *common = commonIRemTransforms(I))
3576     return common;
3577   
3578   if (Value *RHSNeg = dyn_castNegVal(Op1))
3579     if (!isa<ConstantInt>(RHSNeg) || 
3580         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3581       // X % -Y -> X % Y
3582       AddUsesToWorkList(I);
3583       I.setOperand(1, RHSNeg);
3584       return &I;
3585     }
3586  
3587   // If the sign bits of both operands are zero (i.e. we can prove they are
3588   // unsigned inputs), turn this into a urem.
3589   if (I.getType()->isInteger()) {
3590     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3591     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3592       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3593       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3594     }
3595   }
3596
3597   return 0;
3598 }
3599
3600 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3601   return commonRemTransforms(I);
3602 }
3603
3604 // isMaxValueMinusOne - return true if this is Max-1
3605 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3606   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3607   if (!isSigned)
3608     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3609   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3610 }
3611
3612 // isMinValuePlusOne - return true if this is Min+1
3613 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3614   if (!isSigned)
3615     return C->getValue() == 1; // unsigned
3616     
3617   // Calculate 1111111111000000000000
3618   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3619   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3620 }
3621
3622 // isOneBitSet - Return true if there is exactly one bit set in the specified
3623 // constant.
3624 static bool isOneBitSet(const ConstantInt *CI) {
3625   return CI->getValue().isPowerOf2();
3626 }
3627
3628 // isHighOnes - Return true if the constant is of the form 1+0+.
3629 // This is the same as lowones(~X).
3630 static bool isHighOnes(const ConstantInt *CI) {
3631   return (~CI->getValue() + 1).isPowerOf2();
3632 }
3633
3634 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3635 /// are carefully arranged to allow folding of expressions such as:
3636 ///
3637 ///      (A < B) | (A > B) --> (A != B)
3638 ///
3639 /// Note that this is only valid if the first and second predicates have the
3640 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3641 ///
3642 /// Three bits are used to represent the condition, as follows:
3643 ///   0  A > B
3644 ///   1  A == B
3645 ///   2  A < B
3646 ///
3647 /// <=>  Value  Definition
3648 /// 000     0   Always false
3649 /// 001     1   A >  B
3650 /// 010     2   A == B
3651 /// 011     3   A >= B
3652 /// 100     4   A <  B
3653 /// 101     5   A != B
3654 /// 110     6   A <= B
3655 /// 111     7   Always true
3656 ///  
3657 static unsigned getICmpCode(const ICmpInst *ICI) {
3658   switch (ICI->getPredicate()) {
3659     // False -> 0
3660   case ICmpInst::ICMP_UGT: return 1;  // 001
3661   case ICmpInst::ICMP_SGT: return 1;  // 001
3662   case ICmpInst::ICMP_EQ:  return 2;  // 010
3663   case ICmpInst::ICMP_UGE: return 3;  // 011
3664   case ICmpInst::ICMP_SGE: return 3;  // 011
3665   case ICmpInst::ICMP_ULT: return 4;  // 100
3666   case ICmpInst::ICMP_SLT: return 4;  // 100
3667   case ICmpInst::ICMP_NE:  return 5;  // 101
3668   case ICmpInst::ICMP_ULE: return 6;  // 110
3669   case ICmpInst::ICMP_SLE: return 6;  // 110
3670     // True -> 7
3671   default:
3672     assert(0 && "Invalid ICmp predicate!");
3673     return 0;
3674   }
3675 }
3676
3677 /// getICmpValue - This is the complement of getICmpCode, which turns an
3678 /// opcode and two operands into either a constant true or false, or a brand 
3679 /// new ICmp instruction. The sign is passed in to determine which kind
3680 /// of predicate to use in new icmp instructions.
3681 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3682   switch (code) {
3683   default: assert(0 && "Illegal ICmp code!");
3684   case  0: return ConstantInt::getFalse();
3685   case  1: 
3686     if (sign)
3687       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3688     else
3689       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3690   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3691   case  3: 
3692     if (sign)
3693       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3694     else
3695       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3696   case  4: 
3697     if (sign)
3698       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3699     else
3700       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3701   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3702   case  6: 
3703     if (sign)
3704       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3705     else
3706       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3707   case  7: return ConstantInt::getTrue();
3708   }
3709 }
3710
3711 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3712   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3713     (ICmpInst::isSignedPredicate(p1) && 
3714      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3715     (ICmpInst::isSignedPredicate(p2) && 
3716      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3717 }
3718
3719 namespace { 
3720 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3721 struct FoldICmpLogical {
3722   InstCombiner &IC;
3723   Value *LHS, *RHS;
3724   ICmpInst::Predicate pred;
3725   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3726     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3727       pred(ICI->getPredicate()) {}
3728   bool shouldApply(Value *V) const {
3729     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3730       if (PredicatesFoldable(pred, ICI->getPredicate()))
3731         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3732                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3733     return false;
3734   }
3735   Instruction *apply(Instruction &Log) const {
3736     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3737     if (ICI->getOperand(0) != LHS) {
3738       assert(ICI->getOperand(1) == LHS);
3739       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3740     }
3741
3742     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3743     unsigned LHSCode = getICmpCode(ICI);
3744     unsigned RHSCode = getICmpCode(RHSICI);
3745     unsigned Code;
3746     switch (Log.getOpcode()) {
3747     case Instruction::And: Code = LHSCode & RHSCode; break;
3748     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3749     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3750     default: assert(0 && "Illegal logical opcode!"); return 0;
3751     }
3752
3753     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3754                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3755       
3756     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3757     if (Instruction *I = dyn_cast<Instruction>(RV))
3758       return I;
3759     // Otherwise, it's a constant boolean value...
3760     return IC.ReplaceInstUsesWith(Log, RV);
3761   }
3762 };
3763 } // end anonymous namespace
3764
3765 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3766 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3767 // guaranteed to be a binary operator.
3768 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3769                                     ConstantInt *OpRHS,
3770                                     ConstantInt *AndRHS,
3771                                     BinaryOperator &TheAnd) {
3772   Value *X = Op->getOperand(0);
3773   Constant *Together = 0;
3774   if (!Op->isShift())
3775     Together = And(AndRHS, OpRHS);
3776
3777   switch (Op->getOpcode()) {
3778   case Instruction::Xor:
3779     if (Op->hasOneUse()) {
3780       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3781       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3782       InsertNewInstBefore(And, TheAnd);
3783       And->takeName(Op);
3784       return BinaryOperator::CreateXor(And, Together);
3785     }
3786     break;
3787   case Instruction::Or:
3788     if (Together == AndRHS) // (X | C) & C --> C
3789       return ReplaceInstUsesWith(TheAnd, AndRHS);
3790
3791     if (Op->hasOneUse() && Together != OpRHS) {
3792       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3793       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3794       InsertNewInstBefore(Or, TheAnd);
3795       Or->takeName(Op);
3796       return BinaryOperator::CreateAnd(Or, AndRHS);
3797     }
3798     break;
3799   case Instruction::Add:
3800     if (Op->hasOneUse()) {
3801       // Adding a one to a single bit bit-field should be turned into an XOR
3802       // of the bit.  First thing to check is to see if this AND is with a
3803       // single bit constant.
3804       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3805
3806       // If there is only one bit set...
3807       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3808         // Ok, at this point, we know that we are masking the result of the
3809         // ADD down to exactly one bit.  If the constant we are adding has
3810         // no bits set below this bit, then we can eliminate the ADD.
3811         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3812
3813         // Check to see if any bits below the one bit set in AndRHSV are set.
3814         if ((AddRHS & (AndRHSV-1)) == 0) {
3815           // If not, the only thing that can effect the output of the AND is
3816           // the bit specified by AndRHSV.  If that bit is set, the effect of
3817           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3818           // no effect.
3819           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3820             TheAnd.setOperand(0, X);
3821             return &TheAnd;
3822           } else {
3823             // Pull the XOR out of the AND.
3824             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3825             InsertNewInstBefore(NewAnd, TheAnd);
3826             NewAnd->takeName(Op);
3827             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3828           }
3829         }
3830       }
3831     }
3832     break;
3833
3834   case Instruction::Shl: {
3835     // We know that the AND will not produce any of the bits shifted in, so if
3836     // the anded constant includes them, clear them now!
3837     //
3838     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3839     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3840     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3841     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3842
3843     if (CI->getValue() == ShlMask) { 
3844     // Masking out bits that the shift already masks
3845       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3846     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3847       TheAnd.setOperand(1, CI);
3848       return &TheAnd;
3849     }
3850     break;
3851   }
3852   case Instruction::LShr:
3853   {
3854     // We know that the AND will not produce any of the bits shifted in, so if
3855     // the anded constant includes them, clear them now!  This only applies to
3856     // unsigned shifts, because a signed shr may bring in set bits!
3857     //
3858     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3859     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3860     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3861     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3862
3863     if (CI->getValue() == ShrMask) {   
3864     // Masking out bits that the shift already masks.
3865       return ReplaceInstUsesWith(TheAnd, Op);
3866     } else if (CI != AndRHS) {
3867       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3868       return &TheAnd;
3869     }
3870     break;
3871   }
3872   case Instruction::AShr:
3873     // Signed shr.
3874     // See if this is shifting in some sign extension, then masking it out
3875     // with an and.
3876     if (Op->hasOneUse()) {
3877       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3878       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3879       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3880       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3881       if (C == AndRHS) {          // Masking out bits shifted in.
3882         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3883         // Make the argument unsigned.
3884         Value *ShVal = Op->getOperand(0);
3885         ShVal = InsertNewInstBefore(
3886             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3887                                    Op->getName()), TheAnd);
3888         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3889       }
3890     }
3891     break;
3892   }
3893   return 0;
3894 }
3895
3896
3897 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3898 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3899 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3900 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3901 /// insert new instructions.
3902 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3903                                            bool isSigned, bool Inside, 
3904                                            Instruction &IB) {
3905   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3906             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3907          "Lo is not <= Hi in range emission code!");
3908     
3909   if (Inside) {
3910     if (Lo == Hi)  // Trivially false.
3911       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3912
3913     // V >= Min && V < Hi --> V < Hi
3914     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3915       ICmpInst::Predicate pred = (isSigned ? 
3916         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3917       return new ICmpInst(pred, V, Hi);
3918     }
3919
3920     // Emit V-Lo <u Hi-Lo
3921     Constant *NegLo = ConstantExpr::getNeg(Lo);
3922     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3923     InsertNewInstBefore(Add, IB);
3924     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3925     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3926   }
3927
3928   if (Lo == Hi)  // Trivially true.
3929     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3930
3931   // V < Min || V >= Hi -> V > Hi-1
3932   Hi = SubOne(cast<ConstantInt>(Hi));
3933   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3934     ICmpInst::Predicate pred = (isSigned ? 
3935         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3936     return new ICmpInst(pred, V, Hi);
3937   }
3938
3939   // Emit V-Lo >u Hi-1-Lo
3940   // Note that Hi has already had one subtracted from it, above.
3941   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3942   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3943   InsertNewInstBefore(Add, IB);
3944   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3945   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3946 }
3947
3948 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3949 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3950 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3951 // not, since all 1s are not contiguous.
3952 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3953   const APInt& V = Val->getValue();
3954   uint32_t BitWidth = Val->getType()->getBitWidth();
3955   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3956
3957   // look for the first zero bit after the run of ones
3958   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3959   // look for the first non-zero bit
3960   ME = V.getActiveBits(); 
3961   return true;
3962 }
3963
3964 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3965 /// where isSub determines whether the operator is a sub.  If we can fold one of
3966 /// the following xforms:
3967 /// 
3968 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3969 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3970 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3971 ///
3972 /// return (A +/- B).
3973 ///
3974 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3975                                         ConstantInt *Mask, bool isSub,
3976                                         Instruction &I) {
3977   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3978   if (!LHSI || LHSI->getNumOperands() != 2 ||
3979       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3980
3981   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3982
3983   switch (LHSI->getOpcode()) {
3984   default: return 0;
3985   case Instruction::And:
3986     if (And(N, Mask) == Mask) {
3987       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3988       if ((Mask->getValue().countLeadingZeros() + 
3989            Mask->getValue().countPopulation()) == 
3990           Mask->getValue().getBitWidth())
3991         break;
3992
3993       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3994       // part, we don't need any explicit masks to take them out of A.  If that
3995       // is all N is, ignore it.
3996       uint32_t MB = 0, ME = 0;
3997       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3998         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3999         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4000         if (MaskedValueIsZero(RHS, Mask))
4001           break;
4002       }
4003     }
4004     return 0;
4005   case Instruction::Or:
4006   case Instruction::Xor:
4007     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4008     if ((Mask->getValue().countLeadingZeros() + 
4009          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4010         && And(N, Mask)->isZero())
4011       break;
4012     return 0;
4013   }
4014   
4015   Instruction *New;
4016   if (isSub)
4017     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
4018   else
4019     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
4020   return InsertNewInstBefore(New, I);
4021 }
4022
4023 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4024   bool Changed = SimplifyCommutative(I);
4025   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4026
4027   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4028     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4029
4030   // and X, X = X
4031   if (Op0 == Op1)
4032     return ReplaceInstUsesWith(I, Op1);
4033
4034   // See if we can simplify any instructions used by the instruction whose sole 
4035   // purpose is to compute bits we don't care about.
4036   if (!isa<VectorType>(I.getType())) {
4037     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4038     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4039     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4040                              KnownZero, KnownOne))
4041       return &I;
4042   } else {
4043     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4044       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4045         return ReplaceInstUsesWith(I, I.getOperand(0));
4046     } else if (isa<ConstantAggregateZero>(Op1)) {
4047       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4048     }
4049   }
4050   
4051   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4052     const APInt& AndRHSMask = AndRHS->getValue();
4053     APInt NotAndRHS(~AndRHSMask);
4054
4055     // Optimize a variety of ((val OP C1) & C2) combinations...
4056     if (isa<BinaryOperator>(Op0)) {
4057       Instruction *Op0I = cast<Instruction>(Op0);
4058       Value *Op0LHS = Op0I->getOperand(0);
4059       Value *Op0RHS = Op0I->getOperand(1);
4060       switch (Op0I->getOpcode()) {
4061       case Instruction::Xor:
4062       case Instruction::Or:
4063         // If the mask is only needed on one incoming arm, push it up.
4064         if (Op0I->hasOneUse()) {
4065           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4066             // Not masking anything out for the LHS, move to RHS.
4067             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4068                                                    Op0RHS->getName()+".masked");
4069             InsertNewInstBefore(NewRHS, I);
4070             return BinaryOperator::Create(
4071                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4072           }
4073           if (!isa<Constant>(Op0RHS) &&
4074               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4075             // Not masking anything out for the RHS, move to LHS.
4076             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4077                                                    Op0LHS->getName()+".masked");
4078             InsertNewInstBefore(NewLHS, I);
4079             return BinaryOperator::Create(
4080                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4081           }
4082         }
4083
4084         break;
4085       case Instruction::Add:
4086         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4087         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4088         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4089         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4090           return BinaryOperator::CreateAnd(V, AndRHS);
4091         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4092           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4093         break;
4094
4095       case Instruction::Sub:
4096         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4097         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4098         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4099         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4100           return BinaryOperator::CreateAnd(V, AndRHS);
4101         break;
4102       }
4103
4104       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4105         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4106           return Res;
4107     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4108       // If this is an integer truncation or change from signed-to-unsigned, and
4109       // if the source is an and/or with immediate, transform it.  This
4110       // frequently occurs for bitfield accesses.
4111       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4112         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4113             CastOp->getNumOperands() == 2)
4114           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4115             if (CastOp->getOpcode() == Instruction::And) {
4116               // Change: and (cast (and X, C1) to T), C2
4117               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4118               // This will fold the two constants together, which may allow 
4119               // other simplifications.
4120               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4121                 CastOp->getOperand(0), I.getType(), 
4122                 CastOp->getName()+".shrunk");
4123               NewCast = InsertNewInstBefore(NewCast, I);
4124               // trunc_or_bitcast(C1)&C2
4125               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4126               C3 = ConstantExpr::getAnd(C3, AndRHS);
4127               return BinaryOperator::CreateAnd(NewCast, C3);
4128             } else if (CastOp->getOpcode() == Instruction::Or) {
4129               // Change: and (cast (or X, C1) to T), C2
4130               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4131               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4132               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
4133                 return ReplaceInstUsesWith(I, AndRHS);
4134             }
4135           }
4136       }
4137     }
4138
4139     // Try to fold constant and into select arguments.
4140     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4141       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4142         return R;
4143     if (isa<PHINode>(Op0))
4144       if (Instruction *NV = FoldOpIntoPhi(I))
4145         return NV;
4146   }
4147
4148   Value *Op0NotVal = dyn_castNotVal(Op0);
4149   Value *Op1NotVal = dyn_castNotVal(Op1);
4150
4151   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4152     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4153
4154   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4155   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4156     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4157                                                I.getName()+".demorgan");
4158     InsertNewInstBefore(Or, I);
4159     return BinaryOperator::CreateNot(Or);
4160   }
4161   
4162   {
4163     Value *A = 0, *B = 0, *C = 0, *D = 0;
4164     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4165       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4166         return ReplaceInstUsesWith(I, Op1);
4167     
4168       // (A|B) & ~(A&B) -> A^B
4169       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4170         if ((A == C && B == D) || (A == D && B == C))
4171           return BinaryOperator::CreateXor(A, B);
4172       }
4173     }
4174     
4175     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4176       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4177         return ReplaceInstUsesWith(I, Op0);
4178
4179       // ~(A&B) & (A|B) -> A^B
4180       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4181         if ((A == C && B == D) || (A == D && B == C))
4182           return BinaryOperator::CreateXor(A, B);
4183       }
4184     }
4185     
4186     if (Op0->hasOneUse() &&
4187         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4188       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4189         I.swapOperands();     // Simplify below
4190         std::swap(Op0, Op1);
4191       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4192         cast<BinaryOperator>(Op0)->swapOperands();
4193         I.swapOperands();     // Simplify below
4194         std::swap(Op0, Op1);
4195       }
4196     }
4197     if (Op1->hasOneUse() &&
4198         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4199       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4200         cast<BinaryOperator>(Op1)->swapOperands();
4201         std::swap(A, B);
4202       }
4203       if (A == Op0) {                                // A&(A^B) -> A & ~B
4204         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4205         InsertNewInstBefore(NotB, I);
4206         return BinaryOperator::CreateAnd(A, NotB);
4207       }
4208     }
4209   }
4210   
4211   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4212     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4213     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4214       return R;
4215
4216     Value *LHSVal, *RHSVal;
4217     ConstantInt *LHSCst, *RHSCst;
4218     ICmpInst::Predicate LHSCC, RHSCC;
4219     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4220       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4221         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
4222             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4223             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4224             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4225             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4226             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4227             
4228             // Don't try to fold ICMP_SLT + ICMP_ULT.
4229             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4230              ICmpInst::isSignedPredicate(LHSCC) == 
4231                  ICmpInst::isSignedPredicate(RHSCC))) {
4232           // Ensure that the larger constant is on the RHS.
4233           ICmpInst::Predicate GT;
4234           if (ICmpInst::isSignedPredicate(LHSCC) ||
4235               (ICmpInst::isEquality(LHSCC) && 
4236                ICmpInst::isSignedPredicate(RHSCC)))
4237             GT = ICmpInst::ICMP_SGT;
4238           else
4239             GT = ICmpInst::ICMP_UGT;
4240           
4241           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4242           ICmpInst *LHS = cast<ICmpInst>(Op0);
4243           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4244             std::swap(LHS, RHS);
4245             std::swap(LHSCst, RHSCst);
4246             std::swap(LHSCC, RHSCC);
4247           }
4248
4249           // At this point, we know we have have two icmp instructions
4250           // comparing a value against two constants and and'ing the result
4251           // together.  Because of the above check, we know that we only have
4252           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4253           // (from the FoldICmpLogical check above), that the two constants 
4254           // are not equal and that the larger constant is on the RHS
4255           assert(LHSCst != RHSCst && "Compares not folded above?");
4256
4257           switch (LHSCC) {
4258           default: assert(0 && "Unknown integer condition code!");
4259           case ICmpInst::ICMP_EQ:
4260             switch (RHSCC) {
4261             default: assert(0 && "Unknown integer condition code!");
4262             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4263             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4264             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4265               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4266             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4267             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4268             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4269               return ReplaceInstUsesWith(I, LHS);
4270             }
4271           case ICmpInst::ICMP_NE:
4272             switch (RHSCC) {
4273             default: assert(0 && "Unknown integer condition code!");
4274             case ICmpInst::ICMP_ULT:
4275               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4276                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4277               break;                        // (X != 13 & X u< 15) -> no change
4278             case ICmpInst::ICMP_SLT:
4279               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4280                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4281               break;                        // (X != 13 & X s< 15) -> no change
4282             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4283             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4284             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4285               return ReplaceInstUsesWith(I, RHS);
4286             case ICmpInst::ICMP_NE:
4287               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4288                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4289                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4290                                                       LHSVal->getName()+".off");
4291                 InsertNewInstBefore(Add, I);
4292                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4293                                     ConstantInt::get(Add->getType(), 1));
4294               }
4295               break;                        // (X != 13 & X != 15) -> no change
4296             }
4297             break;
4298           case ICmpInst::ICMP_ULT:
4299             switch (RHSCC) {
4300             default: assert(0 && "Unknown integer condition code!");
4301             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4302             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4303               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4304             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4305               break;
4306             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4307             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4308               return ReplaceInstUsesWith(I, LHS);
4309             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4310               break;
4311             }
4312             break;
4313           case ICmpInst::ICMP_SLT:
4314             switch (RHSCC) {
4315             default: assert(0 && "Unknown integer condition code!");
4316             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4317             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4318               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4319             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4320               break;
4321             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4322             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4323               return ReplaceInstUsesWith(I, LHS);
4324             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4325               break;
4326             }
4327             break;
4328           case ICmpInst::ICMP_UGT:
4329             switch (RHSCC) {
4330             default: assert(0 && "Unknown integer condition code!");
4331             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
4332               return ReplaceInstUsesWith(I, LHS);
4333             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4334               return ReplaceInstUsesWith(I, RHS);
4335             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4336               break;
4337             case ICmpInst::ICMP_NE:
4338               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4339                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4340               break;                        // (X u> 13 & X != 15) -> no change
4341             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
4342               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
4343                                      true, I);
4344             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4345               break;
4346             }
4347             break;
4348           case ICmpInst::ICMP_SGT:
4349             switch (RHSCC) {
4350             default: assert(0 && "Unknown integer condition code!");
4351             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4352             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4353               return ReplaceInstUsesWith(I, RHS);
4354             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4355               break;
4356             case ICmpInst::ICMP_NE:
4357               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4358                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4359               break;                        // (X s> 13 & X != 15) -> no change
4360             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
4361               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
4362                                      true, I);
4363             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4364               break;
4365             }
4366             break;
4367           }
4368         }
4369   }
4370
4371   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4372   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4373     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4374       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4375         const Type *SrcTy = Op0C->getOperand(0)->getType();
4376         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4377             // Only do this if the casts both really cause code to be generated.
4378             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4379                               I.getType(), TD) &&
4380             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4381                               I.getType(), TD)) {
4382           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4383                                                          Op1C->getOperand(0),
4384                                                          I.getName());
4385           InsertNewInstBefore(NewOp, I);
4386           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4387         }
4388       }
4389     
4390   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4391   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4392     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4393       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4394           SI0->getOperand(1) == SI1->getOperand(1) &&
4395           (SI0->hasOneUse() || SI1->hasOneUse())) {
4396         Instruction *NewOp =
4397           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4398                                                         SI1->getOperand(0),
4399                                                         SI0->getName()), I);
4400         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4401                                       SI1->getOperand(1));
4402       }
4403   }
4404
4405   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4406   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4407     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4408       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4409           RHS->getPredicate() == FCmpInst::FCMP_ORD)
4410         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4411           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4412             // If either of the constants are nans, then the whole thing returns
4413             // false.
4414             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4415               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4416             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4417                                 RHS->getOperand(0));
4418           }
4419     }
4420   }
4421       
4422   return Changed ? &I : 0;
4423 }
4424
4425 /// CollectBSwapParts - Look to see if the specified value defines a single byte
4426 /// in the result.  If it does, and if the specified byte hasn't been filled in
4427 /// yet, fill it in and return false.
4428 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4429   Instruction *I = dyn_cast<Instruction>(V);
4430   if (I == 0) return true;
4431
4432   // If this is an or instruction, it is an inner node of the bswap.
4433   if (I->getOpcode() == Instruction::Or)
4434     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4435            CollectBSwapParts(I->getOperand(1), ByteValues);
4436   
4437   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4438   // If this is a shift by a constant int, and it is "24", then its operand
4439   // defines a byte.  We only handle unsigned types here.
4440   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4441     // Not shifting the entire input by N-1 bytes?
4442     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4443         8*(ByteValues.size()-1))
4444       return true;
4445     
4446     unsigned DestNo;
4447     if (I->getOpcode() == Instruction::Shl) {
4448       // X << 24 defines the top byte with the lowest of the input bytes.
4449       DestNo = ByteValues.size()-1;
4450     } else {
4451       // X >>u 24 defines the low byte with the highest of the input bytes.
4452       DestNo = 0;
4453     }
4454     
4455     // If the destination byte value is already defined, the values are or'd
4456     // together, which isn't a bswap (unless it's an or of the same bits).
4457     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4458       return true;
4459     ByteValues[DestNo] = I->getOperand(0);
4460     return false;
4461   }
4462   
4463   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
4464   // don't have this.
4465   Value *Shift = 0, *ShiftLHS = 0;
4466   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4467   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4468       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4469     return true;
4470   Instruction *SI = cast<Instruction>(Shift);
4471
4472   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4473   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4474       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4475     return true;
4476   
4477   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4478   unsigned DestByte;
4479   if (AndAmt->getValue().getActiveBits() > 64)
4480     return true;
4481   uint64_t AndAmtVal = AndAmt->getZExtValue();
4482   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4483     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4484       break;
4485   // Unknown mask for bswap.
4486   if (DestByte == ByteValues.size()) return true;
4487   
4488   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4489   unsigned SrcByte;
4490   if (SI->getOpcode() == Instruction::Shl)
4491     SrcByte = DestByte - ShiftBytes;
4492   else
4493     SrcByte = DestByte + ShiftBytes;
4494   
4495   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4496   if (SrcByte != ByteValues.size()-DestByte-1)
4497     return true;
4498   
4499   // If the destination byte value is already defined, the values are or'd
4500   // together, which isn't a bswap (unless it's an or of the same bits).
4501   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4502     return true;
4503   ByteValues[DestByte] = SI->getOperand(0);
4504   return false;
4505 }
4506
4507 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4508 /// If so, insert the new bswap intrinsic and return it.
4509 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4510   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4511   if (!ITy || ITy->getBitWidth() % 16) 
4512     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4513   
4514   /// ByteValues - For each byte of the result, we keep track of which value
4515   /// defines each byte.
4516   SmallVector<Value*, 8> ByteValues;
4517   ByteValues.resize(ITy->getBitWidth()/8);
4518     
4519   // Try to find all the pieces corresponding to the bswap.
4520   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4521       CollectBSwapParts(I.getOperand(1), ByteValues))
4522     return 0;
4523   
4524   // Check to see if all of the bytes come from the same value.
4525   Value *V = ByteValues[0];
4526   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4527   
4528   // Check to make sure that all of the bytes come from the same value.
4529   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4530     if (ByteValues[i] != V)
4531       return 0;
4532   const Type *Tys[] = { ITy };
4533   Module *M = I.getParent()->getParent()->getParent();
4534   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4535   return CallInst::Create(F, V);
4536 }
4537
4538
4539 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4540   bool Changed = SimplifyCommutative(I);
4541   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4542
4543   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4544     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4545
4546   // or X, X = X
4547   if (Op0 == Op1)
4548     return ReplaceInstUsesWith(I, Op0);
4549
4550   // See if we can simplify any instructions used by the instruction whose sole 
4551   // purpose is to compute bits we don't care about.
4552   if (!isa<VectorType>(I.getType())) {
4553     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4554     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4555     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4556                              KnownZero, KnownOne))
4557       return &I;
4558   } else if (isa<ConstantAggregateZero>(Op1)) {
4559     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4560   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4561     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4562       return ReplaceInstUsesWith(I, I.getOperand(1));
4563   }
4564     
4565
4566   
4567   // or X, -1 == -1
4568   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4569     ConstantInt *C1 = 0; Value *X = 0;
4570     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4571     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4572       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4573       InsertNewInstBefore(Or, I);
4574       Or->takeName(Op0);
4575       return BinaryOperator::CreateAnd(Or, 
4576                ConstantInt::get(RHS->getValue() | C1->getValue()));
4577     }
4578
4579     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4580     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4581       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4582       InsertNewInstBefore(Or, I);
4583       Or->takeName(Op0);
4584       return BinaryOperator::CreateXor(Or,
4585                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4586     }
4587
4588     // Try to fold constant and into select arguments.
4589     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4590       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4591         return R;
4592     if (isa<PHINode>(Op0))
4593       if (Instruction *NV = FoldOpIntoPhi(I))
4594         return NV;
4595   }
4596
4597   Value *A = 0, *B = 0;
4598   ConstantInt *C1 = 0, *C2 = 0;
4599
4600   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4601     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4602       return ReplaceInstUsesWith(I, Op1);
4603   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4604     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4605       return ReplaceInstUsesWith(I, Op0);
4606
4607   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4608   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4609   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4610       match(Op1, m_Or(m_Value(), m_Value())) ||
4611       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4612        match(Op1, m_Shift(m_Value(), m_Value())))) {
4613     if (Instruction *BSwap = MatchBSwap(I))
4614       return BSwap;
4615   }
4616   
4617   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4618   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4619       MaskedValueIsZero(Op1, C1->getValue())) {
4620     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4621     InsertNewInstBefore(NOr, I);
4622     NOr->takeName(Op0);
4623     return BinaryOperator::CreateXor(NOr, C1);
4624   }
4625
4626   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4627   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4628       MaskedValueIsZero(Op0, C1->getValue())) {
4629     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4630     InsertNewInstBefore(NOr, I);
4631     NOr->takeName(Op0);
4632     return BinaryOperator::CreateXor(NOr, C1);
4633   }
4634
4635   // (A & C)|(B & D)
4636   Value *C = 0, *D = 0;
4637   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4638       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4639     Value *V1 = 0, *V2 = 0, *V3 = 0;
4640     C1 = dyn_cast<ConstantInt>(C);
4641     C2 = dyn_cast<ConstantInt>(D);
4642     if (C1 && C2) {  // (A & C1)|(B & C2)
4643       // If we have: ((V + N) & C1) | (V & C2)
4644       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4645       // replace with V+N.
4646       if (C1->getValue() == ~C2->getValue()) {
4647         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4648             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4649           // Add commutes, try both ways.
4650           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4651             return ReplaceInstUsesWith(I, A);
4652           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4653             return ReplaceInstUsesWith(I, A);
4654         }
4655         // Or commutes, try both ways.
4656         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4657             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4658           // Add commutes, try both ways.
4659           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4660             return ReplaceInstUsesWith(I, B);
4661           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4662             return ReplaceInstUsesWith(I, B);
4663         }
4664       }
4665       V1 = 0; V2 = 0; V3 = 0;
4666     }
4667     
4668     // Check to see if we have any common things being and'ed.  If so, find the
4669     // terms for V1 & (V2|V3).
4670     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4671       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4672         V1 = A, V2 = C, V3 = D;
4673       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4674         V1 = A, V2 = B, V3 = C;
4675       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4676         V1 = C, V2 = A, V3 = D;
4677       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4678         V1 = C, V2 = A, V3 = B;
4679       
4680       if (V1) {
4681         Value *Or =
4682           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4683         return BinaryOperator::CreateAnd(V1, Or);
4684       }
4685     }
4686   }
4687   
4688   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4689   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4690     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4691       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4692           SI0->getOperand(1) == SI1->getOperand(1) &&
4693           (SI0->hasOneUse() || SI1->hasOneUse())) {
4694         Instruction *NewOp =
4695         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4696                                                      SI1->getOperand(0),
4697                                                      SI0->getName()), I);
4698         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4699                                       SI1->getOperand(1));
4700       }
4701   }
4702
4703   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4704     if (A == Op1)   // ~A | A == -1
4705       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4706   } else {
4707     A = 0;
4708   }
4709   // Note, A is still live here!
4710   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4711     if (Op0 == B)
4712       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4713
4714     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4715     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4716       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4717                                               I.getName()+".demorgan"), I);
4718       return BinaryOperator::CreateNot(And);
4719     }
4720   }
4721
4722   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4723   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4724     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4725       return R;
4726
4727     Value *LHSVal, *RHSVal;
4728     ConstantInt *LHSCst, *RHSCst;
4729     ICmpInst::Predicate LHSCC, RHSCC;
4730     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4731       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4732         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4733             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4734             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4735             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4736             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4737             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4738             // We can't fold (ugt x, C) | (sgt x, C2).
4739             PredicatesFoldable(LHSCC, RHSCC)) {
4740           // Ensure that the larger constant is on the RHS.
4741           ICmpInst *LHS = cast<ICmpInst>(Op0);
4742           bool NeedsSwap;
4743           if (ICmpInst::isSignedPredicate(LHSCC))
4744             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4745           else
4746             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4747             
4748           if (NeedsSwap) {
4749             std::swap(LHS, RHS);
4750             std::swap(LHSCst, RHSCst);
4751             std::swap(LHSCC, RHSCC);
4752           }
4753
4754           // At this point, we know we have have two icmp instructions
4755           // comparing a value against two constants and or'ing the result
4756           // together.  Because of the above check, we know that we only have
4757           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4758           // FoldICmpLogical check above), that the two constants are not
4759           // equal.
4760           assert(LHSCst != RHSCst && "Compares not folded above?");
4761
4762           switch (LHSCC) {
4763           default: assert(0 && "Unknown integer condition code!");
4764           case ICmpInst::ICMP_EQ:
4765             switch (RHSCC) {
4766             default: assert(0 && "Unknown integer condition code!");
4767             case ICmpInst::ICMP_EQ:
4768               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4769                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4770                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4771                                                       LHSVal->getName()+".off");
4772                 InsertNewInstBefore(Add, I);
4773                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4774                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4775               }
4776               break;                         // (X == 13 | X == 15) -> no change
4777             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4778             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4779               break;
4780             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4781             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4782             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4783               return ReplaceInstUsesWith(I, RHS);
4784             }
4785             break;
4786           case ICmpInst::ICMP_NE:
4787             switch (RHSCC) {
4788             default: assert(0 && "Unknown integer condition code!");
4789             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4790             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4791             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4792               return ReplaceInstUsesWith(I, LHS);
4793             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4794             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4795             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4796               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4797             }
4798             break;
4799           case ICmpInst::ICMP_ULT:
4800             switch (RHSCC) {
4801             default: assert(0 && "Unknown integer condition code!");
4802             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4803               break;
4804             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4805               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4806               // this can cause overflow.
4807               if (RHSCst->isMaxValue(false))
4808                 return ReplaceInstUsesWith(I, LHS);
4809               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4810                                      false, I);
4811             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4812               break;
4813             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4814             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4815               return ReplaceInstUsesWith(I, RHS);
4816             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4817               break;
4818             }
4819             break;
4820           case ICmpInst::ICMP_SLT:
4821             switch (RHSCC) {
4822             default: assert(0 && "Unknown integer condition code!");
4823             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4824               break;
4825             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4826               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4827               // this can cause overflow.
4828               if (RHSCst->isMaxValue(true))
4829                 return ReplaceInstUsesWith(I, LHS);
4830               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4831                                      false, I);
4832             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4833               break;
4834             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4835             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4836               return ReplaceInstUsesWith(I, RHS);
4837             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4838               break;
4839             }
4840             break;
4841           case ICmpInst::ICMP_UGT:
4842             switch (RHSCC) {
4843             default: assert(0 && "Unknown integer condition code!");
4844             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4845             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4846               return ReplaceInstUsesWith(I, LHS);
4847             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4848               break;
4849             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4850             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4851               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4852             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4853               break;
4854             }
4855             break;
4856           case ICmpInst::ICMP_SGT:
4857             switch (RHSCC) {
4858             default: assert(0 && "Unknown integer condition code!");
4859             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4860             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4861               return ReplaceInstUsesWith(I, LHS);
4862             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4863               break;
4864             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4865             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4866               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4867             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4868               break;
4869             }
4870             break;
4871           }
4872         }
4873   }
4874     
4875   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4876   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4877     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4878       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4879         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4880             !isa<ICmpInst>(Op1C->getOperand(0))) {
4881           const Type *SrcTy = Op0C->getOperand(0)->getType();
4882           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4883               // Only do this if the casts both really cause code to be
4884               // generated.
4885               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4886                                 I.getType(), TD) &&
4887               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4888                                 I.getType(), TD)) {
4889             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4890                                                           Op1C->getOperand(0),
4891                                                           I.getName());
4892             InsertNewInstBefore(NewOp, I);
4893             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4894           }
4895         }
4896       }
4897   }
4898   
4899     
4900   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4901   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4902     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4903       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4904           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4905           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4906         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4907           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4908             // If either of the constants are nans, then the whole thing returns
4909             // true.
4910             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4911               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4912             
4913             // Otherwise, no need to compare the two constants, compare the
4914             // rest.
4915             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4916                                 RHS->getOperand(0));
4917           }
4918     }
4919   }
4920
4921   return Changed ? &I : 0;
4922 }
4923
4924 namespace {
4925
4926 // XorSelf - Implements: X ^ X --> 0
4927 struct XorSelf {
4928   Value *RHS;
4929   XorSelf(Value *rhs) : RHS(rhs) {}
4930   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4931   Instruction *apply(BinaryOperator &Xor) const {
4932     return &Xor;
4933   }
4934 };
4935
4936 }
4937
4938 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4939   bool Changed = SimplifyCommutative(I);
4940   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4941
4942   if (isa<UndefValue>(Op1)) {
4943     if (isa<UndefValue>(Op0))
4944       // Handle undef ^ undef -> 0 special case. This is a common
4945       // idiom (misuse).
4946       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4947     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4948   }
4949
4950   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4951   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4952     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4953     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4954   }
4955   
4956   // See if we can simplify any instructions used by the instruction whose sole 
4957   // purpose is to compute bits we don't care about.
4958   if (!isa<VectorType>(I.getType())) {
4959     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4960     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4961     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4962                              KnownZero, KnownOne))
4963       return &I;
4964   } else if (isa<ConstantAggregateZero>(Op1)) {
4965     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4966   }
4967
4968   // Is this a ~ operation?
4969   if (Value *NotOp = dyn_castNotVal(&I)) {
4970     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4971     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4972     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4973       if (Op0I->getOpcode() == Instruction::And || 
4974           Op0I->getOpcode() == Instruction::Or) {
4975         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4976         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4977           Instruction *NotY =
4978             BinaryOperator::CreateNot(Op0I->getOperand(1),
4979                                       Op0I->getOperand(1)->getName()+".not");
4980           InsertNewInstBefore(NotY, I);
4981           if (Op0I->getOpcode() == Instruction::And)
4982             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4983           else
4984             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4985         }
4986       }
4987     }
4988   }
4989   
4990   
4991   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4992     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4993     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4994       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4995         return new ICmpInst(ICI->getInversePredicate(),
4996                             ICI->getOperand(0), ICI->getOperand(1));
4997
4998       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4999         return new FCmpInst(FCI->getInversePredicate(),
5000                             FCI->getOperand(0), FCI->getOperand(1));
5001     }
5002
5003     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5004       // ~(c-X) == X-c-1 == X+(-c-1)
5005       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5006         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5007           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5008           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5009                                               ConstantInt::get(I.getType(), 1));
5010           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5011         }
5012           
5013       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5014         if (Op0I->getOpcode() == Instruction::Add) {
5015           // ~(X-c) --> (-c-1)-X
5016           if (RHS->isAllOnesValue()) {
5017             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5018             return BinaryOperator::CreateSub(
5019                            ConstantExpr::getSub(NegOp0CI,
5020                                              ConstantInt::get(I.getType(), 1)),
5021                                           Op0I->getOperand(0));
5022           } else if (RHS->getValue().isSignBit()) {
5023             // (X + C) ^ signbit -> (X + C + signbit)
5024             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
5025             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5026
5027           }
5028         } else if (Op0I->getOpcode() == Instruction::Or) {
5029           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5030           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5031             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5032             // Anything in both C1 and C2 is known to be zero, remove it from
5033             // NewRHS.
5034             Constant *CommonBits = And(Op0CI, RHS);
5035             NewRHS = ConstantExpr::getAnd(NewRHS, 
5036                                           ConstantExpr::getNot(CommonBits));
5037             AddToWorkList(Op0I);
5038             I.setOperand(0, Op0I->getOperand(0));
5039             I.setOperand(1, NewRHS);
5040             return &I;
5041           }
5042         }
5043       }
5044     }
5045
5046     // Try to fold constant and into select arguments.
5047     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5048       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5049         return R;
5050     if (isa<PHINode>(Op0))
5051       if (Instruction *NV = FoldOpIntoPhi(I))
5052         return NV;
5053   }
5054
5055   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5056     if (X == Op1)
5057       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5058
5059   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5060     if (X == Op0)
5061       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5062
5063   
5064   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5065   if (Op1I) {
5066     Value *A, *B;
5067     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5068       if (A == Op0) {              // B^(B|A) == (A|B)^B
5069         Op1I->swapOperands();
5070         I.swapOperands();
5071         std::swap(Op0, Op1);
5072       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5073         I.swapOperands();     // Simplified below.
5074         std::swap(Op0, Op1);
5075       }
5076     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5077       if (Op0 == A)                                          // A^(A^B) == B
5078         return ReplaceInstUsesWith(I, B);
5079       else if (Op0 == B)                                     // A^(B^A) == B
5080         return ReplaceInstUsesWith(I, A);
5081     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5082       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5083         Op1I->swapOperands();
5084         std::swap(A, B);
5085       }
5086       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5087         I.swapOperands();     // Simplified below.
5088         std::swap(Op0, Op1);
5089       }
5090     }
5091   }
5092   
5093   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5094   if (Op0I) {
5095     Value *A, *B;
5096     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5097       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5098         std::swap(A, B);
5099       if (B == Op1) {                                // (A|B)^B == A & ~B
5100         Instruction *NotB =
5101           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5102         return BinaryOperator::CreateAnd(A, NotB);
5103       }
5104     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5105       if (Op1 == A)                                          // (A^B)^A == B
5106         return ReplaceInstUsesWith(I, B);
5107       else if (Op1 == B)                                     // (B^A)^A == B
5108         return ReplaceInstUsesWith(I, A);
5109     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5110       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5111         std::swap(A, B);
5112       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5113           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5114         Instruction *N =
5115           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5116         return BinaryOperator::CreateAnd(N, Op1);
5117       }
5118     }
5119   }
5120   
5121   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5122   if (Op0I && Op1I && Op0I->isShift() && 
5123       Op0I->getOpcode() == Op1I->getOpcode() && 
5124       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5125       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5126     Instruction *NewOp =
5127       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5128                                                     Op1I->getOperand(0),
5129                                                     Op0I->getName()), I);
5130     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5131                                   Op1I->getOperand(1));
5132   }
5133     
5134   if (Op0I && Op1I) {
5135     Value *A, *B, *C, *D;
5136     // (A & B)^(A | B) -> A ^ B
5137     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5138         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5139       if ((A == C && B == D) || (A == D && B == C)) 
5140         return BinaryOperator::CreateXor(A, B);
5141     }
5142     // (A | B)^(A & B) -> A ^ B
5143     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5144         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5145       if ((A == C && B == D) || (A == D && B == C)) 
5146         return BinaryOperator::CreateXor(A, B);
5147     }
5148     
5149     // (A & B)^(C & D)
5150     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5151         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5152         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5153       // (X & Y)^(X & Y) -> (Y^Z) & X
5154       Value *X = 0, *Y = 0, *Z = 0;
5155       if (A == C)
5156         X = A, Y = B, Z = D;
5157       else if (A == D)
5158         X = A, Y = B, Z = C;
5159       else if (B == C)
5160         X = B, Y = A, Z = D;
5161       else if (B == D)
5162         X = B, Y = A, Z = C;
5163       
5164       if (X) {
5165         Instruction *NewOp =
5166         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5167         return BinaryOperator::CreateAnd(NewOp, X);
5168       }
5169     }
5170   }
5171     
5172   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5173   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5174     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5175       return R;
5176
5177   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5178   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5179     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5180       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5181         const Type *SrcTy = Op0C->getOperand(0)->getType();
5182         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5183             // Only do this if the casts both really cause code to be generated.
5184             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5185                               I.getType(), TD) &&
5186             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5187                               I.getType(), TD)) {
5188           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5189                                                          Op1C->getOperand(0),
5190                                                          I.getName());
5191           InsertNewInstBefore(NewOp, I);
5192           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5193         }
5194       }
5195   }
5196   return Changed ? &I : 0;
5197 }
5198
5199 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5200 /// overflowed for this type.
5201 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5202                             ConstantInt *In2, bool IsSigned = false) {
5203   Result = cast<ConstantInt>(Add(In1, In2));
5204
5205   if (IsSigned)
5206     if (In2->getValue().isNegative())
5207       return Result->getValue().sgt(In1->getValue());
5208     else
5209       return Result->getValue().slt(In1->getValue());
5210   else
5211     return Result->getValue().ult(In1->getValue());
5212 }
5213
5214 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5215 /// code necessary to compute the offset from the base pointer (without adding
5216 /// in the base pointer).  Return the result as a signed integer of intptr size.
5217 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5218   TargetData &TD = IC.getTargetData();
5219   gep_type_iterator GTI = gep_type_begin(GEP);
5220   const Type *IntPtrTy = TD.getIntPtrType();
5221   Value *Result = Constant::getNullValue(IntPtrTy);
5222
5223   // Build a mask for high order bits.
5224   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5225   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5226
5227   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5228     Value *Op = GEP->getOperand(i);
5229     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5230     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5231       if (OpC->isZero()) continue;
5232       
5233       // Handle a struct index, which adds its field offset to the pointer.
5234       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5235         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5236         
5237         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5238           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5239         else
5240           Result = IC.InsertNewInstBefore(
5241                    BinaryOperator::CreateAdd(Result,
5242                                              ConstantInt::get(IntPtrTy, Size),
5243                                              GEP->getName()+".offs"), I);
5244         continue;
5245       }
5246       
5247       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5248       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5249       Scale = ConstantExpr::getMul(OC, Scale);
5250       if (Constant *RC = dyn_cast<Constant>(Result))
5251         Result = ConstantExpr::getAdd(RC, Scale);
5252       else {
5253         // Emit an add instruction.
5254         Result = IC.InsertNewInstBefore(
5255            BinaryOperator::CreateAdd(Result, Scale,
5256                                      GEP->getName()+".offs"), I);
5257       }
5258       continue;
5259     }
5260     // Convert to correct type.
5261     if (Op->getType() != IntPtrTy) {
5262       if (Constant *OpC = dyn_cast<Constant>(Op))
5263         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5264       else
5265         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5266                                                  Op->getName()+".c"), I);
5267     }
5268     if (Size != 1) {
5269       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5270       if (Constant *OpC = dyn_cast<Constant>(Op))
5271         Op = ConstantExpr::getMul(OpC, Scale);
5272       else    // We'll let instcombine(mul) convert this to a shl if possible.
5273         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5274                                                   GEP->getName()+".idx"), I);
5275     }
5276
5277     // Emit an add instruction.
5278     if (isa<Constant>(Op) && isa<Constant>(Result))
5279       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5280                                     cast<Constant>(Result));
5281     else
5282       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5283                                                   GEP->getName()+".offs"), I);
5284   }
5285   return Result;
5286 }
5287
5288
5289 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5290 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5291 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5292 /// complex, and scales are involved.  The above expression would also be legal
5293 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5294 /// later form is less amenable to optimization though, and we are allowed to
5295 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5296 ///
5297 /// If we can't emit an optimized form for this expression, this returns null.
5298 /// 
5299 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5300                                           InstCombiner &IC) {
5301   TargetData &TD = IC.getTargetData();
5302   gep_type_iterator GTI = gep_type_begin(GEP);
5303
5304   // Check to see if this gep only has a single variable index.  If so, and if
5305   // any constant indices are a multiple of its scale, then we can compute this
5306   // in terms of the scale of the variable index.  For example, if the GEP
5307   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5308   // because the expression will cross zero at the same point.
5309   unsigned i, e = GEP->getNumOperands();
5310   int64_t Offset = 0;
5311   for (i = 1; i != e; ++i, ++GTI) {
5312     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5313       // Compute the aggregate offset of constant indices.
5314       if (CI->isZero()) continue;
5315
5316       // Handle a struct index, which adds its field offset to the pointer.
5317       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5318         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5319       } else {
5320         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5321         Offset += Size*CI->getSExtValue();
5322       }
5323     } else {
5324       // Found our variable index.
5325       break;
5326     }
5327   }
5328   
5329   // If there are no variable indices, we must have a constant offset, just
5330   // evaluate it the general way.
5331   if (i == e) return 0;
5332   
5333   Value *VariableIdx = GEP->getOperand(i);
5334   // Determine the scale factor of the variable element.  For example, this is
5335   // 4 if the variable index is into an array of i32.
5336   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5337   
5338   // Verify that there are no other variable indices.  If so, emit the hard way.
5339   for (++i, ++GTI; i != e; ++i, ++GTI) {
5340     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5341     if (!CI) return 0;
5342    
5343     // Compute the aggregate offset of constant indices.
5344     if (CI->isZero()) continue;
5345     
5346     // Handle a struct index, which adds its field offset to the pointer.
5347     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5348       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5349     } else {
5350       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5351       Offset += Size*CI->getSExtValue();
5352     }
5353   }
5354   
5355   // Okay, we know we have a single variable index, which must be a
5356   // pointer/array/vector index.  If there is no offset, life is simple, return
5357   // the index.
5358   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5359   if (Offset == 0) {
5360     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5361     // we don't need to bother extending: the extension won't affect where the
5362     // computation crosses zero.
5363     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5364       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5365                                   VariableIdx->getNameStart(), &I);
5366     return VariableIdx;
5367   }
5368   
5369   // Otherwise, there is an index.  The computation we will do will be modulo
5370   // the pointer size, so get it.
5371   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5372   
5373   Offset &= PtrSizeMask;
5374   VariableScale &= PtrSizeMask;
5375
5376   // To do this transformation, any constant index must be a multiple of the
5377   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5378   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5379   // multiple of the variable scale.
5380   int64_t NewOffs = Offset / (int64_t)VariableScale;
5381   if (Offset != NewOffs*(int64_t)VariableScale)
5382     return 0;
5383
5384   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5385   const Type *IntPtrTy = TD.getIntPtrType();
5386   if (VariableIdx->getType() != IntPtrTy)
5387     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5388                                               true /*SExt*/, 
5389                                               VariableIdx->getNameStart(), &I);
5390   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5391   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5392 }
5393
5394
5395 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5396 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5397 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5398                                        ICmpInst::Predicate Cond,
5399                                        Instruction &I) {
5400   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5401
5402   // Look through bitcasts.
5403   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5404     RHS = BCI->getOperand(0);
5405
5406   Value *PtrBase = GEPLHS->getOperand(0);
5407   if (PtrBase == RHS) {
5408     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5409     // This transformation (ignoring the base and scales) is valid because we
5410     // know pointers can't overflow.  See if we can output an optimized form.
5411     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5412     
5413     // If not, synthesize the offset the hard way.
5414     if (Offset == 0)
5415       Offset = EmitGEPOffset(GEPLHS, I, *this);
5416     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5417                         Constant::getNullValue(Offset->getType()));
5418   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5419     // If the base pointers are different, but the indices are the same, just
5420     // compare the base pointer.
5421     if (PtrBase != GEPRHS->getOperand(0)) {
5422       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5423       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5424                         GEPRHS->getOperand(0)->getType();
5425       if (IndicesTheSame)
5426         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5427           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5428             IndicesTheSame = false;
5429             break;
5430           }
5431
5432       // If all indices are the same, just compare the base pointers.
5433       if (IndicesTheSame)
5434         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5435                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5436
5437       // Otherwise, the base pointers are different and the indices are
5438       // different, bail out.
5439       return 0;
5440     }
5441
5442     // If one of the GEPs has all zero indices, recurse.
5443     bool AllZeros = true;
5444     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5445       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5446           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5447         AllZeros = false;
5448         break;
5449       }
5450     if (AllZeros)
5451       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5452                           ICmpInst::getSwappedPredicate(Cond), I);
5453
5454     // If the other GEP has all zero indices, recurse.
5455     AllZeros = true;
5456     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5457       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5458           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5459         AllZeros = false;
5460         break;
5461       }
5462     if (AllZeros)
5463       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5464
5465     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5466       // If the GEPs only differ by one index, compare it.
5467       unsigned NumDifferences = 0;  // Keep track of # differences.
5468       unsigned DiffOperand = 0;     // The operand that differs.
5469       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5470         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5471           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5472                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5473             // Irreconcilable differences.
5474             NumDifferences = 2;
5475             break;
5476           } else {
5477             if (NumDifferences++) break;
5478             DiffOperand = i;
5479           }
5480         }
5481
5482       if (NumDifferences == 0)   // SAME GEP?
5483         return ReplaceInstUsesWith(I, // No comparison is needed here.
5484                                    ConstantInt::get(Type::Int1Ty,
5485                                              ICmpInst::isTrueWhenEqual(Cond)));
5486
5487       else if (NumDifferences == 1) {
5488         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5489         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5490         // Make sure we do a signed comparison here.
5491         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5492       }
5493     }
5494
5495     // Only lower this if the icmp is the only user of the GEP or if we expect
5496     // the result to fold to a constant!
5497     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5498         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5499       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5500       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5501       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5502       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5503     }
5504   }
5505   return 0;
5506 }
5507
5508 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5509 ///
5510 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5511                                                 Instruction *LHSI,
5512                                                 Constant *RHSC) {
5513   if (!isa<ConstantFP>(RHSC)) return 0;
5514   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5515   
5516   // Get the width of the mantissa.  We don't want to hack on conversions that
5517   // might lose information from the integer, e.g. "i64 -> float"
5518   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5519   if (MantissaWidth == -1) return 0;  // Unknown.
5520   
5521   // Check to see that the input is converted from an integer type that is small
5522   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5523   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5524   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5525   
5526   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5527   if (isa<UIToFPInst>(LHSI))
5528     ++InputSize;
5529   
5530   // If the conversion would lose info, don't hack on this.
5531   if ((int)InputSize > MantissaWidth)
5532     return 0;
5533   
5534   // Otherwise, we can potentially simplify the comparison.  We know that it
5535   // will always come through as an integer value and we know the constant is
5536   // not a NAN (it would have been previously simplified).
5537   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5538   
5539   ICmpInst::Predicate Pred;
5540   switch (I.getPredicate()) {
5541   default: assert(0 && "Unexpected predicate!");
5542   case FCmpInst::FCMP_UEQ:
5543   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5544   case FCmpInst::FCMP_UGT:
5545   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5546   case FCmpInst::FCMP_UGE:
5547   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5548   case FCmpInst::FCMP_ULT:
5549   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5550   case FCmpInst::FCMP_ULE:
5551   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5552   case FCmpInst::FCMP_UNE:
5553   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5554   case FCmpInst::FCMP_ORD:
5555     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5556   case FCmpInst::FCMP_UNO:
5557     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5558   }
5559   
5560   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5561   
5562   // Now we know that the APFloat is a normal number, zero or inf.
5563   
5564   // See if the FP constant is too large for the integer.  For example,
5565   // comparing an i8 to 300.0.
5566   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5567   
5568   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5569   // and large values. 
5570   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5571   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5572                         APFloat::rmNearestTiesToEven);
5573   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5574     if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5575       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5576     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5577   }
5578   
5579   // See if the RHS value is < SignedMin.
5580   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5581   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5582                         APFloat::rmNearestTiesToEven);
5583   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5584     if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5585       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5586     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5587   }
5588
5589   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5590   // it may still be fractional.  See if it is fractional by casting the FP
5591   // value to the integer value and back, checking for equality.  Don't do this
5592   // for zero, because -0.0 is not fractional.
5593   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5594   if (!RHS.isZero() &&
5595       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5596     // If we had a comparison against a fractional value, we have to adjust
5597     // the compare predicate and sometimes the value.  RHSC is rounded towards
5598     // zero at this point.
5599     switch (Pred) {
5600     default: assert(0 && "Unexpected integer comparison!");
5601     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5602       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5603     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5604       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5605     case ICmpInst::ICMP_SLE:
5606       // (float)int <= 4.4   --> int <= 4
5607       // (float)int <= -4.4  --> int < -4
5608       if (RHS.isNegative())
5609         Pred = ICmpInst::ICMP_SLT;
5610       break;
5611     case ICmpInst::ICMP_SLT:
5612       // (float)int < -4.4   --> int < -4
5613       // (float)int < 4.4    --> int <= 4
5614       if (!RHS.isNegative())
5615         Pred = ICmpInst::ICMP_SLE;
5616       break;
5617     case ICmpInst::ICMP_SGT:
5618       // (float)int > 4.4    --> int > 4
5619       // (float)int > -4.4   --> int >= -4
5620       if (RHS.isNegative())
5621         Pred = ICmpInst::ICMP_SGE;
5622       break;
5623     case ICmpInst::ICMP_SGE:
5624       // (float)int >= -4.4   --> int >= -4
5625       // (float)int >= 4.4    --> int > 4
5626       if (!RHS.isNegative())
5627         Pred = ICmpInst::ICMP_SGT;
5628       break;
5629     }
5630   }
5631
5632   // Lower this FP comparison into an appropriate integer version of the
5633   // comparison.
5634   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5635 }
5636
5637 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5638   bool Changed = SimplifyCompare(I);
5639   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5640
5641   // Fold trivial predicates.
5642   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5643     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5644   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5645     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5646   
5647   // Simplify 'fcmp pred X, X'
5648   if (Op0 == Op1) {
5649     switch (I.getPredicate()) {
5650     default: assert(0 && "Unknown predicate!");
5651     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5652     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5653     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5654       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5655     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5656     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5657     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5658       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5659       
5660     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5661     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5662     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5663     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5664       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5665       I.setPredicate(FCmpInst::FCMP_UNO);
5666       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5667       return &I;
5668       
5669     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5670     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5671     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5672     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5673       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5674       I.setPredicate(FCmpInst::FCMP_ORD);
5675       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5676       return &I;
5677     }
5678   }
5679     
5680   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5681     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5682
5683   // Handle fcmp with constant RHS
5684   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5685     // If the constant is a nan, see if we can fold the comparison based on it.
5686     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5687       if (CFP->getValueAPF().isNaN()) {
5688         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5689           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5690         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5691                "Comparison must be either ordered or unordered!");
5692         // True if unordered.
5693         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5694       }
5695     }
5696     
5697     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5698       switch (LHSI->getOpcode()) {
5699       case Instruction::PHI:
5700         if (Instruction *NV = FoldOpIntoPhi(I))
5701           return NV;
5702         break;
5703       case Instruction::SIToFP:
5704       case Instruction::UIToFP:
5705         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5706           return NV;
5707         break;
5708       case Instruction::Select:
5709         // If either operand of the select is a constant, we can fold the
5710         // comparison into the select arms, which will cause one to be
5711         // constant folded and the select turned into a bitwise or.
5712         Value *Op1 = 0, *Op2 = 0;
5713         if (LHSI->hasOneUse()) {
5714           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5715             // Fold the known value into the constant operand.
5716             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5717             // Insert a new FCmp of the other select operand.
5718             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5719                                                       LHSI->getOperand(2), RHSC,
5720                                                       I.getName()), I);
5721           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5722             // Fold the known value into the constant operand.
5723             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5724             // Insert a new FCmp of the other select operand.
5725             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5726                                                       LHSI->getOperand(1), RHSC,
5727                                                       I.getName()), I);
5728           }
5729         }
5730
5731         if (Op1)
5732           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5733         break;
5734       }
5735   }
5736
5737   return Changed ? &I : 0;
5738 }
5739
5740 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5741   bool Changed = SimplifyCompare(I);
5742   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5743   const Type *Ty = Op0->getType();
5744
5745   // icmp X, X
5746   if (Op0 == Op1)
5747     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5748                                                    I.isTrueWhenEqual()));
5749
5750   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5751     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5752   
5753   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5754   // addresses never equal each other!  We already know that Op0 != Op1.
5755   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5756        isa<ConstantPointerNull>(Op0)) &&
5757       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5758        isa<ConstantPointerNull>(Op1)))
5759     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5760                                                    !I.isTrueWhenEqual()));
5761
5762   // icmp's with boolean values can always be turned into bitwise operations
5763   if (Ty == Type::Int1Ty) {
5764     switch (I.getPredicate()) {
5765     default: assert(0 && "Invalid icmp instruction!");
5766     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
5767       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5768       InsertNewInstBefore(Xor, I);
5769       return BinaryOperator::CreateNot(Xor);
5770     }
5771     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
5772       return BinaryOperator::CreateXor(Op0, Op1);
5773
5774     case ICmpInst::ICMP_UGT:
5775     case ICmpInst::ICMP_SGT:
5776       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
5777       // FALL THROUGH
5778     case ICmpInst::ICMP_ULT:
5779     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
5780       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5781       InsertNewInstBefore(Not, I);
5782       return BinaryOperator::CreateAnd(Not, Op1);
5783     }
5784     case ICmpInst::ICMP_UGE:
5785     case ICmpInst::ICMP_SGE:
5786       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
5787       // FALL THROUGH
5788     case ICmpInst::ICMP_ULE:
5789     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
5790       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5791       InsertNewInstBefore(Not, I);
5792       return BinaryOperator::CreateOr(Not, Op1);
5793     }
5794     }
5795   }
5796
5797   // See if we are doing a comparison between a constant and an instruction that
5798   // can be folded into the comparison.
5799   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5800       Value *A, *B;
5801     
5802     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5803     if (I.isEquality() && CI->isNullValue() &&
5804         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5805       // (icmp cond A B) if cond is equality
5806       return new ICmpInst(I.getPredicate(), A, B);
5807     }
5808     
5809     switch (I.getPredicate()) {
5810     default: break;
5811     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5812       if (CI->isMinValue(false))
5813         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5814       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5815         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5816       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5817         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5818       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5819       if (CI->isMinValue(true))
5820         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5821                             ConstantInt::getAllOnesValue(Op0->getType()));
5822           
5823       break;
5824
5825     case ICmpInst::ICMP_SLT:
5826       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5827         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5828       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5829         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5830       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5831         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5832       break;
5833
5834     case ICmpInst::ICMP_UGT:
5835       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5836         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5837       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5838         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5839       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5840         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5841         
5842       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5843       if (CI->isMaxValue(true))
5844         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5845                             ConstantInt::getNullValue(Op0->getType()));
5846       break;
5847
5848     case ICmpInst::ICMP_SGT:
5849       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5850         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5851       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5852         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5853       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5854         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5855       break;
5856
5857     case ICmpInst::ICMP_ULE:
5858       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5859         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5860       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5861         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5862       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5863         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5864       break;
5865
5866     case ICmpInst::ICMP_SLE:
5867       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5868         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5869       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5870         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5871       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5872         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5873       break;
5874
5875     case ICmpInst::ICMP_UGE:
5876       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5877         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5878       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5879         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5880       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5881         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5882       break;
5883
5884     case ICmpInst::ICMP_SGE:
5885       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5886         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5887       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5888         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5889       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5890         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5891       break;
5892     }
5893
5894     // If we still have a icmp le or icmp ge instruction, turn it into the
5895     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5896     // already been handled above, this requires little checking.
5897     //
5898     switch (I.getPredicate()) {
5899     default: break;
5900     case ICmpInst::ICMP_ULE: 
5901       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5902     case ICmpInst::ICMP_SLE:
5903       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5904     case ICmpInst::ICMP_UGE:
5905       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5906     case ICmpInst::ICMP_SGE:
5907       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5908     }
5909     
5910     // See if we can fold the comparison based on bits known to be zero or one
5911     // in the input.  If this comparison is a normal comparison, it demands all
5912     // bits, if it is a sign bit comparison, it only demands the sign bit.
5913     
5914     bool UnusedBit;
5915     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5916     
5917     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5918     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5919     if (SimplifyDemandedBits(Op0, 
5920                              isSignBit ? APInt::getSignBit(BitWidth)
5921                                        : APInt::getAllOnesValue(BitWidth),
5922                              KnownZero, KnownOne, 0))
5923       return &I;
5924         
5925     // Given the known and unknown bits, compute a range that the LHS could be
5926     // in.
5927     if ((KnownOne | KnownZero) != 0) {
5928       // Compute the Min, Max and RHS values based on the known bits. For the
5929       // EQ and NE we use unsigned values.
5930       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5931       const APInt& RHSVal = CI->getValue();
5932       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5933         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5934                                                Max);
5935       } else {
5936         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5937                                                  Max);
5938       }
5939       switch (I.getPredicate()) {  // LE/GE have been folded already.
5940       default: assert(0 && "Unknown icmp opcode!");
5941       case ICmpInst::ICMP_EQ:
5942         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5943           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5944         break;
5945       case ICmpInst::ICMP_NE:
5946         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5947           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5948         break;
5949       case ICmpInst::ICMP_ULT:
5950         if (Max.ult(RHSVal))
5951           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5952         if (Min.uge(RHSVal))
5953           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5954         break;
5955       case ICmpInst::ICMP_UGT:
5956         if (Min.ugt(RHSVal))
5957           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5958         if (Max.ule(RHSVal))
5959           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5960         break;
5961       case ICmpInst::ICMP_SLT:
5962         if (Max.slt(RHSVal))
5963           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5964         if (Min.sgt(RHSVal))
5965           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5966         break;
5967       case ICmpInst::ICMP_SGT: 
5968         if (Min.sgt(RHSVal))
5969           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5970         if (Max.sle(RHSVal))
5971           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5972         break;
5973       }
5974     }
5975           
5976     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5977     // instruction, see if that instruction also has constants so that the 
5978     // instruction can be folded into the icmp 
5979     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5980       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5981         return Res;
5982   }
5983
5984   // Handle icmp with constant (but not simple integer constant) RHS
5985   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5986     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5987       switch (LHSI->getOpcode()) {
5988       case Instruction::GetElementPtr:
5989         if (RHSC->isNullValue()) {
5990           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5991           bool isAllZeros = true;
5992           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5993             if (!isa<Constant>(LHSI->getOperand(i)) ||
5994                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5995               isAllZeros = false;
5996               break;
5997             }
5998           if (isAllZeros)
5999             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6000                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6001         }
6002         break;
6003
6004       case Instruction::PHI:
6005         if (Instruction *NV = FoldOpIntoPhi(I))
6006           return NV;
6007         break;
6008       case Instruction::Select: {
6009         // If either operand of the select is a constant, we can fold the
6010         // comparison into the select arms, which will cause one to be
6011         // constant folded and the select turned into a bitwise or.
6012         Value *Op1 = 0, *Op2 = 0;
6013         if (LHSI->hasOneUse()) {
6014           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6015             // Fold the known value into the constant operand.
6016             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6017             // Insert a new ICmp of the other select operand.
6018             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6019                                                    LHSI->getOperand(2), RHSC,
6020                                                    I.getName()), I);
6021           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6022             // Fold the known value into the constant operand.
6023             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6024             // Insert a new ICmp of the other select operand.
6025             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6026                                                    LHSI->getOperand(1), RHSC,
6027                                                    I.getName()), I);
6028           }
6029         }
6030
6031         if (Op1)
6032           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6033         break;
6034       }
6035       case Instruction::Malloc:
6036         // If we have (malloc != null), and if the malloc has a single use, we
6037         // can assume it is successful and remove the malloc.
6038         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6039           AddToWorkList(LHSI);
6040           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6041                                                          !I.isTrueWhenEqual()));
6042         }
6043         break;
6044       }
6045   }
6046
6047   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6048   if (User *GEP = dyn_castGetElementPtr(Op0))
6049     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6050       return NI;
6051   if (User *GEP = dyn_castGetElementPtr(Op1))
6052     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6053                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6054       return NI;
6055
6056   // Test to see if the operands of the icmp are casted versions of other
6057   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6058   // now.
6059   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6060     if (isa<PointerType>(Op0->getType()) && 
6061         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6062       // We keep moving the cast from the left operand over to the right
6063       // operand, where it can often be eliminated completely.
6064       Op0 = CI->getOperand(0);
6065
6066       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6067       // so eliminate it as well.
6068       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6069         Op1 = CI2->getOperand(0);
6070
6071       // If Op1 is a constant, we can fold the cast into the constant.
6072       if (Op0->getType() != Op1->getType()) {
6073         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6074           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6075         } else {
6076           // Otherwise, cast the RHS right before the icmp
6077           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6078         }
6079       }
6080       return new ICmpInst(I.getPredicate(), Op0, Op1);
6081     }
6082   }
6083   
6084   if (isa<CastInst>(Op0)) {
6085     // Handle the special case of: icmp (cast bool to X), <cst>
6086     // This comes up when you have code like
6087     //   int X = A < B;
6088     //   if (X) ...
6089     // For generality, we handle any zero-extension of any operand comparison
6090     // with a constant or another cast from the same type.
6091     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6092       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6093         return R;
6094   }
6095   
6096   // ~x < ~y --> y < x
6097   { Value *A, *B;
6098     if (match(Op0, m_Not(m_Value(A))) &&
6099         match(Op1, m_Not(m_Value(B))))
6100       return new ICmpInst(I.getPredicate(), B, A);
6101   }
6102   
6103   if (I.isEquality()) {
6104     Value *A, *B, *C, *D;
6105     
6106     // -x == -y --> x == y
6107     if (match(Op0, m_Neg(m_Value(A))) &&
6108         match(Op1, m_Neg(m_Value(B))))
6109       return new ICmpInst(I.getPredicate(), A, B);
6110     
6111     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6112       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6113         Value *OtherVal = A == Op1 ? B : A;
6114         return new ICmpInst(I.getPredicate(), OtherVal,
6115                             Constant::getNullValue(A->getType()));
6116       }
6117
6118       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6119         // A^c1 == C^c2 --> A == C^(c1^c2)
6120         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6121           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6122             if (Op1->hasOneUse()) {
6123               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6124               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6125               return new ICmpInst(I.getPredicate(), A,
6126                                   InsertNewInstBefore(Xor, I));
6127             }
6128         
6129         // A^B == A^D -> B == D
6130         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6131         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6132         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6133         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6134       }
6135     }
6136     
6137     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6138         (A == Op0 || B == Op0)) {
6139       // A == (A^B)  ->  B == 0
6140       Value *OtherVal = A == Op0 ? B : A;
6141       return new ICmpInst(I.getPredicate(), OtherVal,
6142                           Constant::getNullValue(A->getType()));
6143     }
6144     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
6145       // (A-B) == A  ->  B == 0
6146       return new ICmpInst(I.getPredicate(), B,
6147                           Constant::getNullValue(B->getType()));
6148     }
6149     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
6150       // A == (A-B)  ->  B == 0
6151       return new ICmpInst(I.getPredicate(), B,
6152                           Constant::getNullValue(B->getType()));
6153     }
6154     
6155     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6156     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6157         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6158         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6159       Value *X = 0, *Y = 0, *Z = 0;
6160       
6161       if (A == C) {
6162         X = B; Y = D; Z = A;
6163       } else if (A == D) {
6164         X = B; Y = C; Z = A;
6165       } else if (B == C) {
6166         X = A; Y = D; Z = B;
6167       } else if (B == D) {
6168         X = A; Y = C; Z = B;
6169       }
6170       
6171       if (X) {   // Build (X^Y) & Z
6172         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6173         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6174         I.setOperand(0, Op1);
6175         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6176         return &I;
6177       }
6178     }
6179   }
6180   return Changed ? &I : 0;
6181 }
6182
6183
6184 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6185 /// and CmpRHS are both known to be integer constants.
6186 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6187                                           ConstantInt *DivRHS) {
6188   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6189   const APInt &CmpRHSV = CmpRHS->getValue();
6190   
6191   // FIXME: If the operand types don't match the type of the divide 
6192   // then don't attempt this transform. The code below doesn't have the
6193   // logic to deal with a signed divide and an unsigned compare (and
6194   // vice versa). This is because (x /s C1) <s C2  produces different 
6195   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6196   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6197   // work. :(  The if statement below tests that condition and bails 
6198   // if it finds it. 
6199   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6200   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6201     return 0;
6202   if (DivRHS->isZero())
6203     return 0; // The ProdOV computation fails on divide by zero.
6204
6205   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6206   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6207   // C2 (CI). By solving for X we can turn this into a range check 
6208   // instead of computing a divide. 
6209   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6210
6211   // Determine if the product overflows by seeing if the product is
6212   // not equal to the divide. Make sure we do the same kind of divide
6213   // as in the LHS instruction that we're folding. 
6214   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6215                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6216
6217   // Get the ICmp opcode
6218   ICmpInst::Predicate Pred = ICI.getPredicate();
6219
6220   // Figure out the interval that is being checked.  For example, a comparison
6221   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6222   // Compute this interval based on the constants involved and the signedness of
6223   // the compare/divide.  This computes a half-open interval, keeping track of
6224   // whether either value in the interval overflows.  After analysis each
6225   // overflow variable is set to 0 if it's corresponding bound variable is valid
6226   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6227   int LoOverflow = 0, HiOverflow = 0;
6228   ConstantInt *LoBound = 0, *HiBound = 0;
6229   
6230   
6231   if (!DivIsSigned) {  // udiv
6232     // e.g. X/5 op 3  --> [15, 20)
6233     LoBound = Prod;
6234     HiOverflow = LoOverflow = ProdOV;
6235     if (!HiOverflow)
6236       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6237   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6238     if (CmpRHSV == 0) {       // (X / pos) op 0
6239       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6240       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6241       HiBound = DivRHS;
6242     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6243       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6244       HiOverflow = LoOverflow = ProdOV;
6245       if (!HiOverflow)
6246         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6247     } else {                       // (X / pos) op neg
6248       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6249       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6250       LoOverflow = AddWithOverflow(LoBound, Prod,
6251                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
6252       HiBound = AddOne(Prod);
6253       HiOverflow = ProdOV ? -1 : 0;
6254     }
6255   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6256     if (CmpRHSV == 0) {       // (X / neg) op 0
6257       // e.g. X/-5 op 0  --> [-4, 5)
6258       LoBound = AddOne(DivRHS);
6259       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6260       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6261         HiOverflow = 1;            // [INTMIN+1, overflow)
6262         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6263       }
6264     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6265       // e.g. X/-5 op 3  --> [-19, -14)
6266       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6267       if (!LoOverflow)
6268         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
6269       HiBound = AddOne(Prod);
6270     } else {                       // (X / neg) op neg
6271       // e.g. X/-5 op -3  --> [15, 20)
6272       LoBound = Prod;
6273       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
6274       HiBound = Subtract(Prod, DivRHS);
6275     }
6276     
6277     // Dividing by a negative swaps the condition.  LT <-> GT
6278     Pred = ICmpInst::getSwappedPredicate(Pred);
6279   }
6280
6281   Value *X = DivI->getOperand(0);
6282   switch (Pred) {
6283   default: assert(0 && "Unhandled icmp opcode!");
6284   case ICmpInst::ICMP_EQ:
6285     if (LoOverflow && HiOverflow)
6286       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6287     else if (HiOverflow)
6288       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6289                           ICmpInst::ICMP_UGE, X, LoBound);
6290     else if (LoOverflow)
6291       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6292                           ICmpInst::ICMP_ULT, X, HiBound);
6293     else
6294       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6295   case ICmpInst::ICMP_NE:
6296     if (LoOverflow && HiOverflow)
6297       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6298     else if (HiOverflow)
6299       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6300                           ICmpInst::ICMP_ULT, X, LoBound);
6301     else if (LoOverflow)
6302       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6303                           ICmpInst::ICMP_UGE, X, HiBound);
6304     else
6305       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6306   case ICmpInst::ICMP_ULT:
6307   case ICmpInst::ICMP_SLT:
6308     if (LoOverflow == +1)   // Low bound is greater than input range.
6309       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6310     if (LoOverflow == -1)   // Low bound is less than input range.
6311       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6312     return new ICmpInst(Pred, X, LoBound);
6313   case ICmpInst::ICMP_UGT:
6314   case ICmpInst::ICMP_SGT:
6315     if (HiOverflow == +1)       // High bound greater than input range.
6316       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6317     else if (HiOverflow == -1)  // High bound less than input range.
6318       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6319     if (Pred == ICmpInst::ICMP_UGT)
6320       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6321     else
6322       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6323   }
6324 }
6325
6326
6327 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6328 ///
6329 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6330                                                           Instruction *LHSI,
6331                                                           ConstantInt *RHS) {
6332   const APInt &RHSV = RHS->getValue();
6333   
6334   switch (LHSI->getOpcode()) {
6335   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6336     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6337       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6338       // fold the xor.
6339       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6340           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6341         Value *CompareVal = LHSI->getOperand(0);
6342         
6343         // If the sign bit of the XorCST is not set, there is no change to
6344         // the operation, just stop using the Xor.
6345         if (!XorCST->getValue().isNegative()) {
6346           ICI.setOperand(0, CompareVal);
6347           AddToWorkList(LHSI);
6348           return &ICI;
6349         }
6350         
6351         // Was the old condition true if the operand is positive?
6352         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6353         
6354         // If so, the new one isn't.
6355         isTrueIfPositive ^= true;
6356         
6357         if (isTrueIfPositive)
6358           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6359         else
6360           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6361       }
6362     }
6363     break;
6364   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6365     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6366         LHSI->getOperand(0)->hasOneUse()) {
6367       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6368       
6369       // If the LHS is an AND of a truncating cast, we can widen the
6370       // and/compare to be the input width without changing the value
6371       // produced, eliminating a cast.
6372       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6373         // We can do this transformation if either the AND constant does not
6374         // have its sign bit set or if it is an equality comparison. 
6375         // Extending a relational comparison when we're checking the sign
6376         // bit would not work.
6377         if (Cast->hasOneUse() &&
6378             (ICI.isEquality() ||
6379              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6380           uint32_t BitWidth = 
6381             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6382           APInt NewCST = AndCST->getValue();
6383           NewCST.zext(BitWidth);
6384           APInt NewCI = RHSV;
6385           NewCI.zext(BitWidth);
6386           Instruction *NewAnd = 
6387             BinaryOperator::CreateAnd(Cast->getOperand(0),
6388                                       ConstantInt::get(NewCST),LHSI->getName());
6389           InsertNewInstBefore(NewAnd, ICI);
6390           return new ICmpInst(ICI.getPredicate(), NewAnd,
6391                               ConstantInt::get(NewCI));
6392         }
6393       }
6394       
6395       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6396       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6397       // happens a LOT in code produced by the C front-end, for bitfield
6398       // access.
6399       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6400       if (Shift && !Shift->isShift())
6401         Shift = 0;
6402       
6403       ConstantInt *ShAmt;
6404       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6405       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6406       const Type *AndTy = AndCST->getType();          // Type of the and.
6407       
6408       // We can fold this as long as we can't shift unknown bits
6409       // into the mask.  This can only happen with signed shift
6410       // rights, as they sign-extend.
6411       if (ShAmt) {
6412         bool CanFold = Shift->isLogicalShift();
6413         if (!CanFold) {
6414           // To test for the bad case of the signed shr, see if any
6415           // of the bits shifted in could be tested after the mask.
6416           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6417           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6418           
6419           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6420           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6421                AndCST->getValue()) == 0)
6422             CanFold = true;
6423         }
6424         
6425         if (CanFold) {
6426           Constant *NewCst;
6427           if (Shift->getOpcode() == Instruction::Shl)
6428             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6429           else
6430             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6431           
6432           // Check to see if we are shifting out any of the bits being
6433           // compared.
6434           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6435             // If we shifted bits out, the fold is not going to work out.
6436             // As a special case, check to see if this means that the
6437             // result is always true or false now.
6438             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6439               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6440             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6441               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6442           } else {
6443             ICI.setOperand(1, NewCst);
6444             Constant *NewAndCST;
6445             if (Shift->getOpcode() == Instruction::Shl)
6446               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6447             else
6448               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6449             LHSI->setOperand(1, NewAndCST);
6450             LHSI->setOperand(0, Shift->getOperand(0));
6451             AddToWorkList(Shift); // Shift is dead.
6452             AddUsesToWorkList(ICI);
6453             return &ICI;
6454           }
6455         }
6456       }
6457       
6458       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6459       // preferable because it allows the C<<Y expression to be hoisted out
6460       // of a loop if Y is invariant and X is not.
6461       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6462           ICI.isEquality() && !Shift->isArithmeticShift() &&
6463           isa<Instruction>(Shift->getOperand(0))) {
6464         // Compute C << Y.
6465         Value *NS;
6466         if (Shift->getOpcode() == Instruction::LShr) {
6467           NS = BinaryOperator::CreateShl(AndCST, 
6468                                          Shift->getOperand(1), "tmp");
6469         } else {
6470           // Insert a logical shift.
6471           NS = BinaryOperator::CreateLShr(AndCST,
6472                                           Shift->getOperand(1), "tmp");
6473         }
6474         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6475         
6476         // Compute X & (C << Y).
6477         Instruction *NewAnd = 
6478           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6479         InsertNewInstBefore(NewAnd, ICI);
6480         
6481         ICI.setOperand(0, NewAnd);
6482         return &ICI;
6483       }
6484     }
6485     break;
6486     
6487   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6488     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6489     if (!ShAmt) break;
6490     
6491     uint32_t TypeBits = RHSV.getBitWidth();
6492     
6493     // Check that the shift amount is in range.  If not, don't perform
6494     // undefined shifts.  When the shift is visited it will be
6495     // simplified.
6496     if (ShAmt->uge(TypeBits))
6497       break;
6498     
6499     if (ICI.isEquality()) {
6500       // If we are comparing against bits always shifted out, the
6501       // comparison cannot succeed.
6502       Constant *Comp =
6503         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6504       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6505         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6506         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6507         return ReplaceInstUsesWith(ICI, Cst);
6508       }
6509       
6510       if (LHSI->hasOneUse()) {
6511         // Otherwise strength reduce the shift into an and.
6512         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6513         Constant *Mask =
6514           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6515         
6516         Instruction *AndI =
6517           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6518                                     Mask, LHSI->getName()+".mask");
6519         Value *And = InsertNewInstBefore(AndI, ICI);
6520         return new ICmpInst(ICI.getPredicate(), And,
6521                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6522       }
6523     }
6524     
6525     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6526     bool TrueIfSigned = false;
6527     if (LHSI->hasOneUse() &&
6528         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6529       // (X << 31) <s 0  --> (X&1) != 0
6530       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6531                                            (TypeBits-ShAmt->getZExtValue()-1));
6532       Instruction *AndI =
6533         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6534                                   Mask, LHSI->getName()+".mask");
6535       Value *And = InsertNewInstBefore(AndI, ICI);
6536       
6537       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6538                           And, Constant::getNullValue(And->getType()));
6539     }
6540     break;
6541   }
6542     
6543   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6544   case Instruction::AShr: {
6545     // Only handle equality comparisons of shift-by-constant.
6546     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6547     if (!ShAmt || !ICI.isEquality()) break;
6548
6549     // Check that the shift amount is in range.  If not, don't perform
6550     // undefined shifts.  When the shift is visited it will be
6551     // simplified.
6552     uint32_t TypeBits = RHSV.getBitWidth();
6553     if (ShAmt->uge(TypeBits))
6554       break;
6555     
6556     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6557       
6558     // If we are comparing against bits always shifted out, the
6559     // comparison cannot succeed.
6560     APInt Comp = RHSV << ShAmtVal;
6561     if (LHSI->getOpcode() == Instruction::LShr)
6562       Comp = Comp.lshr(ShAmtVal);
6563     else
6564       Comp = Comp.ashr(ShAmtVal);
6565     
6566     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6567       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6568       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6569       return ReplaceInstUsesWith(ICI, Cst);
6570     }
6571     
6572     // Otherwise, check to see if the bits shifted out are known to be zero.
6573     // If so, we can compare against the unshifted value:
6574     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6575     if (LHSI->hasOneUse() &&
6576         MaskedValueIsZero(LHSI->getOperand(0), 
6577                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6578       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6579                           ConstantExpr::getShl(RHS, ShAmt));
6580     }
6581       
6582     if (LHSI->hasOneUse()) {
6583       // Otherwise strength reduce the shift into an and.
6584       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6585       Constant *Mask = ConstantInt::get(Val);
6586       
6587       Instruction *AndI =
6588         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6589                                   Mask, LHSI->getName()+".mask");
6590       Value *And = InsertNewInstBefore(AndI, ICI);
6591       return new ICmpInst(ICI.getPredicate(), And,
6592                           ConstantExpr::getShl(RHS, ShAmt));
6593     }
6594     break;
6595   }
6596     
6597   case Instruction::SDiv:
6598   case Instruction::UDiv:
6599     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6600     // Fold this div into the comparison, producing a range check. 
6601     // Determine, based on the divide type, what the range is being 
6602     // checked.  If there is an overflow on the low or high side, remember 
6603     // it, otherwise compute the range [low, hi) bounding the new value.
6604     // See: InsertRangeTest above for the kinds of replacements possible.
6605     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6606       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6607                                           DivRHS))
6608         return R;
6609     break;
6610
6611   case Instruction::Add:
6612     // Fold: icmp pred (add, X, C1), C2
6613
6614     if (!ICI.isEquality()) {
6615       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6616       if (!LHSC) break;
6617       const APInt &LHSV = LHSC->getValue();
6618
6619       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6620                             .subtract(LHSV);
6621
6622       if (ICI.isSignedPredicate()) {
6623         if (CR.getLower().isSignBit()) {
6624           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6625                               ConstantInt::get(CR.getUpper()));
6626         } else if (CR.getUpper().isSignBit()) {
6627           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6628                               ConstantInt::get(CR.getLower()));
6629         }
6630       } else {
6631         if (CR.getLower().isMinValue()) {
6632           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6633                               ConstantInt::get(CR.getUpper()));
6634         } else if (CR.getUpper().isMinValue()) {
6635           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6636                               ConstantInt::get(CR.getLower()));
6637         }
6638       }
6639     }
6640     break;
6641   }
6642   
6643   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6644   if (ICI.isEquality()) {
6645     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6646     
6647     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6648     // the second operand is a constant, simplify a bit.
6649     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6650       switch (BO->getOpcode()) {
6651       case Instruction::SRem:
6652         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6653         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6654           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6655           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6656             Instruction *NewRem =
6657               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6658                                          BO->getName());
6659             InsertNewInstBefore(NewRem, ICI);
6660             return new ICmpInst(ICI.getPredicate(), NewRem, 
6661                                 Constant::getNullValue(BO->getType()));
6662           }
6663         }
6664         break;
6665       case Instruction::Add:
6666         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6667         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6668           if (BO->hasOneUse())
6669             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6670                                 Subtract(RHS, BOp1C));
6671         } else if (RHSV == 0) {
6672           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6673           // efficiently invertible, or if the add has just this one use.
6674           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6675           
6676           if (Value *NegVal = dyn_castNegVal(BOp1))
6677             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6678           else if (Value *NegVal = dyn_castNegVal(BOp0))
6679             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6680           else if (BO->hasOneUse()) {
6681             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6682             InsertNewInstBefore(Neg, ICI);
6683             Neg->takeName(BO);
6684             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6685           }
6686         }
6687         break;
6688       case Instruction::Xor:
6689         // For the xor case, we can xor two constants together, eliminating
6690         // the explicit xor.
6691         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6692           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6693                               ConstantExpr::getXor(RHS, BOC));
6694         
6695         // FALLTHROUGH
6696       case Instruction::Sub:
6697         // Replace (([sub|xor] A, B) != 0) with (A != B)
6698         if (RHSV == 0)
6699           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6700                               BO->getOperand(1));
6701         break;
6702         
6703       case Instruction::Or:
6704         // If bits are being or'd in that are not present in the constant we
6705         // are comparing against, then the comparison could never succeed!
6706         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6707           Constant *NotCI = ConstantExpr::getNot(RHS);
6708           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6709             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6710                                                              isICMP_NE));
6711         }
6712         break;
6713         
6714       case Instruction::And:
6715         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6716           // If bits are being compared against that are and'd out, then the
6717           // comparison can never succeed!
6718           if ((RHSV & ~BOC->getValue()) != 0)
6719             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6720                                                              isICMP_NE));
6721           
6722           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6723           if (RHS == BOC && RHSV.isPowerOf2())
6724             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6725                                 ICmpInst::ICMP_NE, LHSI,
6726                                 Constant::getNullValue(RHS->getType()));
6727           
6728           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6729           if (isSignBit(BOC)) {
6730             Value *X = BO->getOperand(0);
6731             Constant *Zero = Constant::getNullValue(X->getType());
6732             ICmpInst::Predicate pred = isICMP_NE ? 
6733               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6734             return new ICmpInst(pred, X, Zero);
6735           }
6736           
6737           // ((X & ~7) == 0) --> X < 8
6738           if (RHSV == 0 && isHighOnes(BOC)) {
6739             Value *X = BO->getOperand(0);
6740             Constant *NegX = ConstantExpr::getNeg(BOC);
6741             ICmpInst::Predicate pred = isICMP_NE ? 
6742               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6743             return new ICmpInst(pred, X, NegX);
6744           }
6745         }
6746       default: break;
6747       }
6748     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6749       // Handle icmp {eq|ne} <intrinsic>, intcst.
6750       if (II->getIntrinsicID() == Intrinsic::bswap) {
6751         AddToWorkList(II);
6752         ICI.setOperand(0, II->getOperand(1));
6753         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6754         return &ICI;
6755       }
6756     }
6757   } else {  // Not a ICMP_EQ/ICMP_NE
6758             // If the LHS is a cast from an integral value of the same size, 
6759             // then since we know the RHS is a constant, try to simlify.
6760     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6761       Value *CastOp = Cast->getOperand(0);
6762       const Type *SrcTy = CastOp->getType();
6763       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6764       if (SrcTy->isInteger() && 
6765           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6766         // If this is an unsigned comparison, try to make the comparison use
6767         // smaller constant values.
6768         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6769           // X u< 128 => X s> -1
6770           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6771                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6772         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6773                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6774           // X u> 127 => X s< 0
6775           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6776                               Constant::getNullValue(SrcTy));
6777         }
6778       }
6779     }
6780   }
6781   return 0;
6782 }
6783
6784 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6785 /// We only handle extending casts so far.
6786 ///
6787 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6788   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6789   Value *LHSCIOp        = LHSCI->getOperand(0);
6790   const Type *SrcTy     = LHSCIOp->getType();
6791   const Type *DestTy    = LHSCI->getType();
6792   Value *RHSCIOp;
6793
6794   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6795   // integer type is the same size as the pointer type.
6796   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6797       getTargetData().getPointerSizeInBits() == 
6798          cast<IntegerType>(DestTy)->getBitWidth()) {
6799     Value *RHSOp = 0;
6800     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6801       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6802     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6803       RHSOp = RHSC->getOperand(0);
6804       // If the pointer types don't match, insert a bitcast.
6805       if (LHSCIOp->getType() != RHSOp->getType())
6806         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6807     }
6808
6809     if (RHSOp)
6810       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6811   }
6812   
6813   // The code below only handles extension cast instructions, so far.
6814   // Enforce this.
6815   if (LHSCI->getOpcode() != Instruction::ZExt &&
6816       LHSCI->getOpcode() != Instruction::SExt)
6817     return 0;
6818
6819   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6820   bool isSignedCmp = ICI.isSignedPredicate();
6821
6822   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6823     // Not an extension from the same type?
6824     RHSCIOp = CI->getOperand(0);
6825     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6826       return 0;
6827     
6828     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6829     // and the other is a zext), then we can't handle this.
6830     if (CI->getOpcode() != LHSCI->getOpcode())
6831       return 0;
6832
6833     // Deal with equality cases early.
6834     if (ICI.isEquality())
6835       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6836
6837     // A signed comparison of sign extended values simplifies into a
6838     // signed comparison.
6839     if (isSignedCmp && isSignedExt)
6840       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6841
6842     // The other three cases all fold into an unsigned comparison.
6843     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6844   }
6845
6846   // If we aren't dealing with a constant on the RHS, exit early
6847   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6848   if (!CI)
6849     return 0;
6850
6851   // Compute the constant that would happen if we truncated to SrcTy then
6852   // reextended to DestTy.
6853   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6854   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6855
6856   // If the re-extended constant didn't change...
6857   if (Res2 == CI) {
6858     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6859     // For example, we might have:
6860     //    %A = sext short %X to uint
6861     //    %B = icmp ugt uint %A, 1330
6862     // It is incorrect to transform this into 
6863     //    %B = icmp ugt short %X, 1330 
6864     // because %A may have negative value. 
6865     //
6866     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6867     // OR operation is EQ/NE.
6868     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6869       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6870     else
6871       return 0;
6872   }
6873
6874   // The re-extended constant changed so the constant cannot be represented 
6875   // in the shorter type. Consequently, we cannot emit a simple comparison.
6876
6877   // First, handle some easy cases. We know the result cannot be equal at this
6878   // point so handle the ICI.isEquality() cases
6879   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6880     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6881   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6882     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6883
6884   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6885   // should have been folded away previously and not enter in here.
6886   Value *Result;
6887   if (isSignedCmp) {
6888     // We're performing a signed comparison.
6889     if (cast<ConstantInt>(CI)->getValue().isNegative())
6890       Result = ConstantInt::getFalse();          // X < (small) --> false
6891     else
6892       Result = ConstantInt::getTrue();           // X < (large) --> true
6893   } else {
6894     // We're performing an unsigned comparison.
6895     if (isSignedExt) {
6896       // We're performing an unsigned comp with a sign extended value.
6897       // This is true if the input is >= 0. [aka >s -1]
6898       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6899       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6900                                    NegOne, ICI.getName()), ICI);
6901     } else {
6902       // Unsigned extend & unsigned compare -> always true.
6903       Result = ConstantInt::getTrue();
6904     }
6905   }
6906
6907   // Finally, return the value computed.
6908   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6909       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6910     return ReplaceInstUsesWith(ICI, Result);
6911   } else {
6912     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6913             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6914            "ICmp should be folded!");
6915     if (Constant *CI = dyn_cast<Constant>(Result))
6916       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6917     else
6918       return BinaryOperator::CreateNot(Result);
6919   }
6920 }
6921
6922 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6923   return commonShiftTransforms(I);
6924 }
6925
6926 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6927   return commonShiftTransforms(I);
6928 }
6929
6930 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6931   if (Instruction *R = commonShiftTransforms(I))
6932     return R;
6933   
6934   Value *Op0 = I.getOperand(0);
6935   
6936   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6937   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6938     if (CSI->isAllOnesValue())
6939       return ReplaceInstUsesWith(I, CSI);
6940   
6941   // See if we can turn a signed shr into an unsigned shr.
6942   if (MaskedValueIsZero(Op0, 
6943                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6944     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6945   
6946   return 0;
6947 }
6948
6949 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6950   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6951   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6952
6953   // shl X, 0 == X and shr X, 0 == X
6954   // shl 0, X == 0 and shr 0, X == 0
6955   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6956       Op0 == Constant::getNullValue(Op0->getType()))
6957     return ReplaceInstUsesWith(I, Op0);
6958   
6959   if (isa<UndefValue>(Op0)) {            
6960     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6961       return ReplaceInstUsesWith(I, Op0);
6962     else                                    // undef << X -> 0, undef >>u X -> 0
6963       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6964   }
6965   if (isa<UndefValue>(Op1)) {
6966     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6967       return ReplaceInstUsesWith(I, Op0);          
6968     else                                     // X << undef, X >>u undef -> 0
6969       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6970   }
6971
6972   // Try to fold constant and into select arguments.
6973   if (isa<Constant>(Op0))
6974     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6975       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6976         return R;
6977
6978   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6979     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6980       return Res;
6981   return 0;
6982 }
6983
6984 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6985                                                BinaryOperator &I) {
6986   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6987
6988   // See if we can simplify any instructions used by the instruction whose sole 
6989   // purpose is to compute bits we don't care about.
6990   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6991   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6992   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6993                            KnownZero, KnownOne))
6994     return &I;
6995   
6996   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6997   // of a signed value.
6998   //
6999   if (Op1->uge(TypeBits)) {
7000     if (I.getOpcode() != Instruction::AShr)
7001       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7002     else {
7003       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7004       return &I;
7005     }
7006   }
7007   
7008   // ((X*C1) << C2) == (X * (C1 << C2))
7009   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7010     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7011       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7012         return BinaryOperator::CreateMul(BO->getOperand(0),
7013                                          ConstantExpr::getShl(BOOp, Op1));
7014   
7015   // Try to fold constant and into select arguments.
7016   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7017     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7018       return R;
7019   if (isa<PHINode>(Op0))
7020     if (Instruction *NV = FoldOpIntoPhi(I))
7021       return NV;
7022   
7023   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7024   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7025     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7026     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7027     // place.  Don't try to do this transformation in this case.  Also, we
7028     // require that the input operand is a shift-by-constant so that we have
7029     // confidence that the shifts will get folded together.  We could do this
7030     // xform in more cases, but it is unlikely to be profitable.
7031     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7032         isa<ConstantInt>(TrOp->getOperand(1))) {
7033       // Okay, we'll do this xform.  Make the shift of shift.
7034       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7035       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7036                                                 I.getName());
7037       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7038
7039       // For logical shifts, the truncation has the effect of making the high
7040       // part of the register be zeros.  Emulate this by inserting an AND to
7041       // clear the top bits as needed.  This 'and' will usually be zapped by
7042       // other xforms later if dead.
7043       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7044       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7045       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7046       
7047       // The mask we constructed says what the trunc would do if occurring
7048       // between the shifts.  We want to know the effect *after* the second
7049       // shift.  We know that it is a logical shift by a constant, so adjust the
7050       // mask as appropriate.
7051       if (I.getOpcode() == Instruction::Shl)
7052         MaskV <<= Op1->getZExtValue();
7053       else {
7054         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7055         MaskV = MaskV.lshr(Op1->getZExtValue());
7056       }
7057
7058       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7059                                                    TI->getName());
7060       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7061
7062       // Return the value truncated to the interesting size.
7063       return new TruncInst(And, I.getType());
7064     }
7065   }
7066   
7067   if (Op0->hasOneUse()) {
7068     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7069       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7070       Value *V1, *V2;
7071       ConstantInt *CC;
7072       switch (Op0BO->getOpcode()) {
7073         default: break;
7074         case Instruction::Add:
7075         case Instruction::And:
7076         case Instruction::Or:
7077         case Instruction::Xor: {
7078           // These operators commute.
7079           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7080           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7081               match(Op0BO->getOperand(1),
7082                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7083             Instruction *YS = BinaryOperator::CreateShl(
7084                                             Op0BO->getOperand(0), Op1,
7085                                             Op0BO->getName());
7086             InsertNewInstBefore(YS, I); // (Y << C)
7087             Instruction *X = 
7088               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7089                                      Op0BO->getOperand(1)->getName());
7090             InsertNewInstBefore(X, I);  // (X + (Y << C))
7091             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7092             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7093                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7094           }
7095           
7096           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7097           Value *Op0BOOp1 = Op0BO->getOperand(1);
7098           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7099               match(Op0BOOp1, 
7100                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
7101               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7102               V2 == Op1) {
7103             Instruction *YS = BinaryOperator::CreateShl(
7104                                                      Op0BO->getOperand(0), Op1,
7105                                                      Op0BO->getName());
7106             InsertNewInstBefore(YS, I); // (Y << C)
7107             Instruction *XM =
7108               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7109                                         V1->getName()+".mask");
7110             InsertNewInstBefore(XM, I); // X & (CC << C)
7111             
7112             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7113           }
7114         }
7115           
7116         // FALL THROUGH.
7117         case Instruction::Sub: {
7118           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7119           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7120               match(Op0BO->getOperand(0),
7121                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7122             Instruction *YS = BinaryOperator::CreateShl(
7123                                                      Op0BO->getOperand(1), Op1,
7124                                                      Op0BO->getName());
7125             InsertNewInstBefore(YS, I); // (Y << C)
7126             Instruction *X =
7127               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7128                                      Op0BO->getOperand(0)->getName());
7129             InsertNewInstBefore(X, I);  // (X + (Y << C))
7130             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7131             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7132                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7133           }
7134           
7135           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7136           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7137               match(Op0BO->getOperand(0),
7138                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7139                           m_ConstantInt(CC))) && V2 == Op1 &&
7140               cast<BinaryOperator>(Op0BO->getOperand(0))
7141                   ->getOperand(0)->hasOneUse()) {
7142             Instruction *YS = BinaryOperator::CreateShl(
7143                                                      Op0BO->getOperand(1), Op1,
7144                                                      Op0BO->getName());
7145             InsertNewInstBefore(YS, I); // (Y << C)
7146             Instruction *XM =
7147               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7148                                         V1->getName()+".mask");
7149             InsertNewInstBefore(XM, I); // X & (CC << C)
7150             
7151             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7152           }
7153           
7154           break;
7155         }
7156       }
7157       
7158       
7159       // If the operand is an bitwise operator with a constant RHS, and the
7160       // shift is the only use, we can pull it out of the shift.
7161       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7162         bool isValid = true;     // Valid only for And, Or, Xor
7163         bool highBitSet = false; // Transform if high bit of constant set?
7164         
7165         switch (Op0BO->getOpcode()) {
7166           default: isValid = false; break;   // Do not perform transform!
7167           case Instruction::Add:
7168             isValid = isLeftShift;
7169             break;
7170           case Instruction::Or:
7171           case Instruction::Xor:
7172             highBitSet = false;
7173             break;
7174           case Instruction::And:
7175             highBitSet = true;
7176             break;
7177         }
7178         
7179         // If this is a signed shift right, and the high bit is modified
7180         // by the logical operation, do not perform the transformation.
7181         // The highBitSet boolean indicates the value of the high bit of
7182         // the constant which would cause it to be modified for this
7183         // operation.
7184         //
7185         if (isValid && I.getOpcode() == Instruction::AShr)
7186           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7187         
7188         if (isValid) {
7189           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7190           
7191           Instruction *NewShift =
7192             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7193           InsertNewInstBefore(NewShift, I);
7194           NewShift->takeName(Op0BO);
7195           
7196           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7197                                         NewRHS);
7198         }
7199       }
7200     }
7201   }
7202   
7203   // Find out if this is a shift of a shift by a constant.
7204   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7205   if (ShiftOp && !ShiftOp->isShift())
7206     ShiftOp = 0;
7207   
7208   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7209     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7210     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7211     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7212     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7213     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7214     Value *X = ShiftOp->getOperand(0);
7215     
7216     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7217     if (AmtSum > TypeBits)
7218       AmtSum = TypeBits;
7219     
7220     const IntegerType *Ty = cast<IntegerType>(I.getType());
7221     
7222     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7223     if (I.getOpcode() == ShiftOp->getOpcode()) {
7224       return BinaryOperator::Create(I.getOpcode(), X,
7225                                     ConstantInt::get(Ty, AmtSum));
7226     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7227                I.getOpcode() == Instruction::AShr) {
7228       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7229       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7230     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7231                I.getOpcode() == Instruction::LShr) {
7232       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7233       Instruction *Shift =
7234         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7235       InsertNewInstBefore(Shift, I);
7236
7237       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7238       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7239     }
7240     
7241     // Okay, if we get here, one shift must be left, and the other shift must be
7242     // right.  See if the amounts are equal.
7243     if (ShiftAmt1 == ShiftAmt2) {
7244       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7245       if (I.getOpcode() == Instruction::Shl) {
7246         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7247         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7248       }
7249       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7250       if (I.getOpcode() == Instruction::LShr) {
7251         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7252         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7253       }
7254       // We can simplify ((X << C) >>s C) into a trunc + sext.
7255       // NOTE: we could do this for any C, but that would make 'unusual' integer
7256       // types.  For now, just stick to ones well-supported by the code
7257       // generators.
7258       const Type *SExtType = 0;
7259       switch (Ty->getBitWidth() - ShiftAmt1) {
7260       case 1  :
7261       case 8  :
7262       case 16 :
7263       case 32 :
7264       case 64 :
7265       case 128:
7266         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7267         break;
7268       default: break;
7269       }
7270       if (SExtType) {
7271         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7272         InsertNewInstBefore(NewTrunc, I);
7273         return new SExtInst(NewTrunc, Ty);
7274       }
7275       // Otherwise, we can't handle it yet.
7276     } else if (ShiftAmt1 < ShiftAmt2) {
7277       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7278       
7279       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7280       if (I.getOpcode() == Instruction::Shl) {
7281         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7282                ShiftOp->getOpcode() == Instruction::AShr);
7283         Instruction *Shift =
7284           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7285         InsertNewInstBefore(Shift, I);
7286         
7287         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7288         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7289       }
7290       
7291       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7292       if (I.getOpcode() == Instruction::LShr) {
7293         assert(ShiftOp->getOpcode() == Instruction::Shl);
7294         Instruction *Shift =
7295           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7296         InsertNewInstBefore(Shift, I);
7297         
7298         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7299         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7300       }
7301       
7302       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7303     } else {
7304       assert(ShiftAmt2 < ShiftAmt1);
7305       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7306
7307       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7308       if (I.getOpcode() == Instruction::Shl) {
7309         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7310                ShiftOp->getOpcode() == Instruction::AShr);
7311         Instruction *Shift =
7312           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7313                                  ConstantInt::get(Ty, ShiftDiff));
7314         InsertNewInstBefore(Shift, I);
7315         
7316         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7317         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7318       }
7319       
7320       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7321       if (I.getOpcode() == Instruction::LShr) {
7322         assert(ShiftOp->getOpcode() == Instruction::Shl);
7323         Instruction *Shift =
7324           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7325         InsertNewInstBefore(Shift, I);
7326         
7327         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7328         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7329       }
7330       
7331       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7332     }
7333   }
7334   return 0;
7335 }
7336
7337
7338 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7339 /// expression.  If so, decompose it, returning some value X, such that Val is
7340 /// X*Scale+Offset.
7341 ///
7342 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7343                                         int &Offset) {
7344   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7345   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7346     Offset = CI->getZExtValue();
7347     Scale  = 0;
7348     return ConstantInt::get(Type::Int32Ty, 0);
7349   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7350     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7351       if (I->getOpcode() == Instruction::Shl) {
7352         // This is a value scaled by '1 << the shift amt'.
7353         Scale = 1U << RHS->getZExtValue();
7354         Offset = 0;
7355         return I->getOperand(0);
7356       } else if (I->getOpcode() == Instruction::Mul) {
7357         // This value is scaled by 'RHS'.
7358         Scale = RHS->getZExtValue();
7359         Offset = 0;
7360         return I->getOperand(0);
7361       } else if (I->getOpcode() == Instruction::Add) {
7362         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7363         // where C1 is divisible by C2.
7364         unsigned SubScale;
7365         Value *SubVal = 
7366           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7367         Offset += RHS->getZExtValue();
7368         Scale = SubScale;
7369         return SubVal;
7370       }
7371     }
7372   }
7373
7374   // Otherwise, we can't look past this.
7375   Scale = 1;
7376   Offset = 0;
7377   return Val;
7378 }
7379
7380
7381 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7382 /// try to eliminate the cast by moving the type information into the alloc.
7383 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7384                                                    AllocationInst &AI) {
7385   const PointerType *PTy = cast<PointerType>(CI.getType());
7386   
7387   // Remove any uses of AI that are dead.
7388   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7389   
7390   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7391     Instruction *User = cast<Instruction>(*UI++);
7392     if (isInstructionTriviallyDead(User)) {
7393       while (UI != E && *UI == User)
7394         ++UI; // If this instruction uses AI more than once, don't break UI.
7395       
7396       ++NumDeadInst;
7397       DOUT << "IC: DCE: " << *User;
7398       EraseInstFromFunction(*User);
7399     }
7400   }
7401   
7402   // Get the type really allocated and the type casted to.
7403   const Type *AllocElTy = AI.getAllocatedType();
7404   const Type *CastElTy = PTy->getElementType();
7405   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7406
7407   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7408   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7409   if (CastElTyAlign < AllocElTyAlign) return 0;
7410
7411   // If the allocation has multiple uses, only promote it if we are strictly
7412   // increasing the alignment of the resultant allocation.  If we keep it the
7413   // same, we open the door to infinite loops of various kinds.
7414   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7415
7416   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7417   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7418   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7419
7420   // See if we can satisfy the modulus by pulling a scale out of the array
7421   // size argument.
7422   unsigned ArraySizeScale;
7423   int ArrayOffset;
7424   Value *NumElements = // See if the array size is a decomposable linear expr.
7425     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7426  
7427   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7428   // do the xform.
7429   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7430       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7431
7432   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7433   Value *Amt = 0;
7434   if (Scale == 1) {
7435     Amt = NumElements;
7436   } else {
7437     // If the allocation size is constant, form a constant mul expression
7438     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7439     if (isa<ConstantInt>(NumElements))
7440       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7441     // otherwise multiply the amount and the number of elements
7442     else if (Scale != 1) {
7443       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7444       Amt = InsertNewInstBefore(Tmp, AI);
7445     }
7446   }
7447   
7448   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7449     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7450     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7451     Amt = InsertNewInstBefore(Tmp, AI);
7452   }
7453   
7454   AllocationInst *New;
7455   if (isa<MallocInst>(AI))
7456     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7457   else
7458     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7459   InsertNewInstBefore(New, AI);
7460   New->takeName(&AI);
7461   
7462   // If the allocation has multiple uses, insert a cast and change all things
7463   // that used it to use the new cast.  This will also hack on CI, but it will
7464   // die soon.
7465   if (!AI.hasOneUse()) {
7466     AddUsesToWorkList(AI);
7467     // New is the allocation instruction, pointer typed. AI is the original
7468     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7469     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7470     InsertNewInstBefore(NewCast, AI);
7471     AI.replaceAllUsesWith(NewCast);
7472   }
7473   return ReplaceInstUsesWith(CI, New);
7474 }
7475
7476 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7477 /// and return it as type Ty without inserting any new casts and without
7478 /// changing the computed value.  This is used by code that tries to decide
7479 /// whether promoting or shrinking integer operations to wider or smaller types
7480 /// will allow us to eliminate a truncate or extend.
7481 ///
7482 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7483 /// extension operation if Ty is larger.
7484 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7485                                               unsigned CastOpc,
7486                                               int &NumCastsRemoved) {
7487   // We can always evaluate constants in another type.
7488   if (isa<ConstantInt>(V))
7489     return true;
7490   
7491   Instruction *I = dyn_cast<Instruction>(V);
7492   if (!I) return false;
7493   
7494   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7495   
7496   // If this is an extension or truncate, we can often eliminate it.
7497   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7498     // If this is a cast from the destination type, we can trivially eliminate
7499     // it, and this will remove a cast overall.
7500     if (I->getOperand(0)->getType() == Ty) {
7501       // If the first operand is itself a cast, and is eliminable, do not count
7502       // this as an eliminable cast.  We would prefer to eliminate those two
7503       // casts first.
7504       if (!isa<CastInst>(I->getOperand(0)))
7505         ++NumCastsRemoved;
7506       return true;
7507     }
7508   }
7509
7510   // We can't extend or shrink something that has multiple uses: doing so would
7511   // require duplicating the instruction in general, which isn't profitable.
7512   if (!I->hasOneUse()) return false;
7513
7514   switch (I->getOpcode()) {
7515   case Instruction::Add:
7516   case Instruction::Sub:
7517   case Instruction::And:
7518   case Instruction::Or:
7519   case Instruction::Xor:
7520     // These operators can all arbitrarily be extended or truncated.
7521     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7522                                       NumCastsRemoved) &&
7523            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7524                                       NumCastsRemoved);
7525
7526   case Instruction::Mul:
7527     // A multiply can be truncated by truncating its operands.
7528     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
7529            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7530                                       NumCastsRemoved) &&
7531            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7532                                       NumCastsRemoved);
7533
7534   case Instruction::Shl:
7535     // If we are truncating the result of this SHL, and if it's a shift of a
7536     // constant amount, we can always perform a SHL in a smaller type.
7537     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7538       uint32_t BitWidth = Ty->getBitWidth();
7539       if (BitWidth < OrigTy->getBitWidth() && 
7540           CI->getLimitedValue(BitWidth) < BitWidth)
7541         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7542                                           NumCastsRemoved);
7543     }
7544     break;
7545   case Instruction::LShr:
7546     // If this is a truncate of a logical shr, we can truncate it to a smaller
7547     // lshr iff we know that the bits we would otherwise be shifting in are
7548     // already zeros.
7549     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7550       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7551       uint32_t BitWidth = Ty->getBitWidth();
7552       if (BitWidth < OrigBitWidth &&
7553           MaskedValueIsZero(I->getOperand(0),
7554             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7555           CI->getLimitedValue(BitWidth) < BitWidth) {
7556         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7557                                           NumCastsRemoved);
7558       }
7559     }
7560     break;
7561   case Instruction::ZExt:
7562   case Instruction::SExt:
7563   case Instruction::Trunc:
7564     // If this is the same kind of case as our original (e.g. zext+zext), we
7565     // can safely replace it.  Note that replacing it does not reduce the number
7566     // of casts in the input.
7567     if (I->getOpcode() == CastOpc)
7568       return true;
7569     
7570     break;
7571   default:
7572     // TODO: Can handle more cases here.
7573     break;
7574   }
7575   
7576   return false;
7577 }
7578
7579 /// EvaluateInDifferentType - Given an expression that 
7580 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7581 /// evaluate the expression.
7582 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7583                                              bool isSigned) {
7584   if (Constant *C = dyn_cast<Constant>(V))
7585     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7586
7587   // Otherwise, it must be an instruction.
7588   Instruction *I = cast<Instruction>(V);
7589   Instruction *Res = 0;
7590   switch (I->getOpcode()) {
7591   case Instruction::Add:
7592   case Instruction::Sub:
7593   case Instruction::Mul:
7594   case Instruction::And:
7595   case Instruction::Or:
7596   case Instruction::Xor:
7597   case Instruction::AShr:
7598   case Instruction::LShr:
7599   case Instruction::Shl: {
7600     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7601     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7602     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7603                                  LHS, RHS, I->getName());
7604     break;
7605   }    
7606   case Instruction::Trunc:
7607   case Instruction::ZExt:
7608   case Instruction::SExt:
7609     // If the source type of the cast is the type we're trying for then we can
7610     // just return the source.  There's no need to insert it because it is not
7611     // new.
7612     if (I->getOperand(0)->getType() == Ty)
7613       return I->getOperand(0);
7614     
7615     // Otherwise, must be the same type of case, so just reinsert a new one.
7616     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7617                            Ty, I->getName());
7618     break;
7619   default: 
7620     // TODO: Can handle more cases here.
7621     assert(0 && "Unreachable!");
7622     break;
7623   }
7624   
7625   return InsertNewInstBefore(Res, *I);
7626 }
7627
7628 /// @brief Implement the transforms common to all CastInst visitors.
7629 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7630   Value *Src = CI.getOperand(0);
7631
7632   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7633   // eliminate it now.
7634   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7635     if (Instruction::CastOps opc = 
7636         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7637       // The first cast (CSrc) is eliminable so we need to fix up or replace
7638       // the second cast (CI). CSrc will then have a good chance of being dead.
7639       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7640     }
7641   }
7642
7643   // If we are casting a select then fold the cast into the select
7644   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7645     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7646       return NV;
7647
7648   // If we are casting a PHI then fold the cast into the PHI
7649   if (isa<PHINode>(Src))
7650     if (Instruction *NV = FoldOpIntoPhi(CI))
7651       return NV;
7652   
7653   return 0;
7654 }
7655
7656 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7657 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7658   Value *Src = CI.getOperand(0);
7659   
7660   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7661     // If casting the result of a getelementptr instruction with no offset, turn
7662     // this into a cast of the original pointer!
7663     if (GEP->hasAllZeroIndices()) {
7664       // Changing the cast operand is usually not a good idea but it is safe
7665       // here because the pointer operand is being replaced with another 
7666       // pointer operand so the opcode doesn't need to change.
7667       AddToWorkList(GEP);
7668       CI.setOperand(0, GEP->getOperand(0));
7669       return &CI;
7670     }
7671     
7672     // If the GEP has a single use, and the base pointer is a bitcast, and the
7673     // GEP computes a constant offset, see if we can convert these three
7674     // instructions into fewer.  This typically happens with unions and other
7675     // non-type-safe code.
7676     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7677       if (GEP->hasAllConstantIndices()) {
7678         // We are guaranteed to get a constant from EmitGEPOffset.
7679         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7680         int64_t Offset = OffsetV->getSExtValue();
7681         
7682         // Get the base pointer input of the bitcast, and the type it points to.
7683         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7684         const Type *GEPIdxTy =
7685           cast<PointerType>(OrigBase->getType())->getElementType();
7686         if (GEPIdxTy->isSized()) {
7687           SmallVector<Value*, 8> NewIndices;
7688           
7689           // Start with the index over the outer type.  Note that the type size
7690           // might be zero (even if the offset isn't zero) if the indexed type
7691           // is something like [0 x {int, int}]
7692           const Type *IntPtrTy = TD->getIntPtrType();
7693           int64_t FirstIdx = 0;
7694           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7695             FirstIdx = Offset/TySize;
7696             Offset %= TySize;
7697           
7698             // Handle silly modulus not returning values values [0..TySize).
7699             if (Offset < 0) {
7700               --FirstIdx;
7701               Offset += TySize;
7702               assert(Offset >= 0);
7703             }
7704             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7705           }
7706           
7707           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7708
7709           // Index into the types.  If we fail, set OrigBase to null.
7710           while (Offset) {
7711             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7712               const StructLayout *SL = TD->getStructLayout(STy);
7713               if (Offset < (int64_t)SL->getSizeInBytes()) {
7714                 unsigned Elt = SL->getElementContainingOffset(Offset);
7715                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7716               
7717                 Offset -= SL->getElementOffset(Elt);
7718                 GEPIdxTy = STy->getElementType(Elt);
7719               } else {
7720                 // Otherwise, we can't index into this, bail out.
7721                 Offset = 0;
7722                 OrigBase = 0;
7723               }
7724             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7725               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7726               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7727                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7728                 Offset %= EltSize;
7729               } else {
7730                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7731               }
7732               GEPIdxTy = STy->getElementType();
7733             } else {
7734               // Otherwise, we can't index into this, bail out.
7735               Offset = 0;
7736               OrigBase = 0;
7737             }
7738           }
7739           if (OrigBase) {
7740             // If we were able to index down into an element, create the GEP
7741             // and bitcast the result.  This eliminates one bitcast, potentially
7742             // two.
7743             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7744                                                           NewIndices.begin(),
7745                                                           NewIndices.end(), "");
7746             InsertNewInstBefore(NGEP, CI);
7747             NGEP->takeName(GEP);
7748             
7749             if (isa<BitCastInst>(CI))
7750               return new BitCastInst(NGEP, CI.getType());
7751             assert(isa<PtrToIntInst>(CI));
7752             return new PtrToIntInst(NGEP, CI.getType());
7753           }
7754         }
7755       }      
7756     }
7757   }
7758     
7759   return commonCastTransforms(CI);
7760 }
7761
7762
7763
7764 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7765 /// integer types. This function implements the common transforms for all those
7766 /// cases.
7767 /// @brief Implement the transforms common to CastInst with integer operands
7768 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7769   if (Instruction *Result = commonCastTransforms(CI))
7770     return Result;
7771
7772   Value *Src = CI.getOperand(0);
7773   const Type *SrcTy = Src->getType();
7774   const Type *DestTy = CI.getType();
7775   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7776   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7777
7778   // See if we can simplify any instructions used by the LHS whose sole 
7779   // purpose is to compute bits we don't care about.
7780   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7781   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7782                            KnownZero, KnownOne))
7783     return &CI;
7784
7785   // If the source isn't an instruction or has more than one use then we
7786   // can't do anything more. 
7787   Instruction *SrcI = dyn_cast<Instruction>(Src);
7788   if (!SrcI || !Src->hasOneUse())
7789     return 0;
7790
7791   // Attempt to propagate the cast into the instruction for int->int casts.
7792   int NumCastsRemoved = 0;
7793   if (!isa<BitCastInst>(CI) &&
7794       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7795                                  CI.getOpcode(), NumCastsRemoved)) {
7796     // If this cast is a truncate, evaluting in a different type always
7797     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7798     // we need to do an AND to maintain the clear top-part of the computation,
7799     // so we require that the input have eliminated at least one cast.  If this
7800     // is a sign extension, we insert two new casts (to do the extension) so we
7801     // require that two casts have been eliminated.
7802     bool DoXForm;
7803     switch (CI.getOpcode()) {
7804     default:
7805       // All the others use floating point so we shouldn't actually 
7806       // get here because of the check above.
7807       assert(0 && "Unknown cast type");
7808     case Instruction::Trunc:
7809       DoXForm = true;
7810       break;
7811     case Instruction::ZExt:
7812       DoXForm = NumCastsRemoved >= 1;
7813       break;
7814     case Instruction::SExt:
7815       DoXForm = NumCastsRemoved >= 2;
7816       break;
7817     }
7818     
7819     if (DoXForm) {
7820       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7821                                            CI.getOpcode() == Instruction::SExt);
7822       assert(Res->getType() == DestTy);
7823       switch (CI.getOpcode()) {
7824       default: assert(0 && "Unknown cast type!");
7825       case Instruction::Trunc:
7826       case Instruction::BitCast:
7827         // Just replace this cast with the result.
7828         return ReplaceInstUsesWith(CI, Res);
7829       case Instruction::ZExt: {
7830         // We need to emit an AND to clear the high bits.
7831         assert(SrcBitSize < DestBitSize && "Not a zext?");
7832         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7833                                                             SrcBitSize));
7834         return BinaryOperator::CreateAnd(Res, C);
7835       }
7836       case Instruction::SExt:
7837         // We need to emit a cast to truncate, then a cast to sext.
7838         return CastInst::Create(Instruction::SExt,
7839             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7840                              CI), DestTy);
7841       }
7842     }
7843   }
7844   
7845   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7846   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7847
7848   switch (SrcI->getOpcode()) {
7849   case Instruction::Add:
7850   case Instruction::Mul:
7851   case Instruction::And:
7852   case Instruction::Or:
7853   case Instruction::Xor:
7854     // If we are discarding information, rewrite.
7855     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7856       // Don't insert two casts if they cannot be eliminated.  We allow 
7857       // two casts to be inserted if the sizes are the same.  This could 
7858       // only be converting signedness, which is a noop.
7859       if (DestBitSize == SrcBitSize || 
7860           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7861           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7862         Instruction::CastOps opcode = CI.getOpcode();
7863         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7864         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7865         return BinaryOperator::Create(
7866             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7867       }
7868     }
7869
7870     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7871     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7872         SrcI->getOpcode() == Instruction::Xor &&
7873         Op1 == ConstantInt::getTrue() &&
7874         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7875       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7876       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7877     }
7878     break;
7879   case Instruction::SDiv:
7880   case Instruction::UDiv:
7881   case Instruction::SRem:
7882   case Instruction::URem:
7883     // If we are just changing the sign, rewrite.
7884     if (DestBitSize == SrcBitSize) {
7885       // Don't insert two casts if they cannot be eliminated.  We allow 
7886       // two casts to be inserted if the sizes are the same.  This could 
7887       // only be converting signedness, which is a noop.
7888       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7889           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7890         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7891                                               Op0, DestTy, SrcI);
7892         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7893                                               Op1, DestTy, SrcI);
7894         return BinaryOperator::Create(
7895           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7896       }
7897     }
7898     break;
7899
7900   case Instruction::Shl:
7901     // Allow changing the sign of the source operand.  Do not allow 
7902     // changing the size of the shift, UNLESS the shift amount is a 
7903     // constant.  We must not change variable sized shifts to a smaller 
7904     // size, because it is undefined to shift more bits out than exist 
7905     // in the value.
7906     if (DestBitSize == SrcBitSize ||
7907         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7908       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7909           Instruction::BitCast : Instruction::Trunc);
7910       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7911       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7912       return BinaryOperator::CreateShl(Op0c, Op1c);
7913     }
7914     break;
7915   case Instruction::AShr:
7916     // If this is a signed shr, and if all bits shifted in are about to be
7917     // truncated off, turn it into an unsigned shr to allow greater
7918     // simplifications.
7919     if (DestBitSize < SrcBitSize &&
7920         isa<ConstantInt>(Op1)) {
7921       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7922       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7923         // Insert the new logical shift right.
7924         return BinaryOperator::CreateLShr(Op0, Op1);
7925       }
7926     }
7927     break;
7928   }
7929   return 0;
7930 }
7931
7932 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7933   if (Instruction *Result = commonIntCastTransforms(CI))
7934     return Result;
7935   
7936   Value *Src = CI.getOperand(0);
7937   const Type *Ty = CI.getType();
7938   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7939   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7940   
7941   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7942     switch (SrcI->getOpcode()) {
7943     default: break;
7944     case Instruction::LShr:
7945       // We can shrink lshr to something smaller if we know the bits shifted in
7946       // are already zeros.
7947       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7948         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7949         
7950         // Get a mask for the bits shifting in.
7951         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7952         Value* SrcIOp0 = SrcI->getOperand(0);
7953         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7954           if (ShAmt >= DestBitWidth)        // All zeros.
7955             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7956
7957           // Okay, we can shrink this.  Truncate the input, then return a new
7958           // shift.
7959           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7960           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7961                                        Ty, CI);
7962           return BinaryOperator::CreateLShr(V1, V2);
7963         }
7964       } else {     // This is a variable shr.
7965         
7966         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7967         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7968         // loop-invariant and CSE'd.
7969         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7970           Value *One = ConstantInt::get(SrcI->getType(), 1);
7971
7972           Value *V = InsertNewInstBefore(
7973               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7974                                      "tmp"), CI);
7975           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7976                                                             SrcI->getOperand(0),
7977                                                             "tmp"), CI);
7978           Value *Zero = Constant::getNullValue(V->getType());
7979           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7980         }
7981       }
7982       break;
7983     }
7984   }
7985   
7986   return 0;
7987 }
7988
7989 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7990 /// in order to eliminate the icmp.
7991 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7992                                              bool DoXform) {
7993   // If we are just checking for a icmp eq of a single bit and zext'ing it
7994   // to an integer, then shift the bit to the appropriate place and then
7995   // cast to integer to avoid the comparison.
7996   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7997     const APInt &Op1CV = Op1C->getValue();
7998       
7999     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8000     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8001     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8002         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8003       if (!DoXform) return ICI;
8004
8005       Value *In = ICI->getOperand(0);
8006       Value *Sh = ConstantInt::get(In->getType(),
8007                                    In->getType()->getPrimitiveSizeInBits()-1);
8008       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8009                                                         In->getName()+".lobit"),
8010                                CI);
8011       if (In->getType() != CI.getType())
8012         In = CastInst::CreateIntegerCast(In, CI.getType(),
8013                                          false/*ZExt*/, "tmp", &CI);
8014
8015       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8016         Constant *One = ConstantInt::get(In->getType(), 1);
8017         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8018                                                          In->getName()+".not"),
8019                                  CI);
8020       }
8021
8022       return ReplaceInstUsesWith(CI, In);
8023     }
8024       
8025       
8026       
8027     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8028     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8029     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8030     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8031     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8032     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8033     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8034     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8035     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8036         // This only works for EQ and NE
8037         ICI->isEquality()) {
8038       // If Op1C some other power of two, convert:
8039       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8040       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8041       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8042       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8043         
8044       APInt KnownZeroMask(~KnownZero);
8045       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8046         if (!DoXform) return ICI;
8047
8048         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8049         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8050           // (X&4) == 2 --> false
8051           // (X&4) != 2 --> true
8052           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8053           Res = ConstantExpr::getZExt(Res, CI.getType());
8054           return ReplaceInstUsesWith(CI, Res);
8055         }
8056           
8057         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8058         Value *In = ICI->getOperand(0);
8059         if (ShiftAmt) {
8060           // Perform a logical shr by shiftamt.
8061           // Insert the shift to put the result in the low bit.
8062           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8063                                   ConstantInt::get(In->getType(), ShiftAmt),
8064                                                    In->getName()+".lobit"), CI);
8065         }
8066           
8067         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8068           Constant *One = ConstantInt::get(In->getType(), 1);
8069           In = BinaryOperator::CreateXor(In, One, "tmp");
8070           InsertNewInstBefore(cast<Instruction>(In), CI);
8071         }
8072           
8073         if (CI.getType() == In->getType())
8074           return ReplaceInstUsesWith(CI, In);
8075         else
8076           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8077       }
8078     }
8079   }
8080
8081   return 0;
8082 }
8083
8084 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8085   // If one of the common conversion will work ..
8086   if (Instruction *Result = commonIntCastTransforms(CI))
8087     return Result;
8088
8089   Value *Src = CI.getOperand(0);
8090
8091   // If this is a cast of a cast
8092   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8093     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8094     // types and if the sizes are just right we can convert this into a logical
8095     // 'and' which will be much cheaper than the pair of casts.
8096     if (isa<TruncInst>(CSrc)) {
8097       // Get the sizes of the types involved
8098       Value *A = CSrc->getOperand(0);
8099       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8100       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8101       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8102       // If we're actually extending zero bits and the trunc is a no-op
8103       if (MidSize < DstSize && SrcSize == DstSize) {
8104         // Replace both of the casts with an And of the type mask.
8105         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8106         Constant *AndConst = ConstantInt::get(AndValue);
8107         Instruction *And = 
8108           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8109         // Unfortunately, if the type changed, we need to cast it back.
8110         if (And->getType() != CI.getType()) {
8111           And->setName(CSrc->getName()+".mask");
8112           InsertNewInstBefore(And, CI);
8113           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8114         }
8115         return And;
8116       }
8117     }
8118   }
8119
8120   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8121     return transformZExtICmp(ICI, CI);
8122
8123   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8124   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8125     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8126     // of the (zext icmp) will be transformed.
8127     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8128     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8129     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8130         (transformZExtICmp(LHS, CI, false) ||
8131          transformZExtICmp(RHS, CI, false))) {
8132       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8133       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8134       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8135     }
8136   }
8137
8138   return 0;
8139 }
8140
8141 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8142   if (Instruction *I = commonIntCastTransforms(CI))
8143     return I;
8144   
8145   Value *Src = CI.getOperand(0);
8146   
8147   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
8148   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
8149   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8150     // If we are just checking for a icmp eq of a single bit and zext'ing it
8151     // to an integer, then shift the bit to the appropriate place and then
8152     // cast to integer to avoid the comparison.
8153     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8154       const APInt &Op1CV = Op1C->getValue();
8155       
8156       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8157       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8158       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8159           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8160         Value *In = ICI->getOperand(0);
8161         Value *Sh = ConstantInt::get(In->getType(),
8162                                      In->getType()->getPrimitiveSizeInBits()-1);
8163         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8164                                                         In->getName()+".lobit"),
8165                                  CI);
8166         if (In->getType() != CI.getType())
8167           In = CastInst::CreateIntegerCast(In, CI.getType(),
8168                                            true/*SExt*/, "tmp", &CI);
8169         
8170         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
8171           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8172                                      In->getName()+".not"), CI);
8173         
8174         return ReplaceInstUsesWith(CI, In);
8175       }
8176     }
8177   }
8178
8179   // See if the value being truncated is already sign extended.  If so, just
8180   // eliminate the trunc/sext pair.
8181   if (getOpcode(Src) == Instruction::Trunc) {
8182     Value *Op = cast<User>(Src)->getOperand(0);
8183     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8184     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8185     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8186     unsigned NumSignBits = ComputeNumSignBits(Op);
8187
8188     if (OpBits == DestBits) {
8189       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8190       // bits, it is already ready.
8191       if (NumSignBits > DestBits-MidBits)
8192         return ReplaceInstUsesWith(CI, Op);
8193     } else if (OpBits < DestBits) {
8194       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8195       // bits, just sext from i32.
8196       if (NumSignBits > OpBits-MidBits)
8197         return new SExtInst(Op, CI.getType(), "tmp");
8198     } else {
8199       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8200       // bits, just truncate to i32.
8201       if (NumSignBits > OpBits-MidBits)
8202         return new TruncInst(Op, CI.getType(), "tmp");
8203     }
8204   }
8205       
8206   return 0;
8207 }
8208
8209 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8210 /// in the specified FP type without changing its value.
8211 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8212   APFloat F = CFP->getValueAPF();
8213   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
8214     return ConstantFP::get(F);
8215   return 0;
8216 }
8217
8218 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8219 /// through it until we get the source value.
8220 static Value *LookThroughFPExtensions(Value *V) {
8221   if (Instruction *I = dyn_cast<Instruction>(V))
8222     if (I->getOpcode() == Instruction::FPExt)
8223       return LookThroughFPExtensions(I->getOperand(0));
8224   
8225   // If this value is a constant, return the constant in the smallest FP type
8226   // that can accurately represent it.  This allows us to turn
8227   // (float)((double)X+2.0) into x+2.0f.
8228   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8229     if (CFP->getType() == Type::PPC_FP128Ty)
8230       return V;  // No constant folding of this.
8231     // See if the value can be truncated to float and then reextended.
8232     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8233       return V;
8234     if (CFP->getType() == Type::DoubleTy)
8235       return V;  // Won't shrink.
8236     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8237       return V;
8238     // Don't try to shrink to various long double types.
8239   }
8240   
8241   return V;
8242 }
8243
8244 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8245   if (Instruction *I = commonCastTransforms(CI))
8246     return I;
8247   
8248   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8249   // smaller than the destination type, we can eliminate the truncate by doing
8250   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8251   // many builtins (sqrt, etc).
8252   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8253   if (OpI && OpI->hasOneUse()) {
8254     switch (OpI->getOpcode()) {
8255     default: break;
8256     case Instruction::Add:
8257     case Instruction::Sub:
8258     case Instruction::Mul:
8259     case Instruction::FDiv:
8260     case Instruction::FRem:
8261       const Type *SrcTy = OpI->getType();
8262       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8263       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8264       if (LHSTrunc->getType() != SrcTy && 
8265           RHSTrunc->getType() != SrcTy) {
8266         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8267         // If the source types were both smaller than the destination type of
8268         // the cast, do this xform.
8269         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8270             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8271           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8272                                       CI.getType(), CI);
8273           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8274                                       CI.getType(), CI);
8275           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8276         }
8277       }
8278       break;  
8279     }
8280   }
8281   return 0;
8282 }
8283
8284 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8285   return commonCastTransforms(CI);
8286 }
8287
8288 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8289   // fptoui(uitofp(X)) --> X  if the intermediate type has enough bits in its
8290   // mantissa to accurately represent all values of X.  For example, do not
8291   // do this with i64->float->i64.
8292   if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8293     if (SrcI->getOperand(0)->getType() == FI.getType() &&
8294         (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8295                     SrcI->getType()->getFPMantissaWidth())
8296       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8297
8298   return commonCastTransforms(FI);
8299 }
8300
8301 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8302   // fptosi(sitofp(X)) --> X  if the intermediate type has enough bits in its
8303   // mantissa to accurately represent all values of X.  For example, do not
8304   // do this with i64->float->i64.
8305   if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8306     if (SrcI->getOperand(0)->getType() == FI.getType() &&
8307         (int)FI.getType()->getPrimitiveSizeInBits() <= 
8308                     SrcI->getType()->getFPMantissaWidth())
8309       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8310   
8311   return commonCastTransforms(FI);
8312 }
8313
8314 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8315   return commonCastTransforms(CI);
8316 }
8317
8318 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8319   return commonCastTransforms(CI);
8320 }
8321
8322 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8323   return commonPointerCastTransforms(CI);
8324 }
8325
8326 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8327   if (Instruction *I = commonCastTransforms(CI))
8328     return I;
8329   
8330   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8331   if (!DestPointee->isSized()) return 0;
8332
8333   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8334   ConstantInt *Cst;
8335   Value *X;
8336   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8337                                     m_ConstantInt(Cst)))) {
8338     // If the source and destination operands have the same type, see if this
8339     // is a single-index GEP.
8340     if (X->getType() == CI.getType()) {
8341       // Get the size of the pointee type.
8342       uint64_t Size = TD->getABITypeSize(DestPointee);
8343
8344       // Convert the constant to intptr type.
8345       APInt Offset = Cst->getValue();
8346       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8347
8348       // If Offset is evenly divisible by Size, we can do this xform.
8349       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8350         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8351         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8352       }
8353     }
8354     // TODO: Could handle other cases, e.g. where add is indexing into field of
8355     // struct etc.
8356   } else if (CI.getOperand(0)->hasOneUse() &&
8357              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8358     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8359     // "inttoptr+GEP" instead of "add+intptr".
8360     
8361     // Get the size of the pointee type.
8362     uint64_t Size = TD->getABITypeSize(DestPointee);
8363     
8364     // Convert the constant to intptr type.
8365     APInt Offset = Cst->getValue();
8366     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8367     
8368     // If Offset is evenly divisible by Size, we can do this xform.
8369     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8370       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8371       
8372       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8373                                                             "tmp"), CI);
8374       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8375     }
8376   }
8377   return 0;
8378 }
8379
8380 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8381   // If the operands are integer typed then apply the integer transforms,
8382   // otherwise just apply the common ones.
8383   Value *Src = CI.getOperand(0);
8384   const Type *SrcTy = Src->getType();
8385   const Type *DestTy = CI.getType();
8386
8387   if (SrcTy->isInteger() && DestTy->isInteger()) {
8388     if (Instruction *Result = commonIntCastTransforms(CI))
8389       return Result;
8390   } else if (isa<PointerType>(SrcTy)) {
8391     if (Instruction *I = commonPointerCastTransforms(CI))
8392       return I;
8393   } else {
8394     if (Instruction *Result = commonCastTransforms(CI))
8395       return Result;
8396   }
8397
8398
8399   // Get rid of casts from one type to the same type. These are useless and can
8400   // be replaced by the operand.
8401   if (DestTy == Src->getType())
8402     return ReplaceInstUsesWith(CI, Src);
8403
8404   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8405     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8406     const Type *DstElTy = DstPTy->getElementType();
8407     const Type *SrcElTy = SrcPTy->getElementType();
8408     
8409     // If the address spaces don't match, don't eliminate the bitcast, which is
8410     // required for changing types.
8411     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8412       return 0;
8413     
8414     // If we are casting a malloc or alloca to a pointer to a type of the same
8415     // size, rewrite the allocation instruction to allocate the "right" type.
8416     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8417       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8418         return V;
8419     
8420     // If the source and destination are pointers, and this cast is equivalent
8421     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8422     // This can enhance SROA and other transforms that want type-safe pointers.
8423     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8424     unsigned NumZeros = 0;
8425     while (SrcElTy != DstElTy && 
8426            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8427            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8428       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8429       ++NumZeros;
8430     }
8431
8432     // If we found a path from the src to dest, create the getelementptr now.
8433     if (SrcElTy == DstElTy) {
8434       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8435       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8436                                        ((Instruction*) NULL));
8437     }
8438   }
8439
8440   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8441     if (SVI->hasOneUse()) {
8442       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8443       // a bitconvert to a vector with the same # elts.
8444       if (isa<VectorType>(DestTy) && 
8445           cast<VectorType>(DestTy)->getNumElements() == 
8446                 SVI->getType()->getNumElements()) {
8447         CastInst *Tmp;
8448         // If either of the operands is a cast from CI.getType(), then
8449         // evaluating the shuffle in the casted destination's type will allow
8450         // us to eliminate at least one cast.
8451         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8452              Tmp->getOperand(0)->getType() == DestTy) ||
8453             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8454              Tmp->getOperand(0)->getType() == DestTy)) {
8455           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8456                                                SVI->getOperand(0), DestTy, &CI);
8457           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8458                                                SVI->getOperand(1), DestTy, &CI);
8459           // Return a new shuffle vector.  Use the same element ID's, as we
8460           // know the vector types match #elts.
8461           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8462         }
8463       }
8464     }
8465   }
8466   return 0;
8467 }
8468
8469 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8470 ///   %C = or %A, %B
8471 ///   %D = select %cond, %C, %A
8472 /// into:
8473 ///   %C = select %cond, %B, 0
8474 ///   %D = or %A, %C
8475 ///
8476 /// Assuming that the specified instruction is an operand to the select, return
8477 /// a bitmask indicating which operands of this instruction are foldable if they
8478 /// equal the other incoming value of the select.
8479 ///
8480 static unsigned GetSelectFoldableOperands(Instruction *I) {
8481   switch (I->getOpcode()) {
8482   case Instruction::Add:
8483   case Instruction::Mul:
8484   case Instruction::And:
8485   case Instruction::Or:
8486   case Instruction::Xor:
8487     return 3;              // Can fold through either operand.
8488   case Instruction::Sub:   // Can only fold on the amount subtracted.
8489   case Instruction::Shl:   // Can only fold on the shift amount.
8490   case Instruction::LShr:
8491   case Instruction::AShr:
8492     return 1;
8493   default:
8494     return 0;              // Cannot fold
8495   }
8496 }
8497
8498 /// GetSelectFoldableConstant - For the same transformation as the previous
8499 /// function, return the identity constant that goes into the select.
8500 static Constant *GetSelectFoldableConstant(Instruction *I) {
8501   switch (I->getOpcode()) {
8502   default: assert(0 && "This cannot happen!"); abort();
8503   case Instruction::Add:
8504   case Instruction::Sub:
8505   case Instruction::Or:
8506   case Instruction::Xor:
8507   case Instruction::Shl:
8508   case Instruction::LShr:
8509   case Instruction::AShr:
8510     return Constant::getNullValue(I->getType());
8511   case Instruction::And:
8512     return Constant::getAllOnesValue(I->getType());
8513   case Instruction::Mul:
8514     return ConstantInt::get(I->getType(), 1);
8515   }
8516 }
8517
8518 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8519 /// have the same opcode and only one use each.  Try to simplify this.
8520 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8521                                           Instruction *FI) {
8522   if (TI->getNumOperands() == 1) {
8523     // If this is a non-volatile load or a cast from the same type,
8524     // merge.
8525     if (TI->isCast()) {
8526       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8527         return 0;
8528     } else {
8529       return 0;  // unknown unary op.
8530     }
8531
8532     // Fold this by inserting a select from the input values.
8533     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8534                                            FI->getOperand(0), SI.getName()+".v");
8535     InsertNewInstBefore(NewSI, SI);
8536     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8537                             TI->getType());
8538   }
8539
8540   // Only handle binary operators here.
8541   if (!isa<BinaryOperator>(TI))
8542     return 0;
8543
8544   // Figure out if the operations have any operands in common.
8545   Value *MatchOp, *OtherOpT, *OtherOpF;
8546   bool MatchIsOpZero;
8547   if (TI->getOperand(0) == FI->getOperand(0)) {
8548     MatchOp  = TI->getOperand(0);
8549     OtherOpT = TI->getOperand(1);
8550     OtherOpF = FI->getOperand(1);
8551     MatchIsOpZero = true;
8552   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8553     MatchOp  = TI->getOperand(1);
8554     OtherOpT = TI->getOperand(0);
8555     OtherOpF = FI->getOperand(0);
8556     MatchIsOpZero = false;
8557   } else if (!TI->isCommutative()) {
8558     return 0;
8559   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8560     MatchOp  = TI->getOperand(0);
8561     OtherOpT = TI->getOperand(1);
8562     OtherOpF = FI->getOperand(0);
8563     MatchIsOpZero = true;
8564   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8565     MatchOp  = TI->getOperand(1);
8566     OtherOpT = TI->getOperand(0);
8567     OtherOpF = FI->getOperand(1);
8568     MatchIsOpZero = true;
8569   } else {
8570     return 0;
8571   }
8572
8573   // If we reach here, they do have operations in common.
8574   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8575                                          OtherOpF, SI.getName()+".v");
8576   InsertNewInstBefore(NewSI, SI);
8577
8578   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8579     if (MatchIsOpZero)
8580       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8581     else
8582       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8583   }
8584   assert(0 && "Shouldn't get here");
8585   return 0;
8586 }
8587
8588 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8589   Value *CondVal = SI.getCondition();
8590   Value *TrueVal = SI.getTrueValue();
8591   Value *FalseVal = SI.getFalseValue();
8592
8593   // select true, X, Y  -> X
8594   // select false, X, Y -> Y
8595   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8596     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8597
8598   // select C, X, X -> X
8599   if (TrueVal == FalseVal)
8600     return ReplaceInstUsesWith(SI, TrueVal);
8601
8602   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8603     return ReplaceInstUsesWith(SI, FalseVal);
8604   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8605     return ReplaceInstUsesWith(SI, TrueVal);
8606   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8607     if (isa<Constant>(TrueVal))
8608       return ReplaceInstUsesWith(SI, TrueVal);
8609     else
8610       return ReplaceInstUsesWith(SI, FalseVal);
8611   }
8612
8613   if (SI.getType() == Type::Int1Ty) {
8614     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8615       if (C->getZExtValue()) {
8616         // Change: A = select B, true, C --> A = or B, C
8617         return BinaryOperator::CreateOr(CondVal, FalseVal);
8618       } else {
8619         // Change: A = select B, false, C --> A = and !B, C
8620         Value *NotCond =
8621           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8622                                              "not."+CondVal->getName()), SI);
8623         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8624       }
8625     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8626       if (C->getZExtValue() == false) {
8627         // Change: A = select B, C, false --> A = and B, C
8628         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8629       } else {
8630         // Change: A = select B, C, true --> A = or !B, C
8631         Value *NotCond =
8632           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8633                                              "not."+CondVal->getName()), SI);
8634         return BinaryOperator::CreateOr(NotCond, TrueVal);
8635       }
8636     }
8637     
8638     // select a, b, a  -> a&b
8639     // select a, a, b  -> a|b
8640     if (CondVal == TrueVal)
8641       return BinaryOperator::CreateOr(CondVal, FalseVal);
8642     else if (CondVal == FalseVal)
8643       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8644   }
8645
8646   // Selecting between two integer constants?
8647   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8648     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8649       // select C, 1, 0 -> zext C to int
8650       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8651         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8652       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8653         // select C, 0, 1 -> zext !C to int
8654         Value *NotCond =
8655           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8656                                                "not."+CondVal->getName()), SI);
8657         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8658       }
8659       
8660       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8661
8662       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8663
8664         // (x <s 0) ? -1 : 0 -> ashr x, 31
8665         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8666           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8667             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8668               // The comparison constant and the result are not neccessarily the
8669               // same width. Make an all-ones value by inserting a AShr.
8670               Value *X = IC->getOperand(0);
8671               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8672               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8673               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8674                                                         ShAmt, "ones");
8675               InsertNewInstBefore(SRA, SI);
8676               
8677               // Finally, convert to the type of the select RHS.  We figure out
8678               // if this requires a SExt, Trunc or BitCast based on the sizes.
8679               Instruction::CastOps opc = Instruction::BitCast;
8680               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8681               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8682               if (SRASize < SISize)
8683                 opc = Instruction::SExt;
8684               else if (SRASize > SISize)
8685                 opc = Instruction::Trunc;
8686               return CastInst::Create(opc, SRA, SI.getType());
8687             }
8688           }
8689
8690
8691         // If one of the constants is zero (we know they can't both be) and we
8692         // have an icmp instruction with zero, and we have an 'and' with the
8693         // non-constant value, eliminate this whole mess.  This corresponds to
8694         // cases like this: ((X & 27) ? 27 : 0)
8695         if (TrueValC->isZero() || FalseValC->isZero())
8696           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8697               cast<Constant>(IC->getOperand(1))->isNullValue())
8698             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8699               if (ICA->getOpcode() == Instruction::And &&
8700                   isa<ConstantInt>(ICA->getOperand(1)) &&
8701                   (ICA->getOperand(1) == TrueValC ||
8702                    ICA->getOperand(1) == FalseValC) &&
8703                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8704                 // Okay, now we know that everything is set up, we just don't
8705                 // know whether we have a icmp_ne or icmp_eq and whether the 
8706                 // true or false val is the zero.
8707                 bool ShouldNotVal = !TrueValC->isZero();
8708                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8709                 Value *V = ICA;
8710                 if (ShouldNotVal)
8711                   V = InsertNewInstBefore(BinaryOperator::Create(
8712                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8713                 return ReplaceInstUsesWith(SI, V);
8714               }
8715       }
8716     }
8717
8718   // See if we are selecting two values based on a comparison of the two values.
8719   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8720     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8721       // Transform (X == Y) ? X : Y  -> Y
8722       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8723         // This is not safe in general for floating point:  
8724         // consider X== -0, Y== +0.
8725         // It becomes safe if either operand is a nonzero constant.
8726         ConstantFP *CFPt, *CFPf;
8727         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8728               !CFPt->getValueAPF().isZero()) ||
8729             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8730              !CFPf->getValueAPF().isZero()))
8731         return ReplaceInstUsesWith(SI, FalseVal);
8732       }
8733       // Transform (X != Y) ? X : Y  -> X
8734       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8735         return ReplaceInstUsesWith(SI, TrueVal);
8736       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8737
8738     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8739       // Transform (X == Y) ? Y : X  -> X
8740       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8741         // This is not safe in general for floating point:  
8742         // consider X== -0, Y== +0.
8743         // It becomes safe if either operand is a nonzero constant.
8744         ConstantFP *CFPt, *CFPf;
8745         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8746               !CFPt->getValueAPF().isZero()) ||
8747             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8748              !CFPf->getValueAPF().isZero()))
8749           return ReplaceInstUsesWith(SI, FalseVal);
8750       }
8751       // Transform (X != Y) ? Y : X  -> Y
8752       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8753         return ReplaceInstUsesWith(SI, TrueVal);
8754       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8755     }
8756   }
8757
8758   // See if we are selecting two values based on a comparison of the two values.
8759   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8760     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8761       // Transform (X == Y) ? X : Y  -> Y
8762       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8763         return ReplaceInstUsesWith(SI, FalseVal);
8764       // Transform (X != Y) ? X : Y  -> X
8765       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8766         return ReplaceInstUsesWith(SI, TrueVal);
8767       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8768
8769     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8770       // Transform (X == Y) ? Y : X  -> X
8771       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8772         return ReplaceInstUsesWith(SI, FalseVal);
8773       // Transform (X != Y) ? Y : X  -> Y
8774       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8775         return ReplaceInstUsesWith(SI, TrueVal);
8776       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8777     }
8778   }
8779
8780   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8781     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8782       if (TI->hasOneUse() && FI->hasOneUse()) {
8783         Instruction *AddOp = 0, *SubOp = 0;
8784
8785         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8786         if (TI->getOpcode() == FI->getOpcode())
8787           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8788             return IV;
8789
8790         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8791         // even legal for FP.
8792         if (TI->getOpcode() == Instruction::Sub &&
8793             FI->getOpcode() == Instruction::Add) {
8794           AddOp = FI; SubOp = TI;
8795         } else if (FI->getOpcode() == Instruction::Sub &&
8796                    TI->getOpcode() == Instruction::Add) {
8797           AddOp = TI; SubOp = FI;
8798         }
8799
8800         if (AddOp) {
8801           Value *OtherAddOp = 0;
8802           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8803             OtherAddOp = AddOp->getOperand(1);
8804           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8805             OtherAddOp = AddOp->getOperand(0);
8806           }
8807
8808           if (OtherAddOp) {
8809             // So at this point we know we have (Y -> OtherAddOp):
8810             //        select C, (add X, Y), (sub X, Z)
8811             Value *NegVal;  // Compute -Z
8812             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8813               NegVal = ConstantExpr::getNeg(C);
8814             } else {
8815               NegVal = InsertNewInstBefore(
8816                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8817             }
8818
8819             Value *NewTrueOp = OtherAddOp;
8820             Value *NewFalseOp = NegVal;
8821             if (AddOp != TI)
8822               std::swap(NewTrueOp, NewFalseOp);
8823             Instruction *NewSel =
8824               SelectInst::Create(CondVal, NewTrueOp,
8825                                  NewFalseOp, SI.getName() + ".p");
8826
8827             NewSel = InsertNewInstBefore(NewSel, SI);
8828             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8829           }
8830         }
8831       }
8832
8833   // See if we can fold the select into one of our operands.
8834   if (SI.getType()->isInteger()) {
8835     // See the comment above GetSelectFoldableOperands for a description of the
8836     // transformation we are doing here.
8837     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8838       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8839           !isa<Constant>(FalseVal))
8840         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8841           unsigned OpToFold = 0;
8842           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8843             OpToFold = 1;
8844           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8845             OpToFold = 2;
8846           }
8847
8848           if (OpToFold) {
8849             Constant *C = GetSelectFoldableConstant(TVI);
8850             Instruction *NewSel =
8851               SelectInst::Create(SI.getCondition(),
8852                                  TVI->getOperand(2-OpToFold), C);
8853             InsertNewInstBefore(NewSel, SI);
8854             NewSel->takeName(TVI);
8855             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8856               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8857             else {
8858               assert(0 && "Unknown instruction!!");
8859             }
8860           }
8861         }
8862
8863     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8864       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8865           !isa<Constant>(TrueVal))
8866         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8867           unsigned OpToFold = 0;
8868           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8869             OpToFold = 1;
8870           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8871             OpToFold = 2;
8872           }
8873
8874           if (OpToFold) {
8875             Constant *C = GetSelectFoldableConstant(FVI);
8876             Instruction *NewSel =
8877               SelectInst::Create(SI.getCondition(), C,
8878                                  FVI->getOperand(2-OpToFold));
8879             InsertNewInstBefore(NewSel, SI);
8880             NewSel->takeName(FVI);
8881             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8882               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8883             else
8884               assert(0 && "Unknown instruction!!");
8885           }
8886         }
8887   }
8888
8889   if (BinaryOperator::isNot(CondVal)) {
8890     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8891     SI.setOperand(1, FalseVal);
8892     SI.setOperand(2, TrueVal);
8893     return &SI;
8894   }
8895
8896   return 0;
8897 }
8898
8899 /// EnforceKnownAlignment - If the specified pointer points to an object that
8900 /// we control, modify the object's alignment to PrefAlign. This isn't
8901 /// often possible though. If alignment is important, a more reliable approach
8902 /// is to simply align all global variables and allocation instructions to
8903 /// their preferred alignment from the beginning.
8904 ///
8905 static unsigned EnforceKnownAlignment(Value *V,
8906                                       unsigned Align, unsigned PrefAlign) {
8907
8908   User *U = dyn_cast<User>(V);
8909   if (!U) return Align;
8910
8911   switch (getOpcode(U)) {
8912   default: break;
8913   case Instruction::BitCast:
8914     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8915   case Instruction::GetElementPtr: {
8916     // If all indexes are zero, it is just the alignment of the base pointer.
8917     bool AllZeroOperands = true;
8918     for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8919       if (!isa<Constant>(U->getOperand(i)) ||
8920           !cast<Constant>(U->getOperand(i))->isNullValue()) {
8921         AllZeroOperands = false;
8922         break;
8923       }
8924
8925     if (AllZeroOperands) {
8926       // Treat this like a bitcast.
8927       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8928     }
8929     break;
8930   }
8931   }
8932
8933   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8934     // If there is a large requested alignment and we can, bump up the alignment
8935     // of the global.
8936     if (!GV->isDeclaration()) {
8937       GV->setAlignment(PrefAlign);
8938       Align = PrefAlign;
8939     }
8940   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8941     // If there is a requested alignment and if this is an alloca, round up.  We
8942     // don't do this for malloc, because some systems can't respect the request.
8943     if (isa<AllocaInst>(AI)) {
8944       AI->setAlignment(PrefAlign);
8945       Align = PrefAlign;
8946     }
8947   }
8948
8949   return Align;
8950 }
8951
8952 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8953 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8954 /// and it is more than the alignment of the ultimate object, see if we can
8955 /// increase the alignment of the ultimate object, making this check succeed.
8956 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8957                                                   unsigned PrefAlign) {
8958   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8959                       sizeof(PrefAlign) * CHAR_BIT;
8960   APInt Mask = APInt::getAllOnesValue(BitWidth);
8961   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8962   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8963   unsigned TrailZ = KnownZero.countTrailingOnes();
8964   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8965
8966   if (PrefAlign > Align)
8967     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8968   
8969     // We don't need to make any adjustment.
8970   return Align;
8971 }
8972
8973 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8974   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8975   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8976   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8977   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8978
8979   if (CopyAlign < MinAlign) {
8980     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8981     return MI;
8982   }
8983   
8984   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8985   // load/store.
8986   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8987   if (MemOpLength == 0) return 0;
8988   
8989   // Source and destination pointer types are always "i8*" for intrinsic.  See
8990   // if the size is something we can handle with a single primitive load/store.
8991   // A single load+store correctly handles overlapping memory in the memmove
8992   // case.
8993   unsigned Size = MemOpLength->getZExtValue();
8994   if (Size == 0) return MI;  // Delete this mem transfer.
8995   
8996   if (Size > 8 || (Size&(Size-1)))
8997     return 0;  // If not 1/2/4/8 bytes, exit.
8998   
8999   // Use an integer load+store unless we can find something better.
9000   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9001   
9002   // Memcpy forces the use of i8* for the source and destination.  That means
9003   // that if you're using memcpy to move one double around, you'll get a cast
9004   // from double* to i8*.  We'd much rather use a double load+store rather than
9005   // an i64 load+store, here because this improves the odds that the source or
9006   // dest address will be promotable.  See if we can find a better type than the
9007   // integer datatype.
9008   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9009     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9010     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9011       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9012       // down through these levels if so.
9013       while (!SrcETy->isSingleValueType()) {
9014         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9015           if (STy->getNumElements() == 1)
9016             SrcETy = STy->getElementType(0);
9017           else
9018             break;
9019         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9020           if (ATy->getNumElements() == 1)
9021             SrcETy = ATy->getElementType();
9022           else
9023             break;
9024         } else
9025           break;
9026       }
9027       
9028       if (SrcETy->isSingleValueType())
9029         NewPtrTy = PointerType::getUnqual(SrcETy);
9030     }
9031   }
9032   
9033   
9034   // If the memcpy/memmove provides better alignment info than we can
9035   // infer, use it.
9036   SrcAlign = std::max(SrcAlign, CopyAlign);
9037   DstAlign = std::max(DstAlign, CopyAlign);
9038   
9039   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9040   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9041   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9042   InsertNewInstBefore(L, *MI);
9043   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9044
9045   // Set the size of the copy to 0, it will be deleted on the next iteration.
9046   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9047   return MI;
9048 }
9049
9050 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9051   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9052   if (MI->getAlignment()->getZExtValue() < Alignment) {
9053     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9054     return MI;
9055   }
9056   
9057   // Extract the length and alignment and fill if they are constant.
9058   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9059   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9060   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9061     return 0;
9062   uint64_t Len = LenC->getZExtValue();
9063   Alignment = MI->getAlignment()->getZExtValue();
9064   
9065   // If the length is zero, this is a no-op
9066   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9067   
9068   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9069   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9070     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9071     
9072     Value *Dest = MI->getDest();
9073     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9074
9075     // Alignment 0 is identity for alignment 1 for memset, but not store.
9076     if (Alignment == 0) Alignment = 1;
9077     
9078     // Extract the fill value and store.
9079     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9080     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9081                                       Alignment), *MI);
9082     
9083     // Set the size of the copy to 0, it will be deleted on the next iteration.
9084     MI->setLength(Constant::getNullValue(LenC->getType()));
9085     return MI;
9086   }
9087
9088   return 0;
9089 }
9090
9091
9092 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9093 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9094 /// the heavy lifting.
9095 ///
9096 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9097   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9098   if (!II) return visitCallSite(&CI);
9099   
9100   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9101   // visitCallSite.
9102   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9103     bool Changed = false;
9104
9105     // memmove/cpy/set of zero bytes is a noop.
9106     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9107       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9108
9109       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9110         if (CI->getZExtValue() == 1) {
9111           // Replace the instruction with just byte operations.  We would
9112           // transform other cases to loads/stores, but we don't know if
9113           // alignment is sufficient.
9114         }
9115     }
9116
9117     // If we have a memmove and the source operation is a constant global,
9118     // then the source and dest pointers can't alias, so we can change this
9119     // into a call to memcpy.
9120     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9121       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9122         if (GVSrc->isConstant()) {
9123           Module *M = CI.getParent()->getParent()->getParent();
9124           Intrinsic::ID MemCpyID;
9125           if (CI.getOperand(3)->getType() == Type::Int32Ty)
9126             MemCpyID = Intrinsic::memcpy_i32;
9127           else
9128             MemCpyID = Intrinsic::memcpy_i64;
9129           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
9130           Changed = true;
9131         }
9132     }
9133
9134     // If we can determine a pointer alignment that is bigger than currently
9135     // set, update the alignment.
9136     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9137       if (Instruction *I = SimplifyMemTransfer(MI))
9138         return I;
9139     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9140       if (Instruction *I = SimplifyMemSet(MSI))
9141         return I;
9142     }
9143           
9144     if (Changed) return II;
9145   } else {
9146     switch (II->getIntrinsicID()) {
9147     default: break;
9148     case Intrinsic::ppc_altivec_lvx:
9149     case Intrinsic::ppc_altivec_lvxl:
9150     case Intrinsic::x86_sse_loadu_ps:
9151     case Intrinsic::x86_sse2_loadu_pd:
9152     case Intrinsic::x86_sse2_loadu_dq:
9153       // Turn PPC lvx     -> load if the pointer is known aligned.
9154       // Turn X86 loadups -> load if the pointer is known aligned.
9155       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9156         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9157                                          PointerType::getUnqual(II->getType()),
9158                                          CI);
9159         return new LoadInst(Ptr);
9160       }
9161       break;
9162     case Intrinsic::ppc_altivec_stvx:
9163     case Intrinsic::ppc_altivec_stvxl:
9164       // Turn stvx -> store if the pointer is known aligned.
9165       if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9166         const Type *OpPtrTy = 
9167           PointerType::getUnqual(II->getOperand(1)->getType());
9168         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9169         return new StoreInst(II->getOperand(1), Ptr);
9170       }
9171       break;
9172     case Intrinsic::x86_sse_storeu_ps:
9173     case Intrinsic::x86_sse2_storeu_pd:
9174     case Intrinsic::x86_sse2_storeu_dq:
9175     case Intrinsic::x86_sse2_storel_dq:
9176       // Turn X86 storeu -> store if the pointer is known aligned.
9177       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9178         const Type *OpPtrTy = 
9179           PointerType::getUnqual(II->getOperand(2)->getType());
9180         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9181         return new StoreInst(II->getOperand(2), Ptr);
9182       }
9183       break;
9184       
9185     case Intrinsic::x86_sse_cvttss2si: {
9186       // These intrinsics only demands the 0th element of its input vector.  If
9187       // we can simplify the input based on that, do so now.
9188       uint64_t UndefElts;
9189       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9190                                                 UndefElts)) {
9191         II->setOperand(1, V);
9192         return II;
9193       }
9194       break;
9195     }
9196       
9197     case Intrinsic::ppc_altivec_vperm:
9198       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9199       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9200         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9201         
9202         // Check that all of the elements are integer constants or undefs.
9203         bool AllEltsOk = true;
9204         for (unsigned i = 0; i != 16; ++i) {
9205           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9206               !isa<UndefValue>(Mask->getOperand(i))) {
9207             AllEltsOk = false;
9208             break;
9209           }
9210         }
9211         
9212         if (AllEltsOk) {
9213           // Cast the input vectors to byte vectors.
9214           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9215           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9216           Value *Result = UndefValue::get(Op0->getType());
9217           
9218           // Only extract each element once.
9219           Value *ExtractedElts[32];
9220           memset(ExtractedElts, 0, sizeof(ExtractedElts));
9221           
9222           for (unsigned i = 0; i != 16; ++i) {
9223             if (isa<UndefValue>(Mask->getOperand(i)))
9224               continue;
9225             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9226             Idx &= 31;  // Match the hardware behavior.
9227             
9228             if (ExtractedElts[Idx] == 0) {
9229               Instruction *Elt = 
9230                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9231               InsertNewInstBefore(Elt, CI);
9232               ExtractedElts[Idx] = Elt;
9233             }
9234           
9235             // Insert this value into the result vector.
9236             Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9237                                                i, "tmp");
9238             InsertNewInstBefore(cast<Instruction>(Result), CI);
9239           }
9240           return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9241         }
9242       }
9243       break;
9244
9245     case Intrinsic::stackrestore: {
9246       // If the save is right next to the restore, remove the restore.  This can
9247       // happen when variable allocas are DCE'd.
9248       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9249         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9250           BasicBlock::iterator BI = SS;
9251           if (&*++BI == II)
9252             return EraseInstFromFunction(CI);
9253         }
9254       }
9255       
9256       // Scan down this block to see if there is another stack restore in the
9257       // same block without an intervening call/alloca.
9258       BasicBlock::iterator BI = II;
9259       TerminatorInst *TI = II->getParent()->getTerminator();
9260       bool CannotRemove = false;
9261       for (++BI; &*BI != TI; ++BI) {
9262         if (isa<AllocaInst>(BI)) {
9263           CannotRemove = true;
9264           break;
9265         }
9266         if (isa<CallInst>(BI)) {
9267           if (!isa<IntrinsicInst>(BI)) {
9268             CannotRemove = true;
9269             break;
9270           }
9271           // If there is a stackrestore below this one, remove this one.
9272           return EraseInstFromFunction(CI);
9273         }
9274       }
9275       
9276       // If the stack restore is in a return/unwind block and if there are no
9277       // allocas or calls between the restore and the return, nuke the restore.
9278       if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9279         return EraseInstFromFunction(CI);
9280       break;
9281     }
9282     }
9283   }
9284
9285   return visitCallSite(II);
9286 }
9287
9288 // InvokeInst simplification
9289 //
9290 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9291   return visitCallSite(&II);
9292 }
9293
9294 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9295 /// passed through the varargs area, we can eliminate the use of the cast.
9296 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9297                                          const CastInst * const CI,
9298                                          const TargetData * const TD,
9299                                          const int ix) {
9300   if (!CI->isLosslessCast())
9301     return false;
9302
9303   // The size of ByVal arguments is derived from the type, so we
9304   // can't change to a type with a different size.  If the size were
9305   // passed explicitly we could avoid this check.
9306   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9307     return true;
9308
9309   const Type* SrcTy = 
9310             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9311   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9312   if (!SrcTy->isSized() || !DstTy->isSized())
9313     return false;
9314   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9315     return false;
9316   return true;
9317 }
9318
9319 // visitCallSite - Improvements for call and invoke instructions.
9320 //
9321 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9322   bool Changed = false;
9323
9324   // If the callee is a constexpr cast of a function, attempt to move the cast
9325   // to the arguments of the call/invoke.
9326   if (transformConstExprCastCall(CS)) return 0;
9327
9328   Value *Callee = CS.getCalledValue();
9329
9330   if (Function *CalleeF = dyn_cast<Function>(Callee))
9331     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9332       Instruction *OldCall = CS.getInstruction();
9333       // If the call and callee calling conventions don't match, this call must
9334       // be unreachable, as the call is undefined.
9335       new StoreInst(ConstantInt::getTrue(),
9336                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9337                                     OldCall);
9338       if (!OldCall->use_empty())
9339         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9340       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9341         return EraseInstFromFunction(*OldCall);
9342       return 0;
9343     }
9344
9345   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9346     // This instruction is not reachable, just remove it.  We insert a store to
9347     // undef so that we know that this code is not reachable, despite the fact
9348     // that we can't modify the CFG here.
9349     new StoreInst(ConstantInt::getTrue(),
9350                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9351                   CS.getInstruction());
9352
9353     if (!CS.getInstruction()->use_empty())
9354       CS.getInstruction()->
9355         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9356
9357     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9358       // Don't break the CFG, insert a dummy cond branch.
9359       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9360                          ConstantInt::getTrue(), II);
9361     }
9362     return EraseInstFromFunction(*CS.getInstruction());
9363   }
9364
9365   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9366     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9367       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9368         return transformCallThroughTrampoline(CS);
9369
9370   const PointerType *PTy = cast<PointerType>(Callee->getType());
9371   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9372   if (FTy->isVarArg()) {
9373     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9374     // See if we can optimize any arguments passed through the varargs area of
9375     // the call.
9376     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9377            E = CS.arg_end(); I != E; ++I, ++ix) {
9378       CastInst *CI = dyn_cast<CastInst>(*I);
9379       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9380         *I = CI->getOperand(0);
9381         Changed = true;
9382       }
9383     }
9384   }
9385
9386   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9387     // Inline asm calls cannot throw - mark them 'nounwind'.
9388     CS.setDoesNotThrow();
9389     Changed = true;
9390   }
9391
9392   return Changed ? CS.getInstruction() : 0;
9393 }
9394
9395 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9396 // attempt to move the cast to the arguments of the call/invoke.
9397 //
9398 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9399   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9400   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9401   if (CE->getOpcode() != Instruction::BitCast || 
9402       !isa<Function>(CE->getOperand(0)))
9403     return false;
9404   Function *Callee = cast<Function>(CE->getOperand(0));
9405   Instruction *Caller = CS.getInstruction();
9406   const PAListPtr &CallerPAL = CS.getParamAttrs();
9407
9408   // Okay, this is a cast from a function to a different type.  Unless doing so
9409   // would cause a type conversion of one of our arguments, change this call to
9410   // be a direct call with arguments casted to the appropriate types.
9411   //
9412   const FunctionType *FT = Callee->getFunctionType();
9413   const Type *OldRetTy = Caller->getType();
9414
9415   if (isa<StructType>(FT->getReturnType()))
9416     return false; // TODO: Handle multiple return values.
9417
9418   // Check to see if we are changing the return type...
9419   if (OldRetTy != FT->getReturnType()) {
9420     if (Callee->isDeclaration() &&
9421         // Conversion is ok if changing from pointer to int of same size.
9422         !(isa<PointerType>(FT->getReturnType()) &&
9423           TD->getIntPtrType() == OldRetTy))
9424       return false;   // Cannot transform this return value.
9425
9426     if (!Caller->use_empty() &&
9427         // void -> non-void is handled specially
9428         FT->getReturnType() != Type::VoidTy &&
9429         !CastInst::isCastable(FT->getReturnType(), OldRetTy))
9430       return false;   // Cannot transform this return value.
9431
9432     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9433       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9434       if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9435         return false;   // Attribute not compatible with transformed value.
9436     }
9437
9438     // If the callsite is an invoke instruction, and the return value is used by
9439     // a PHI node in a successor, we cannot change the return type of the call
9440     // because there is no place to put the cast instruction (without breaking
9441     // the critical edge).  Bail out in this case.
9442     if (!Caller->use_empty())
9443       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9444         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9445              UI != E; ++UI)
9446           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9447             if (PN->getParent() == II->getNormalDest() ||
9448                 PN->getParent() == II->getUnwindDest())
9449               return false;
9450   }
9451
9452   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9453   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9454
9455   CallSite::arg_iterator AI = CS.arg_begin();
9456   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9457     const Type *ParamTy = FT->getParamType(i);
9458     const Type *ActTy = (*AI)->getType();
9459
9460     if (!CastInst::isCastable(ActTy, ParamTy))
9461       return false;   // Cannot transform this parameter value.
9462
9463     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9464       return false;   // Attribute not compatible with transformed value.
9465
9466     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
9467     // Some conversions are safe even if we do not have a body.
9468     // Either we can cast directly, or we can upconvert the argument
9469     bool isConvertible = ActTy == ParamTy ||
9470       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
9471       (ParamTy->isInteger() && ActTy->isInteger() &&
9472        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9473       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
9474        && c->getValue().isStrictlyPositive());
9475     if (Callee->isDeclaration() && !isConvertible) return false;
9476   }
9477
9478   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9479       Callee->isDeclaration())
9480     return false;   // Do not delete arguments unless we have a function body.
9481
9482   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9483       !CallerPAL.isEmpty())
9484     // In this case we have more arguments than the new function type, but we
9485     // won't be dropping them.  Check that these extra arguments have attributes
9486     // that are compatible with being a vararg call argument.
9487     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9488       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9489         break;
9490       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9491       if (PAttrs & ParamAttr::VarArgsIncompatible)
9492         return false;
9493     }
9494
9495   // Okay, we decided that this is a safe thing to do: go ahead and start
9496   // inserting cast instructions as necessary...
9497   std::vector<Value*> Args;
9498   Args.reserve(NumActualArgs);
9499   SmallVector<ParamAttrsWithIndex, 8> attrVec;
9500   attrVec.reserve(NumCommonArgs);
9501
9502   // Get any return attributes.
9503   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9504
9505   // If the return value is not being used, the type may not be compatible
9506   // with the existing attributes.  Wipe out any problematic attributes.
9507   RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
9508
9509   // Add the new return attributes.
9510   if (RAttrs)
9511     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
9512
9513   AI = CS.arg_begin();
9514   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9515     const Type *ParamTy = FT->getParamType(i);
9516     if ((*AI)->getType() == ParamTy) {
9517       Args.push_back(*AI);
9518     } else {
9519       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9520           false, ParamTy, false);
9521       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9522       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9523     }
9524
9525     // Add any parameter attributes.
9526     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9527       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9528   }
9529
9530   // If the function takes more arguments than the call was taking, add them
9531   // now...
9532   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9533     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9534
9535   // If we are removing arguments to the function, emit an obnoxious warning...
9536   if (FT->getNumParams() < NumActualArgs) {
9537     if (!FT->isVarArg()) {
9538       cerr << "WARNING: While resolving call to function '"
9539            << Callee->getName() << "' arguments were dropped!\n";
9540     } else {
9541       // Add all of the arguments in their promoted form to the arg list...
9542       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9543         const Type *PTy = getPromotedType((*AI)->getType());
9544         if (PTy != (*AI)->getType()) {
9545           // Must promote to pass through va_arg area!
9546           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9547                                                                 PTy, false);
9548           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9549           InsertNewInstBefore(Cast, *Caller);
9550           Args.push_back(Cast);
9551         } else {
9552           Args.push_back(*AI);
9553         }
9554
9555         // Add any parameter attributes.
9556         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9557           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9558       }
9559     }
9560   }
9561
9562   if (FT->getReturnType() == Type::VoidTy)
9563     Caller->setName("");   // Void type should not have a name.
9564
9565   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9566
9567   Instruction *NC;
9568   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9569     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9570                             Args.begin(), Args.end(),
9571                             Caller->getName(), Caller);
9572     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9573     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9574   } else {
9575     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9576                           Caller->getName(), Caller);
9577     CallInst *CI = cast<CallInst>(Caller);
9578     if (CI->isTailCall())
9579       cast<CallInst>(NC)->setTailCall();
9580     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9581     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9582   }
9583
9584   // Insert a cast of the return type as necessary.
9585   Value *NV = NC;
9586   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9587     if (NV->getType() != Type::VoidTy) {
9588       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9589                                                             OldRetTy, false);
9590       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9591
9592       // If this is an invoke instruction, we should insert it after the first
9593       // non-phi, instruction in the normal successor block.
9594       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9595         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9596         InsertNewInstBefore(NC, *I);
9597       } else {
9598         // Otherwise, it's a call, just insert cast right after the call instr
9599         InsertNewInstBefore(NC, *Caller);
9600       }
9601       AddUsersToWorkList(*Caller);
9602     } else {
9603       NV = UndefValue::get(Caller->getType());
9604     }
9605   }
9606
9607   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9608     Caller->replaceAllUsesWith(NV);
9609   Caller->eraseFromParent();
9610   RemoveFromWorkList(Caller);
9611   return true;
9612 }
9613
9614 // transformCallThroughTrampoline - Turn a call to a function created by the
9615 // init_trampoline intrinsic into a direct call to the underlying function.
9616 //
9617 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9618   Value *Callee = CS.getCalledValue();
9619   const PointerType *PTy = cast<PointerType>(Callee->getType());
9620   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9621   const PAListPtr &Attrs = CS.getParamAttrs();
9622
9623   // If the call already has the 'nest' attribute somewhere then give up -
9624   // otherwise 'nest' would occur twice after splicing in the chain.
9625   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9626     return 0;
9627
9628   IntrinsicInst *Tramp =
9629     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9630
9631   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9632   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9633   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9634
9635   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9636   if (!NestAttrs.isEmpty()) {
9637     unsigned NestIdx = 1;
9638     const Type *NestTy = 0;
9639     ParameterAttributes NestAttr = ParamAttr::None;
9640
9641     // Look for a parameter marked with the 'nest' attribute.
9642     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9643          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9644       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9645         // Record the parameter type and any other attributes.
9646         NestTy = *I;
9647         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9648         break;
9649       }
9650
9651     if (NestTy) {
9652       Instruction *Caller = CS.getInstruction();
9653       std::vector<Value*> NewArgs;
9654       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9655
9656       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9657       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9658
9659       // Insert the nest argument into the call argument list, which may
9660       // mean appending it.  Likewise for attributes.
9661
9662       // Add any function result attributes.
9663       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9664         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9665
9666       {
9667         unsigned Idx = 1;
9668         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9669         do {
9670           if (Idx == NestIdx) {
9671             // Add the chain argument and attributes.
9672             Value *NestVal = Tramp->getOperand(3);
9673             if (NestVal->getType() != NestTy)
9674               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9675             NewArgs.push_back(NestVal);
9676             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9677           }
9678
9679           if (I == E)
9680             break;
9681
9682           // Add the original argument and attributes.
9683           NewArgs.push_back(*I);
9684           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9685             NewAttrs.push_back
9686               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9687
9688           ++Idx, ++I;
9689         } while (1);
9690       }
9691
9692       // The trampoline may have been bitcast to a bogus type (FTy).
9693       // Handle this by synthesizing a new function type, equal to FTy
9694       // with the chain parameter inserted.
9695
9696       std::vector<const Type*> NewTypes;
9697       NewTypes.reserve(FTy->getNumParams()+1);
9698
9699       // Insert the chain's type into the list of parameter types, which may
9700       // mean appending it.
9701       {
9702         unsigned Idx = 1;
9703         FunctionType::param_iterator I = FTy->param_begin(),
9704           E = FTy->param_end();
9705
9706         do {
9707           if (Idx == NestIdx)
9708             // Add the chain's type.
9709             NewTypes.push_back(NestTy);
9710
9711           if (I == E)
9712             break;
9713
9714           // Add the original type.
9715           NewTypes.push_back(*I);
9716
9717           ++Idx, ++I;
9718         } while (1);
9719       }
9720
9721       // Replace the trampoline call with a direct call.  Let the generic
9722       // code sort out any function type mismatches.
9723       FunctionType *NewFTy =
9724         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9725       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9726         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9727       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9728
9729       Instruction *NewCaller;
9730       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9731         NewCaller = InvokeInst::Create(NewCallee,
9732                                        II->getNormalDest(), II->getUnwindDest(),
9733                                        NewArgs.begin(), NewArgs.end(),
9734                                        Caller->getName(), Caller);
9735         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9736         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9737       } else {
9738         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9739                                      Caller->getName(), Caller);
9740         if (cast<CallInst>(Caller)->isTailCall())
9741           cast<CallInst>(NewCaller)->setTailCall();
9742         cast<CallInst>(NewCaller)->
9743           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9744         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9745       }
9746       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9747         Caller->replaceAllUsesWith(NewCaller);
9748       Caller->eraseFromParent();
9749       RemoveFromWorkList(Caller);
9750       return 0;
9751     }
9752   }
9753
9754   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9755   // parameter, there is no need to adjust the argument list.  Let the generic
9756   // code sort out any function type mismatches.
9757   Constant *NewCallee =
9758     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9759   CS.setCalledFunction(NewCallee);
9760   return CS.getInstruction();
9761 }
9762
9763 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9764 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9765 /// and a single binop.
9766 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9767   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9768   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9769          isa<CmpInst>(FirstInst));
9770   unsigned Opc = FirstInst->getOpcode();
9771   Value *LHSVal = FirstInst->getOperand(0);
9772   Value *RHSVal = FirstInst->getOperand(1);
9773     
9774   const Type *LHSType = LHSVal->getType();
9775   const Type *RHSType = RHSVal->getType();
9776   
9777   // Scan to see if all operands are the same opcode, all have one use, and all
9778   // kill their operands (i.e. the operands have one use).
9779   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9780     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9781     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9782         // Verify type of the LHS matches so we don't fold cmp's of different
9783         // types or GEP's with different index types.
9784         I->getOperand(0)->getType() != LHSType ||
9785         I->getOperand(1)->getType() != RHSType)
9786       return 0;
9787
9788     // If they are CmpInst instructions, check their predicates
9789     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9790       if (cast<CmpInst>(I)->getPredicate() !=
9791           cast<CmpInst>(FirstInst)->getPredicate())
9792         return 0;
9793     
9794     // Keep track of which operand needs a phi node.
9795     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9796     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9797   }
9798   
9799   // Otherwise, this is safe to transform, determine if it is profitable.
9800
9801   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9802   // Indexes are often folded into load/store instructions, so we don't want to
9803   // hide them behind a phi.
9804   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9805     return 0;
9806   
9807   Value *InLHS = FirstInst->getOperand(0);
9808   Value *InRHS = FirstInst->getOperand(1);
9809   PHINode *NewLHS = 0, *NewRHS = 0;
9810   if (LHSVal == 0) {
9811     NewLHS = PHINode::Create(LHSType,
9812                              FirstInst->getOperand(0)->getName() + ".pn");
9813     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9814     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9815     InsertNewInstBefore(NewLHS, PN);
9816     LHSVal = NewLHS;
9817   }
9818   
9819   if (RHSVal == 0) {
9820     NewRHS = PHINode::Create(RHSType,
9821                              FirstInst->getOperand(1)->getName() + ".pn");
9822     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9823     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9824     InsertNewInstBefore(NewRHS, PN);
9825     RHSVal = NewRHS;
9826   }
9827   
9828   // Add all operands to the new PHIs.
9829   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9830     if (NewLHS) {
9831       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9832       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9833     }
9834     if (NewRHS) {
9835       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9836       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9837     }
9838   }
9839     
9840   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9841     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9842   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9843     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9844                            RHSVal);
9845   else {
9846     assert(isa<GetElementPtrInst>(FirstInst));
9847     return GetElementPtrInst::Create(LHSVal, RHSVal);
9848   }
9849 }
9850
9851 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9852 /// of the block that defines it.  This means that it must be obvious the value
9853 /// of the load is not changed from the point of the load to the end of the
9854 /// block it is in.
9855 ///
9856 /// Finally, it is safe, but not profitable, to sink a load targetting a
9857 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9858 /// to a register.
9859 static bool isSafeToSinkLoad(LoadInst *L) {
9860   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9861   
9862   for (++BBI; BBI != E; ++BBI)
9863     if (BBI->mayWriteToMemory())
9864       return false;
9865   
9866   // Check for non-address taken alloca.  If not address-taken already, it isn't
9867   // profitable to do this xform.
9868   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9869     bool isAddressTaken = false;
9870     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9871          UI != E; ++UI) {
9872       if (isa<LoadInst>(UI)) continue;
9873       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9874         // If storing TO the alloca, then the address isn't taken.
9875         if (SI->getOperand(1) == AI) continue;
9876       }
9877       isAddressTaken = true;
9878       break;
9879     }
9880     
9881     if (!isAddressTaken)
9882       return false;
9883   }
9884   
9885   return true;
9886 }
9887
9888
9889 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9890 // operator and they all are only used by the PHI, PHI together their
9891 // inputs, and do the operation once, to the result of the PHI.
9892 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9893   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9894
9895   // Scan the instruction, looking for input operations that can be folded away.
9896   // If all input operands to the phi are the same instruction (e.g. a cast from
9897   // the same type or "+42") we can pull the operation through the PHI, reducing
9898   // code size and simplifying code.
9899   Constant *ConstantOp = 0;
9900   const Type *CastSrcTy = 0;
9901   bool isVolatile = false;
9902   if (isa<CastInst>(FirstInst)) {
9903     CastSrcTy = FirstInst->getOperand(0)->getType();
9904   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9905     // Can fold binop, compare or shift here if the RHS is a constant, 
9906     // otherwise call FoldPHIArgBinOpIntoPHI.
9907     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9908     if (ConstantOp == 0)
9909       return FoldPHIArgBinOpIntoPHI(PN);
9910   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9911     isVolatile = LI->isVolatile();
9912     // We can't sink the load if the loaded value could be modified between the
9913     // load and the PHI.
9914     if (LI->getParent() != PN.getIncomingBlock(0) ||
9915         !isSafeToSinkLoad(LI))
9916       return 0;
9917   } else if (isa<GetElementPtrInst>(FirstInst)) {
9918     if (FirstInst->getNumOperands() == 2)
9919       return FoldPHIArgBinOpIntoPHI(PN);
9920     // Can't handle general GEPs yet.
9921     return 0;
9922   } else {
9923     return 0;  // Cannot fold this operation.
9924   }
9925
9926   // Check to see if all arguments are the same operation.
9927   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9928     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9929     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9930     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9931       return 0;
9932     if (CastSrcTy) {
9933       if (I->getOperand(0)->getType() != CastSrcTy)
9934         return 0;  // Cast operation must match.
9935     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9936       // We can't sink the load if the loaded value could be modified between 
9937       // the load and the PHI.
9938       if (LI->isVolatile() != isVolatile ||
9939           LI->getParent() != PN.getIncomingBlock(i) ||
9940           !isSafeToSinkLoad(LI))
9941         return 0;
9942       
9943       // If the PHI is volatile and its block has multiple successors, sinking
9944       // it would remove a load of the volatile value from the path through the
9945       // other successor.
9946       if (isVolatile &&
9947           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9948         return 0;
9949
9950       
9951     } else if (I->getOperand(1) != ConstantOp) {
9952       return 0;
9953     }
9954   }
9955
9956   // Okay, they are all the same operation.  Create a new PHI node of the
9957   // correct type, and PHI together all of the LHS's of the instructions.
9958   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9959                                    PN.getName()+".in");
9960   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9961
9962   Value *InVal = FirstInst->getOperand(0);
9963   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9964
9965   // Add all operands to the new PHI.
9966   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9967     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9968     if (NewInVal != InVal)
9969       InVal = 0;
9970     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9971   }
9972
9973   Value *PhiVal;
9974   if (InVal) {
9975     // The new PHI unions all of the same values together.  This is really
9976     // common, so we handle it intelligently here for compile-time speed.
9977     PhiVal = InVal;
9978     delete NewPN;
9979   } else {
9980     InsertNewInstBefore(NewPN, PN);
9981     PhiVal = NewPN;
9982   }
9983
9984   // Insert and return the new operation.
9985   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9986     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9987   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9988     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9989   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9990     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9991                            PhiVal, ConstantOp);
9992   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9993   
9994   // If this was a volatile load that we are merging, make sure to loop through
9995   // and mark all the input loads as non-volatile.  If we don't do this, we will
9996   // insert a new volatile load and the old ones will not be deletable.
9997   if (isVolatile)
9998     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9999       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10000   
10001   return new LoadInst(PhiVal, "", isVolatile);
10002 }
10003
10004 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10005 /// that is dead.
10006 static bool DeadPHICycle(PHINode *PN,
10007                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10008   if (PN->use_empty()) return true;
10009   if (!PN->hasOneUse()) return false;
10010
10011   // Remember this node, and if we find the cycle, return.
10012   if (!PotentiallyDeadPHIs.insert(PN))
10013     return true;
10014   
10015   // Don't scan crazily complex things.
10016   if (PotentiallyDeadPHIs.size() == 16)
10017     return false;
10018
10019   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10020     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10021
10022   return false;
10023 }
10024
10025 /// PHIsEqualValue - Return true if this phi node is always equal to
10026 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10027 ///   z = some value; x = phi (y, z); y = phi (x, z)
10028 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10029                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10030   // See if we already saw this PHI node.
10031   if (!ValueEqualPHIs.insert(PN))
10032     return true;
10033   
10034   // Don't scan crazily complex things.
10035   if (ValueEqualPHIs.size() == 16)
10036     return false;
10037  
10038   // Scan the operands to see if they are either phi nodes or are equal to
10039   // the value.
10040   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10041     Value *Op = PN->getIncomingValue(i);
10042     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10043       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10044         return false;
10045     } else if (Op != NonPhiInVal)
10046       return false;
10047   }
10048   
10049   return true;
10050 }
10051
10052
10053 // PHINode simplification
10054 //
10055 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10056   // If LCSSA is around, don't mess with Phi nodes
10057   if (MustPreserveLCSSA) return 0;
10058   
10059   if (Value *V = PN.hasConstantValue())
10060     return ReplaceInstUsesWith(PN, V);
10061
10062   // If all PHI operands are the same operation, pull them through the PHI,
10063   // reducing code size.
10064   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10065       PN.getIncomingValue(0)->hasOneUse())
10066     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10067       return Result;
10068
10069   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10070   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10071   // PHI)... break the cycle.
10072   if (PN.hasOneUse()) {
10073     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10074     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10075       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10076       PotentiallyDeadPHIs.insert(&PN);
10077       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10078         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10079     }
10080    
10081     // If this phi has a single use, and if that use just computes a value for
10082     // the next iteration of a loop, delete the phi.  This occurs with unused
10083     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10084     // common case here is good because the only other things that catch this
10085     // are induction variable analysis (sometimes) and ADCE, which is only run
10086     // late.
10087     if (PHIUser->hasOneUse() &&
10088         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10089         PHIUser->use_back() == &PN) {
10090       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10091     }
10092   }
10093
10094   // We sometimes end up with phi cycles that non-obviously end up being the
10095   // same value, for example:
10096   //   z = some value; x = phi (y, z); y = phi (x, z)
10097   // where the phi nodes don't necessarily need to be in the same block.  Do a
10098   // quick check to see if the PHI node only contains a single non-phi value, if
10099   // so, scan to see if the phi cycle is actually equal to that value.
10100   {
10101     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10102     // Scan for the first non-phi operand.
10103     while (InValNo != NumOperandVals && 
10104            isa<PHINode>(PN.getIncomingValue(InValNo)))
10105       ++InValNo;
10106
10107     if (InValNo != NumOperandVals) {
10108       Value *NonPhiInVal = PN.getOperand(InValNo);
10109       
10110       // Scan the rest of the operands to see if there are any conflicts, if so
10111       // there is no need to recursively scan other phis.
10112       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10113         Value *OpVal = PN.getIncomingValue(InValNo);
10114         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10115           break;
10116       }
10117       
10118       // If we scanned over all operands, then we have one unique value plus
10119       // phi values.  Scan PHI nodes to see if they all merge in each other or
10120       // the value.
10121       if (InValNo == NumOperandVals) {
10122         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10123         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10124           return ReplaceInstUsesWith(PN, NonPhiInVal);
10125       }
10126     }
10127   }
10128   return 0;
10129 }
10130
10131 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10132                                    Instruction *InsertPoint,
10133                                    InstCombiner *IC) {
10134   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10135   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10136   // We must cast correctly to the pointer type. Ensure that we
10137   // sign extend the integer value if it is smaller as this is
10138   // used for address computation.
10139   Instruction::CastOps opcode = 
10140      (VTySize < PtrSize ? Instruction::SExt :
10141       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10142   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10143 }
10144
10145
10146 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10147   Value *PtrOp = GEP.getOperand(0);
10148   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10149   // If so, eliminate the noop.
10150   if (GEP.getNumOperands() == 1)
10151     return ReplaceInstUsesWith(GEP, PtrOp);
10152
10153   if (isa<UndefValue>(GEP.getOperand(0)))
10154     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10155
10156   bool HasZeroPointerIndex = false;
10157   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10158     HasZeroPointerIndex = C->isNullValue();
10159
10160   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10161     return ReplaceInstUsesWith(GEP, PtrOp);
10162
10163   // Eliminate unneeded casts for indices.
10164   bool MadeChange = false;
10165   
10166   gep_type_iterator GTI = gep_type_begin(GEP);
10167   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
10168     if (isa<SequentialType>(*GTI)) {
10169       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
10170         if (CI->getOpcode() == Instruction::ZExt ||
10171             CI->getOpcode() == Instruction::SExt) {
10172           const Type *SrcTy = CI->getOperand(0)->getType();
10173           // We can eliminate a cast from i32 to i64 iff the target 
10174           // is a 32-bit pointer target.
10175           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10176             MadeChange = true;
10177             GEP.setOperand(i, CI->getOperand(0));
10178           }
10179         }
10180       }
10181       // If we are using a wider index than needed for this platform, shrink it
10182       // to what we need.  If the incoming value needs a cast instruction,
10183       // insert it.  This explicit cast can make subsequent optimizations more
10184       // obvious.
10185       Value *Op = GEP.getOperand(i);
10186       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10187         if (Constant *C = dyn_cast<Constant>(Op)) {
10188           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
10189           MadeChange = true;
10190         } else {
10191           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10192                                 GEP);
10193           GEP.setOperand(i, Op);
10194           MadeChange = true;
10195         }
10196       }
10197     }
10198   }
10199   if (MadeChange) return &GEP;
10200
10201   // If this GEP instruction doesn't move the pointer, and if the input operand
10202   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10203   // real input to the dest type.
10204   if (GEP.hasAllZeroIndices()) {
10205     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10206       // If the bitcast is of an allocation, and the allocation will be
10207       // converted to match the type of the cast, don't touch this.
10208       if (isa<AllocationInst>(BCI->getOperand(0))) {
10209         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10210         if (Instruction *I = visitBitCast(*BCI)) {
10211           if (I != BCI) {
10212             I->takeName(BCI);
10213             BCI->getParent()->getInstList().insert(BCI, I);
10214             ReplaceInstUsesWith(*BCI, I);
10215           }
10216           return &GEP;
10217         }
10218       }
10219       return new BitCastInst(BCI->getOperand(0), GEP.getType());
10220     }
10221   }
10222   
10223   // Combine Indices - If the source pointer to this getelementptr instruction
10224   // is a getelementptr instruction, combine the indices of the two
10225   // getelementptr instructions into a single instruction.
10226   //
10227   SmallVector<Value*, 8> SrcGEPOperands;
10228   if (User *Src = dyn_castGetElementPtr(PtrOp))
10229     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10230
10231   if (!SrcGEPOperands.empty()) {
10232     // Note that if our source is a gep chain itself that we wait for that
10233     // chain to be resolved before we perform this transformation.  This
10234     // avoids us creating a TON of code in some cases.
10235     //
10236     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10237         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10238       return 0;   // Wait until our source is folded to completion.
10239
10240     SmallVector<Value*, 8> Indices;
10241
10242     // Find out whether the last index in the source GEP is a sequential idx.
10243     bool EndsWithSequential = false;
10244     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10245            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10246       EndsWithSequential = !isa<StructType>(*I);
10247
10248     // Can we combine the two pointer arithmetics offsets?
10249     if (EndsWithSequential) {
10250       // Replace: gep (gep %P, long B), long A, ...
10251       // With:    T = long A+B; gep %P, T, ...
10252       //
10253       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10254       if (SO1 == Constant::getNullValue(SO1->getType())) {
10255         Sum = GO1;
10256       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10257         Sum = SO1;
10258       } else {
10259         // If they aren't the same type, convert both to an integer of the
10260         // target's pointer size.
10261         if (SO1->getType() != GO1->getType()) {
10262           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10263             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10264           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10265             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10266           } else {
10267             unsigned PS = TD->getPointerSizeInBits();
10268             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10269               // Convert GO1 to SO1's type.
10270               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10271
10272             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10273               // Convert SO1 to GO1's type.
10274               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10275             } else {
10276               const Type *PT = TD->getIntPtrType();
10277               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10278               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10279             }
10280           }
10281         }
10282         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10283           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10284         else {
10285           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10286           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10287         }
10288       }
10289
10290       // Recycle the GEP we already have if possible.
10291       if (SrcGEPOperands.size() == 2) {
10292         GEP.setOperand(0, SrcGEPOperands[0]);
10293         GEP.setOperand(1, Sum);
10294         return &GEP;
10295       } else {
10296         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10297                        SrcGEPOperands.end()-1);
10298         Indices.push_back(Sum);
10299         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10300       }
10301     } else if (isa<Constant>(*GEP.idx_begin()) &&
10302                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10303                SrcGEPOperands.size() != 1) {
10304       // Otherwise we can do the fold if the first index of the GEP is a zero
10305       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10306                      SrcGEPOperands.end());
10307       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10308     }
10309
10310     if (!Indices.empty())
10311       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10312                                        Indices.end(), GEP.getName());
10313
10314   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10315     // GEP of global variable.  If all of the indices for this GEP are
10316     // constants, we can promote this to a constexpr instead of an instruction.
10317
10318     // Scan for nonconstants...
10319     SmallVector<Constant*, 8> Indices;
10320     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10321     for (; I != E && isa<Constant>(*I); ++I)
10322       Indices.push_back(cast<Constant>(*I));
10323
10324     if (I == E) {  // If they are all constants...
10325       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10326                                                     &Indices[0],Indices.size());
10327
10328       // Replace all uses of the GEP with the new constexpr...
10329       return ReplaceInstUsesWith(GEP, CE);
10330     }
10331   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10332     if (!isa<PointerType>(X->getType())) {
10333       // Not interesting.  Source pointer must be a cast from pointer.
10334     } else if (HasZeroPointerIndex) {
10335       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10336       // into     : GEP [10 x i8]* X, i32 0, ...
10337       //
10338       // This occurs when the program declares an array extern like "int X[];"
10339       //
10340       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10341       const PointerType *XTy = cast<PointerType>(X->getType());
10342       if (const ArrayType *XATy =
10343           dyn_cast<ArrayType>(XTy->getElementType()))
10344         if (const ArrayType *CATy =
10345             dyn_cast<ArrayType>(CPTy->getElementType()))
10346           if (CATy->getElementType() == XATy->getElementType()) {
10347             // At this point, we know that the cast source type is a pointer
10348             // to an array of the same type as the destination pointer
10349             // array.  Because the array type is never stepped over (there
10350             // is a leading zero) we can fold the cast into this GEP.
10351             GEP.setOperand(0, X);
10352             return &GEP;
10353           }
10354     } else if (GEP.getNumOperands() == 2) {
10355       // Transform things like:
10356       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10357       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10358       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10359       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10360       if (isa<ArrayType>(SrcElTy) &&
10361           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10362           TD->getABITypeSize(ResElTy)) {
10363         Value *Idx[2];
10364         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10365         Idx[1] = GEP.getOperand(1);
10366         Value *V = InsertNewInstBefore(
10367                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10368         // V and GEP are both pointer types --> BitCast
10369         return new BitCastInst(V, GEP.getType());
10370       }
10371       
10372       // Transform things like:
10373       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10374       //   (where tmp = 8*tmp2) into:
10375       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10376       
10377       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10378         uint64_t ArrayEltSize =
10379             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10380         
10381         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10382         // allow either a mul, shift, or constant here.
10383         Value *NewIdx = 0;
10384         ConstantInt *Scale = 0;
10385         if (ArrayEltSize == 1) {
10386           NewIdx = GEP.getOperand(1);
10387           Scale = ConstantInt::get(NewIdx->getType(), 1);
10388         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10389           NewIdx = ConstantInt::get(CI->getType(), 1);
10390           Scale = CI;
10391         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10392           if (Inst->getOpcode() == Instruction::Shl &&
10393               isa<ConstantInt>(Inst->getOperand(1))) {
10394             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10395             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10396             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10397             NewIdx = Inst->getOperand(0);
10398           } else if (Inst->getOpcode() == Instruction::Mul &&
10399                      isa<ConstantInt>(Inst->getOperand(1))) {
10400             Scale = cast<ConstantInt>(Inst->getOperand(1));
10401             NewIdx = Inst->getOperand(0);
10402           }
10403         }
10404         
10405         // If the index will be to exactly the right offset with the scale taken
10406         // out, perform the transformation. Note, we don't know whether Scale is
10407         // signed or not. We'll use unsigned version of division/modulo
10408         // operation after making sure Scale doesn't have the sign bit set.
10409         if (Scale && Scale->getSExtValue() >= 0LL &&
10410             Scale->getZExtValue() % ArrayEltSize == 0) {
10411           Scale = ConstantInt::get(Scale->getType(),
10412                                    Scale->getZExtValue() / ArrayEltSize);
10413           if (Scale->getZExtValue() != 1) {
10414             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10415                                                        false /*ZExt*/);
10416             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10417             NewIdx = InsertNewInstBefore(Sc, GEP);
10418           }
10419
10420           // Insert the new GEP instruction.
10421           Value *Idx[2];
10422           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10423           Idx[1] = NewIdx;
10424           Instruction *NewGEP =
10425             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10426           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10427           // The NewGEP must be pointer typed, so must the old one -> BitCast
10428           return new BitCastInst(NewGEP, GEP.getType());
10429         }
10430       }
10431     }
10432   }
10433
10434   return 0;
10435 }
10436
10437 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10438   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10439   if (AI.isArrayAllocation()) {  // Check C != 1
10440     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10441       const Type *NewTy = 
10442         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10443       AllocationInst *New = 0;
10444
10445       // Create and insert the replacement instruction...
10446       if (isa<MallocInst>(AI))
10447         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10448       else {
10449         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10450         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10451       }
10452
10453       InsertNewInstBefore(New, AI);
10454
10455       // Scan to the end of the allocation instructions, to skip over a block of
10456       // allocas if possible...
10457       //
10458       BasicBlock::iterator It = New;
10459       while (isa<AllocationInst>(*It)) ++It;
10460
10461       // Now that I is pointing to the first non-allocation-inst in the block,
10462       // insert our getelementptr instruction...
10463       //
10464       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10465       Value *Idx[2];
10466       Idx[0] = NullIdx;
10467       Idx[1] = NullIdx;
10468       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10469                                            New->getName()+".sub", It);
10470
10471       // Now make everything use the getelementptr instead of the original
10472       // allocation.
10473       return ReplaceInstUsesWith(AI, V);
10474     } else if (isa<UndefValue>(AI.getArraySize())) {
10475       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10476     }
10477   }
10478
10479   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10480   // Note that we only do this for alloca's, because malloc should allocate and
10481   // return a unique pointer, even for a zero byte allocation.
10482   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10483       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10484     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10485
10486   return 0;
10487 }
10488
10489 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10490   Value *Op = FI.getOperand(0);
10491
10492   // free undef -> unreachable.
10493   if (isa<UndefValue>(Op)) {
10494     // Insert a new store to null because we cannot modify the CFG here.
10495     new StoreInst(ConstantInt::getTrue(),
10496                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10497     return EraseInstFromFunction(FI);
10498   }
10499   
10500   // If we have 'free null' delete the instruction.  This can happen in stl code
10501   // when lots of inlining happens.
10502   if (isa<ConstantPointerNull>(Op))
10503     return EraseInstFromFunction(FI);
10504   
10505   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10506   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10507     FI.setOperand(0, CI->getOperand(0));
10508     return &FI;
10509   }
10510   
10511   // Change free (gep X, 0,0,0,0) into free(X)
10512   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10513     if (GEPI->hasAllZeroIndices()) {
10514       AddToWorkList(GEPI);
10515       FI.setOperand(0, GEPI->getOperand(0));
10516       return &FI;
10517     }
10518   }
10519   
10520   // Change free(malloc) into nothing, if the malloc has a single use.
10521   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10522     if (MI->hasOneUse()) {
10523       EraseInstFromFunction(FI);
10524       return EraseInstFromFunction(*MI);
10525     }
10526
10527   return 0;
10528 }
10529
10530
10531 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10532 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10533                                         const TargetData *TD) {
10534   User *CI = cast<User>(LI.getOperand(0));
10535   Value *CastOp = CI->getOperand(0);
10536
10537   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10538     // Instead of loading constant c string, use corresponding integer value
10539     // directly if string length is small enough.
10540     const std::string &Str = CE->getOperand(0)->getStringValue();
10541     if (!Str.empty()) {
10542       unsigned len = Str.length();
10543       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10544       unsigned numBits = Ty->getPrimitiveSizeInBits();
10545       // Replace LI with immediate integer store.
10546       if ((numBits >> 3) == len + 1) {
10547         APInt StrVal(numBits, 0);
10548         APInt SingleChar(numBits, 0);
10549         if (TD->isLittleEndian()) {
10550           for (signed i = len-1; i >= 0; i--) {
10551             SingleChar = (uint64_t) Str[i];
10552             StrVal = (StrVal << 8) | SingleChar;
10553           }
10554         } else {
10555           for (unsigned i = 0; i < len; i++) {
10556             SingleChar = (uint64_t) Str[i];
10557             StrVal = (StrVal << 8) | SingleChar;
10558           }
10559           // Append NULL at the end.
10560           SingleChar = 0;
10561           StrVal = (StrVal << 8) | SingleChar;
10562         }
10563         Value *NL = ConstantInt::get(StrVal);
10564         return IC.ReplaceInstUsesWith(LI, NL);
10565       }
10566     }
10567   }
10568
10569   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10570   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10571     const Type *SrcPTy = SrcTy->getElementType();
10572
10573     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10574          isa<VectorType>(DestPTy)) {
10575       // If the source is an array, the code below will not succeed.  Check to
10576       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10577       // constants.
10578       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10579         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10580           if (ASrcTy->getNumElements() != 0) {
10581             Value *Idxs[2];
10582             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10583             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10584             SrcTy = cast<PointerType>(CastOp->getType());
10585             SrcPTy = SrcTy->getElementType();
10586           }
10587
10588       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10589             isa<VectorType>(SrcPTy)) &&
10590           // Do not allow turning this into a load of an integer, which is then
10591           // casted to a pointer, this pessimizes pointer analysis a lot.
10592           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10593           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10594                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10595
10596         // Okay, we are casting from one integer or pointer type to another of
10597         // the same size.  Instead of casting the pointer before the load, cast
10598         // the result of the loaded value.
10599         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10600                                                              CI->getName(),
10601                                                          LI.isVolatile()),LI);
10602         // Now cast the result of the load.
10603         return new BitCastInst(NewLoad, LI.getType());
10604       }
10605     }
10606   }
10607   return 0;
10608 }
10609
10610 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10611 /// from this value cannot trap.  If it is not obviously safe to load from the
10612 /// specified pointer, we do a quick local scan of the basic block containing
10613 /// ScanFrom, to determine if the address is already accessed.
10614 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10615   // If it is an alloca it is always safe to load from.
10616   if (isa<AllocaInst>(V)) return true;
10617
10618   // If it is a global variable it is mostly safe to load from.
10619   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10620     // Don't try to evaluate aliases.  External weak GV can be null.
10621     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10622
10623   // Otherwise, be a little bit agressive by scanning the local block where we
10624   // want to check to see if the pointer is already being loaded or stored
10625   // from/to.  If so, the previous load or store would have already trapped,
10626   // so there is no harm doing an extra load (also, CSE will later eliminate
10627   // the load entirely).
10628   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10629
10630   while (BBI != E) {
10631     --BBI;
10632
10633     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10634       if (LI->getOperand(0) == V) return true;
10635     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10636       if (SI->getOperand(1) == V) return true;
10637
10638   }
10639   return false;
10640 }
10641
10642 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10643 /// until we find the underlying object a pointer is referring to or something
10644 /// we don't understand.  Note that the returned pointer may be offset from the
10645 /// input, because we ignore GEP indices.
10646 static Value *GetUnderlyingObject(Value *Ptr) {
10647   while (1) {
10648     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10649       if (CE->getOpcode() == Instruction::BitCast ||
10650           CE->getOpcode() == Instruction::GetElementPtr)
10651         Ptr = CE->getOperand(0);
10652       else
10653         return Ptr;
10654     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10655       Ptr = BCI->getOperand(0);
10656     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10657       Ptr = GEP->getOperand(0);
10658     } else {
10659       return Ptr;
10660     }
10661   }
10662 }
10663
10664 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10665   Value *Op = LI.getOperand(0);
10666
10667   // Attempt to improve the alignment.
10668   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10669   if (KnownAlign >
10670       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10671                                 LI.getAlignment()))
10672     LI.setAlignment(KnownAlign);
10673
10674   // load (cast X) --> cast (load X) iff safe
10675   if (isa<CastInst>(Op))
10676     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10677       return Res;
10678
10679   // None of the following transforms are legal for volatile loads.
10680   if (LI.isVolatile()) return 0;
10681   
10682   if (&LI.getParent()->front() != &LI) {
10683     BasicBlock::iterator BBI = &LI; --BBI;
10684     // If the instruction immediately before this is a store to the same
10685     // address, do a simple form of store->load forwarding.
10686     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10687       if (SI->getOperand(1) == LI.getOperand(0))
10688         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10689     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10690       if (LIB->getOperand(0) == LI.getOperand(0))
10691         return ReplaceInstUsesWith(LI, LIB);
10692   }
10693
10694   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10695     const Value *GEPI0 = GEPI->getOperand(0);
10696     // TODO: Consider a target hook for valid address spaces for this xform.
10697     if (isa<ConstantPointerNull>(GEPI0) &&
10698         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10699       // Insert a new store to null instruction before the load to indicate
10700       // that this code is not reachable.  We do this instead of inserting
10701       // an unreachable instruction directly because we cannot modify the
10702       // CFG.
10703       new StoreInst(UndefValue::get(LI.getType()),
10704                     Constant::getNullValue(Op->getType()), &LI);
10705       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10706     }
10707   } 
10708
10709   if (Constant *C = dyn_cast<Constant>(Op)) {
10710     // load null/undef -> undef
10711     // TODO: Consider a target hook for valid address spaces for this xform.
10712     if (isa<UndefValue>(C) || (C->isNullValue() && 
10713         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10714       // Insert a new store to null instruction before the load to indicate that
10715       // this code is not reachable.  We do this instead of inserting an
10716       // unreachable instruction directly because we cannot modify the CFG.
10717       new StoreInst(UndefValue::get(LI.getType()),
10718                     Constant::getNullValue(Op->getType()), &LI);
10719       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10720     }
10721
10722     // Instcombine load (constant global) into the value loaded.
10723     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10724       if (GV->isConstant() && !GV->isDeclaration())
10725         return ReplaceInstUsesWith(LI, GV->getInitializer());
10726
10727     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10728     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10729       if (CE->getOpcode() == Instruction::GetElementPtr) {
10730         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10731           if (GV->isConstant() && !GV->isDeclaration())
10732             if (Constant *V = 
10733                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10734               return ReplaceInstUsesWith(LI, V);
10735         if (CE->getOperand(0)->isNullValue()) {
10736           // Insert a new store to null instruction before the load to indicate
10737           // that this code is not reachable.  We do this instead of inserting
10738           // an unreachable instruction directly because we cannot modify the
10739           // CFG.
10740           new StoreInst(UndefValue::get(LI.getType()),
10741                         Constant::getNullValue(Op->getType()), &LI);
10742           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10743         }
10744
10745       } else if (CE->isCast()) {
10746         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10747           return Res;
10748       }
10749     }
10750   }
10751     
10752   // If this load comes from anywhere in a constant global, and if the global
10753   // is all undef or zero, we know what it loads.
10754   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10755     if (GV->isConstant() && GV->hasInitializer()) {
10756       if (GV->getInitializer()->isNullValue())
10757         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10758       else if (isa<UndefValue>(GV->getInitializer()))
10759         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10760     }
10761   }
10762
10763   if (Op->hasOneUse()) {
10764     // Change select and PHI nodes to select values instead of addresses: this
10765     // helps alias analysis out a lot, allows many others simplifications, and
10766     // exposes redundancy in the code.
10767     //
10768     // Note that we cannot do the transformation unless we know that the
10769     // introduced loads cannot trap!  Something like this is valid as long as
10770     // the condition is always false: load (select bool %C, int* null, int* %G),
10771     // but it would not be valid if we transformed it to load from null
10772     // unconditionally.
10773     //
10774     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10775       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10776       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10777           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10778         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10779                                      SI->getOperand(1)->getName()+".val"), LI);
10780         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10781                                      SI->getOperand(2)->getName()+".val"), LI);
10782         return SelectInst::Create(SI->getCondition(), V1, V2);
10783       }
10784
10785       // load (select (cond, null, P)) -> load P
10786       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10787         if (C->isNullValue()) {
10788           LI.setOperand(0, SI->getOperand(2));
10789           return &LI;
10790         }
10791
10792       // load (select (cond, P, null)) -> load P
10793       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10794         if (C->isNullValue()) {
10795           LI.setOperand(0, SI->getOperand(1));
10796           return &LI;
10797         }
10798     }
10799   }
10800   return 0;
10801 }
10802
10803 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10804 /// when possible.
10805 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10806   User *CI = cast<User>(SI.getOperand(1));
10807   Value *CastOp = CI->getOperand(0);
10808
10809   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10810   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10811     const Type *SrcPTy = SrcTy->getElementType();
10812
10813     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10814       // If the source is an array, the code below will not succeed.  Check to
10815       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10816       // constants.
10817       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10818         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10819           if (ASrcTy->getNumElements() != 0) {
10820             Value* Idxs[2];
10821             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10822             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10823             SrcTy = cast<PointerType>(CastOp->getType());
10824             SrcPTy = SrcTy->getElementType();
10825           }
10826
10827       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10828           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10829                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10830
10831         // Okay, we are casting from one integer or pointer type to another of
10832         // the same size.  Instead of casting the pointer before 
10833         // the store, cast the value to be stored.
10834         Value *NewCast;
10835         Value *SIOp0 = SI.getOperand(0);
10836         Instruction::CastOps opcode = Instruction::BitCast;
10837         const Type* CastSrcTy = SIOp0->getType();
10838         const Type* CastDstTy = SrcPTy;
10839         if (isa<PointerType>(CastDstTy)) {
10840           if (CastSrcTy->isInteger())
10841             opcode = Instruction::IntToPtr;
10842         } else if (isa<IntegerType>(CastDstTy)) {
10843           if (isa<PointerType>(SIOp0->getType()))
10844             opcode = Instruction::PtrToInt;
10845         }
10846         if (Constant *C = dyn_cast<Constant>(SIOp0))
10847           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10848         else
10849           NewCast = IC.InsertNewInstBefore(
10850             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10851             SI);
10852         return new StoreInst(NewCast, CastOp);
10853       }
10854     }
10855   }
10856   return 0;
10857 }
10858
10859 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10860   Value *Val = SI.getOperand(0);
10861   Value *Ptr = SI.getOperand(1);
10862
10863   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10864     EraseInstFromFunction(SI);
10865     ++NumCombined;
10866     return 0;
10867   }
10868   
10869   // If the RHS is an alloca with a single use, zapify the store, making the
10870   // alloca dead.
10871   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10872     if (isa<AllocaInst>(Ptr)) {
10873       EraseInstFromFunction(SI);
10874       ++NumCombined;
10875       return 0;
10876     }
10877     
10878     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10879       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10880           GEP->getOperand(0)->hasOneUse()) {
10881         EraseInstFromFunction(SI);
10882         ++NumCombined;
10883         return 0;
10884       }
10885   }
10886
10887   // Attempt to improve the alignment.
10888   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10889   if (KnownAlign >
10890       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10891                                 SI.getAlignment()))
10892     SI.setAlignment(KnownAlign);
10893
10894   // Do really simple DSE, to catch cases where there are several consequtive
10895   // stores to the same location, separated by a few arithmetic operations. This
10896   // situation often occurs with bitfield accesses.
10897   BasicBlock::iterator BBI = &SI;
10898   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10899        --ScanInsts) {
10900     --BBI;
10901     
10902     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10903       // Prev store isn't volatile, and stores to the same location?
10904       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10905         ++NumDeadStore;
10906         ++BBI;
10907         EraseInstFromFunction(*PrevSI);
10908         continue;
10909       }
10910       break;
10911     }
10912     
10913     // If this is a load, we have to stop.  However, if the loaded value is from
10914     // the pointer we're loading and is producing the pointer we're storing,
10915     // then *this* store is dead (X = load P; store X -> P).
10916     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10917       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10918         EraseInstFromFunction(SI);
10919         ++NumCombined;
10920         return 0;
10921       }
10922       // Otherwise, this is a load from some other location.  Stores before it
10923       // may not be dead.
10924       break;
10925     }
10926     
10927     // Don't skip over loads or things that can modify memory.
10928     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10929       break;
10930   }
10931   
10932   
10933   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10934
10935   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10936   if (isa<ConstantPointerNull>(Ptr)) {
10937     if (!isa<UndefValue>(Val)) {
10938       SI.setOperand(0, UndefValue::get(Val->getType()));
10939       if (Instruction *U = dyn_cast<Instruction>(Val))
10940         AddToWorkList(U);  // Dropped a use.
10941       ++NumCombined;
10942     }
10943     return 0;  // Do not modify these!
10944   }
10945
10946   // store undef, Ptr -> noop
10947   if (isa<UndefValue>(Val)) {
10948     EraseInstFromFunction(SI);
10949     ++NumCombined;
10950     return 0;
10951   }
10952
10953   // If the pointer destination is a cast, see if we can fold the cast into the
10954   // source instead.
10955   if (isa<CastInst>(Ptr))
10956     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10957       return Res;
10958   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10959     if (CE->isCast())
10960       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10961         return Res;
10962
10963   
10964   // If this store is the last instruction in the basic block, and if the block
10965   // ends with an unconditional branch, try to move it to the successor block.
10966   BBI = &SI; ++BBI;
10967   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10968     if (BI->isUnconditional())
10969       if (SimplifyStoreAtEndOfBlock(SI))
10970         return 0;  // xform done!
10971   
10972   return 0;
10973 }
10974
10975 /// SimplifyStoreAtEndOfBlock - Turn things like:
10976 ///   if () { *P = v1; } else { *P = v2 }
10977 /// into a phi node with a store in the successor.
10978 ///
10979 /// Simplify things like:
10980 ///   *P = v1; if () { *P = v2; }
10981 /// into a phi node with a store in the successor.
10982 ///
10983 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10984   BasicBlock *StoreBB = SI.getParent();
10985   
10986   // Check to see if the successor block has exactly two incoming edges.  If
10987   // so, see if the other predecessor contains a store to the same location.
10988   // if so, insert a PHI node (if needed) and move the stores down.
10989   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10990   
10991   // Determine whether Dest has exactly two predecessors and, if so, compute
10992   // the other predecessor.
10993   pred_iterator PI = pred_begin(DestBB);
10994   BasicBlock *OtherBB = 0;
10995   if (*PI != StoreBB)
10996     OtherBB = *PI;
10997   ++PI;
10998   if (PI == pred_end(DestBB))
10999     return false;
11000   
11001   if (*PI != StoreBB) {
11002     if (OtherBB)
11003       return false;
11004     OtherBB = *PI;
11005   }
11006   if (++PI != pred_end(DestBB))
11007     return false;
11008   
11009   
11010   // Verify that the other block ends in a branch and is not otherwise empty.
11011   BasicBlock::iterator BBI = OtherBB->getTerminator();
11012   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11013   if (!OtherBr || BBI == OtherBB->begin())
11014     return false;
11015   
11016   // If the other block ends in an unconditional branch, check for the 'if then
11017   // else' case.  there is an instruction before the branch.
11018   StoreInst *OtherStore = 0;
11019   if (OtherBr->isUnconditional()) {
11020     // If this isn't a store, or isn't a store to the same location, bail out.
11021     --BBI;
11022     OtherStore = dyn_cast<StoreInst>(BBI);
11023     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11024       return false;
11025   } else {
11026     // Otherwise, the other block ended with a conditional branch. If one of the
11027     // destinations is StoreBB, then we have the if/then case.
11028     if (OtherBr->getSuccessor(0) != StoreBB && 
11029         OtherBr->getSuccessor(1) != StoreBB)
11030       return false;
11031     
11032     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11033     // if/then triangle.  See if there is a store to the same ptr as SI that
11034     // lives in OtherBB.
11035     for (;; --BBI) {
11036       // Check to see if we find the matching store.
11037       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11038         if (OtherStore->getOperand(1) != SI.getOperand(1))
11039           return false;
11040         break;
11041       }
11042       // If we find something that may be using the stored value, or if we run
11043       // out of instructions, we can't do the xform.
11044       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11045           BBI == OtherBB->begin())
11046         return false;
11047     }
11048     
11049     // In order to eliminate the store in OtherBr, we have to
11050     // make sure nothing reads the stored value in StoreBB.
11051     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11052       // FIXME: This should really be AA driven.
11053       if (isa<LoadInst>(I) || I->mayWriteToMemory())
11054         return false;
11055     }
11056   }
11057   
11058   // Insert a PHI node now if we need it.
11059   Value *MergedVal = OtherStore->getOperand(0);
11060   if (MergedVal != SI.getOperand(0)) {
11061     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11062     PN->reserveOperandSpace(2);
11063     PN->addIncoming(SI.getOperand(0), SI.getParent());
11064     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11065     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11066   }
11067   
11068   // Advance to a place where it is safe to insert the new store and
11069   // insert it.
11070   BBI = DestBB->getFirstNonPHI();
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->getFirstNonPHI();
11739
11740   I->moveBefore(InsertPos);
11741   ++NumSunkInst;
11742   return true;
11743 }
11744
11745
11746 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11747 /// all reachable code to the worklist.
11748 ///
11749 /// This has a couple of tricks to make the code faster and more powerful.  In
11750 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11751 /// them to the worklist (this significantly speeds up instcombine on code where
11752 /// many instructions are dead or constant).  Additionally, if we find a branch
11753 /// whose condition is a known constant, we only visit the reachable successors.
11754 ///
11755 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11756                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11757                                        InstCombiner &IC,
11758                                        const TargetData *TD) {
11759   std::vector<BasicBlock*> Worklist;
11760   Worklist.push_back(BB);
11761
11762   while (!Worklist.empty()) {
11763     BB = Worklist.back();
11764     Worklist.pop_back();
11765     
11766     // We have now visited this block!  If we've already been here, ignore it.
11767     if (!Visited.insert(BB)) continue;
11768     
11769     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11770       Instruction *Inst = BBI++;
11771       
11772       // DCE instruction if trivially dead.
11773       if (isInstructionTriviallyDead(Inst)) {
11774         ++NumDeadInst;
11775         DOUT << "IC: DCE: " << *Inst;
11776         Inst->eraseFromParent();
11777         continue;
11778       }
11779       
11780       // ConstantProp instruction if trivially constant.
11781       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11782         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11783         Inst->replaceAllUsesWith(C);
11784         ++NumConstProp;
11785         Inst->eraseFromParent();
11786         continue;
11787       }
11788      
11789       IC.AddToWorkList(Inst);
11790     }
11791
11792     // Recursively visit successors.  If this is a branch or switch on a
11793     // constant, only visit the reachable successor.
11794     TerminatorInst *TI = BB->getTerminator();
11795     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11796       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11797         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11798         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11799         Worklist.push_back(ReachableBB);
11800         continue;
11801       }
11802     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11803       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11804         // See if this is an explicit destination.
11805         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11806           if (SI->getCaseValue(i) == Cond) {
11807             BasicBlock *ReachableBB = SI->getSuccessor(i);
11808             Worklist.push_back(ReachableBB);
11809             continue;
11810           }
11811         
11812         // Otherwise it is the default destination.
11813         Worklist.push_back(SI->getSuccessor(0));
11814         continue;
11815       }
11816     }
11817     
11818     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11819       Worklist.push_back(TI->getSuccessor(i));
11820   }
11821 }
11822
11823 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11824   bool Changed = false;
11825   TD = &getAnalysis<TargetData>();
11826   
11827   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11828              << F.getNameStr() << "\n");
11829
11830   {
11831     // Do a depth-first traversal of the function, populate the worklist with
11832     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11833     // track of which blocks we visit.
11834     SmallPtrSet<BasicBlock*, 64> Visited;
11835     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11836
11837     // Do a quick scan over the function.  If we find any blocks that are
11838     // unreachable, remove any instructions inside of them.  This prevents
11839     // the instcombine code from having to deal with some bad special cases.
11840     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11841       if (!Visited.count(BB)) {
11842         Instruction *Term = BB->getTerminator();
11843         while (Term != BB->begin()) {   // Remove instrs bottom-up
11844           BasicBlock::iterator I = Term; --I;
11845
11846           DOUT << "IC: DCE: " << *I;
11847           ++NumDeadInst;
11848
11849           if (!I->use_empty())
11850             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11851           I->eraseFromParent();
11852         }
11853       }
11854   }
11855
11856   while (!Worklist.empty()) {
11857     Instruction *I = RemoveOneFromWorkList();
11858     if (I == 0) continue;  // skip null values.
11859
11860     // Check to see if we can DCE the instruction.
11861     if (isInstructionTriviallyDead(I)) {
11862       // Add operands to the worklist.
11863       if (I->getNumOperands() < 4)
11864         AddUsesToWorkList(*I);
11865       ++NumDeadInst;
11866
11867       DOUT << "IC: DCE: " << *I;
11868
11869       I->eraseFromParent();
11870       RemoveFromWorkList(I);
11871       continue;
11872     }
11873
11874     // Instruction isn't dead, see if we can constant propagate it.
11875     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11876       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11877
11878       // Add operands to the worklist.
11879       AddUsesToWorkList(*I);
11880       ReplaceInstUsesWith(*I, C);
11881
11882       ++NumConstProp;
11883       I->eraseFromParent();
11884       RemoveFromWorkList(I);
11885       continue;
11886     }
11887
11888     // See if we can trivially sink this instruction to a successor basic block.
11889     // FIXME: Remove GetResultInst test when first class support for aggregates
11890     // is implemented.
11891     if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11892       BasicBlock *BB = I->getParent();
11893       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11894       if (UserParent != BB) {
11895         bool UserIsSuccessor = false;
11896         // See if the user is one of our successors.
11897         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11898           if (*SI == UserParent) {
11899             UserIsSuccessor = true;
11900             break;
11901           }
11902
11903         // If the user is one of our immediate successors, and if that successor
11904         // only has us as a predecessors (we'd have to split the critical edge
11905         // otherwise), we can keep going.
11906         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11907             next(pred_begin(UserParent)) == pred_end(UserParent))
11908           // Okay, the CFG is simple enough, try to sink this instruction.
11909           Changed |= TryToSinkInstruction(I, UserParent);
11910       }
11911     }
11912
11913     // Now that we have an instruction, try combining it to simplify it...
11914 #ifndef NDEBUG
11915     std::string OrigI;
11916 #endif
11917     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11918     if (Instruction *Result = visit(*I)) {
11919       ++NumCombined;
11920       // Should we replace the old instruction with a new one?
11921       if (Result != I) {
11922         DOUT << "IC: Old = " << *I
11923              << "    New = " << *Result;
11924
11925         // Everything uses the new instruction now.
11926         I->replaceAllUsesWith(Result);
11927
11928         // Push the new instruction and any users onto the worklist.
11929         AddToWorkList(Result);
11930         AddUsersToWorkList(*Result);
11931
11932         // Move the name to the new instruction first.
11933         Result->takeName(I);
11934
11935         // Insert the new instruction into the basic block...
11936         BasicBlock *InstParent = I->getParent();
11937         BasicBlock::iterator InsertPos = I;
11938
11939         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11940           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11941             ++InsertPos;
11942
11943         InstParent->getInstList().insert(InsertPos, Result);
11944
11945         // Make sure that we reprocess all operands now that we reduced their
11946         // use counts.
11947         AddUsesToWorkList(*I);
11948
11949         // Instructions can end up on the worklist more than once.  Make sure
11950         // we do not process an instruction that has been deleted.
11951         RemoveFromWorkList(I);
11952
11953         // Erase the old instruction.
11954         InstParent->getInstList().erase(I);
11955       } else {
11956 #ifndef NDEBUG
11957         DOUT << "IC: Mod = " << OrigI
11958              << "    New = " << *I;
11959 #endif
11960
11961         // If the instruction was modified, it's possible that it is now dead.
11962         // if so, remove it.
11963         if (isInstructionTriviallyDead(I)) {
11964           // Make sure we process all operands now that we are reducing their
11965           // use counts.
11966           AddUsesToWorkList(*I);
11967
11968           // Instructions may end up in the worklist more than once.  Erase all
11969           // occurrences of this instruction.
11970           RemoveFromWorkList(I);
11971           I->eraseFromParent();
11972         } else {
11973           AddToWorkList(I);
11974           AddUsersToWorkList(*I);
11975         }
11976       }
11977       Changed = true;
11978     }
11979   }
11980
11981   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11982     
11983   // Do an explicit clear, this shrinks the map if needed.
11984   WorklistMap.clear();
11985   return Changed;
11986 }
11987
11988
11989 bool InstCombiner::runOnFunction(Function &F) {
11990   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11991   
11992   bool EverMadeChange = false;
11993
11994   // Iterate while there is work to do.
11995   unsigned Iteration = 0;
11996   while (DoOneIteration(F, Iteration++))
11997     EverMadeChange = true;
11998   return EverMadeChange;
11999 }
12000
12001 FunctionPass *llvm::createInstructionCombiningPass() {
12002   return new InstCombiner();
12003 }
12004