Generalize the new code in instcombine's ComputeNumSignBits for handling
[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   return 0;
554 }
555
556 static inline Value *dyn_castNotVal(Value *V) {
557   if (BinaryOperator::isNot(V))
558     return BinaryOperator::getNotArgument(V);
559
560   // Constants can be considered to be not'ed values...
561   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
562     return ConstantInt::get(~C->getValue());
563   return 0;
564 }
565
566 // dyn_castFoldableMul - If this value is a multiply that can be folded into
567 // other computations (because it has a constant operand), return the
568 // non-constant operand of the multiply, and set CST to point to the multiplier.
569 // Otherwise, return null.
570 //
571 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
572   if (V->hasOneUse() && V->getType()->isInteger())
573     if (Instruction *I = dyn_cast<Instruction>(V)) {
574       if (I->getOpcode() == Instruction::Mul)
575         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
576           return I->getOperand(0);
577       if (I->getOpcode() == Instruction::Shl)
578         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
579           // The multiplier is really 1 << CST.
580           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
581           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
582           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
583           return I->getOperand(0);
584         }
585     }
586   return 0;
587 }
588
589 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
590 /// expression, return it.
591 static User *dyn_castGetElementPtr(Value *V) {
592   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
593   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
594     if (CE->getOpcode() == Instruction::GetElementPtr)
595       return cast<User>(V);
596   return false;
597 }
598
599 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
600 /// opcode value. Otherwise return UserOp1.
601 static unsigned getOpcode(Value *V) {
602   if (Instruction *I = dyn_cast<Instruction>(V))
603     return I->getOpcode();
604   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
605     return CE->getOpcode();
606   // Use UserOp1 to mean there's no opcode.
607   return Instruction::UserOp1;
608 }
609
610 /// AddOne - Add one to a ConstantInt
611 static ConstantInt *AddOne(ConstantInt *C) {
612   APInt Val(C->getValue());
613   return ConstantInt::get(++Val);
614 }
615 /// SubOne - Subtract one from a ConstantInt
616 static ConstantInt *SubOne(ConstantInt *C) {
617   APInt Val(C->getValue());
618   return ConstantInt::get(--Val);
619 }
620 /// Add - Add two ConstantInts together
621 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
622   return ConstantInt::get(C1->getValue() + C2->getValue());
623 }
624 /// And - Bitwise AND two ConstantInts together
625 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
626   return ConstantInt::get(C1->getValue() & C2->getValue());
627 }
628 /// Subtract - Subtract one ConstantInt from another
629 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
630   return ConstantInt::get(C1->getValue() - C2->getValue());
631 }
632 /// Multiply - Multiply two ConstantInts together
633 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
634   return ConstantInt::get(C1->getValue() * C2->getValue());
635 }
636 /// MultiplyOverflows - True if the multiply can not be expressed in an int
637 /// this size.
638 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
639   uint32_t W = C1->getBitWidth();
640   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
641   if (sign) {
642     LHSExt.sext(W * 2);
643     RHSExt.sext(W * 2);
644   } else {
645     LHSExt.zext(W * 2);
646     RHSExt.zext(W * 2);
647   }
648
649   APInt MulExt = LHSExt * RHSExt;
650
651   if (sign) {
652     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
653     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
654     return MulExt.slt(Min) || MulExt.sgt(Max);
655   } else 
656     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
657 }
658
659 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
660 /// known to be either zero or one and return them in the KnownZero/KnownOne
661 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
662 /// processing.
663 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
664 /// we cannot optimize based on the assumption that it is zero without changing
665 /// it to be an explicit zero.  If we don't change it to zero, other code could
666 /// optimized based on the contradictory assumption that it is non-zero.
667 /// Because instcombine aggressively folds operations with undef args anyway,
668 /// this won't lose us code quality.
669 void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
670                                      APInt& KnownZero, APInt& KnownOne,
671                                      unsigned Depth) const {
672   assert(V && "No Value?");
673   assert(Depth <= 6 && "Limit Search Depth");
674   uint32_t BitWidth = Mask.getBitWidth();
675   assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
676          "Not integer or pointer type!");
677   assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
678          (!isa<IntegerType>(V->getType()) ||
679           V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
680          KnownZero.getBitWidth() == BitWidth && 
681          KnownOne.getBitWidth() == BitWidth &&
682          "V, Mask, KnownOne and KnownZero should have same BitWidth");
683
684   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
685     // We know all of the bits for a constant!
686     KnownOne = CI->getValue() & Mask;
687     KnownZero = ~KnownOne & Mask;
688     return;
689   }
690   // Null is all-zeros.
691   if (isa<ConstantPointerNull>(V)) {
692     KnownOne.clear();
693     KnownZero = Mask;
694     return;
695   }
696   // The address of an aligned GlobalValue has trailing zeros.
697   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
698     unsigned Align = GV->getAlignment();
699     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
700       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
701     if (Align > 0)
702       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
703                                               CountTrailingZeros_32(Align));
704     else
705       KnownZero.clear();
706     KnownOne.clear();
707     return;
708   }
709
710   KnownZero.clear(); KnownOne.clear();   // Start out not knowing anything.
711
712   if (Depth == 6 || Mask == 0)
713     return;  // Limit search depth.
714
715   User *I = dyn_cast<User>(V);
716   if (!I) return;
717
718   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
719   switch (getOpcode(I)) {
720   default: break;
721   case Instruction::And: {
722     // If either the LHS or the RHS are Zero, the result is zero.
723     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
724     APInt Mask2(Mask & ~KnownZero);
725     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
726     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
727     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
728     
729     // Output known-1 bits are only known if set in both the LHS & RHS.
730     KnownOne &= KnownOne2;
731     // Output known-0 are known to be clear if zero in either the LHS | RHS.
732     KnownZero |= KnownZero2;
733     return;
734   }
735   case Instruction::Or: {
736     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
737     APInt Mask2(Mask & ~KnownOne);
738     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
739     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
740     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
741     
742     // Output known-0 bits are only known if clear in both the LHS & RHS.
743     KnownZero &= KnownZero2;
744     // Output known-1 are known to be set if set in either the LHS | RHS.
745     KnownOne |= KnownOne2;
746     return;
747   }
748   case Instruction::Xor: {
749     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
750     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
751     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
752     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
753     
754     // Output known-0 bits are known if clear or set in both the LHS & RHS.
755     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
756     // Output known-1 are known to be set if set in only one of the LHS, RHS.
757     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
758     KnownZero = KnownZeroOut;
759     return;
760   }
761   case Instruction::Mul: {
762     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
763     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
764     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
765     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
766     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
767     
768     // If low bits are zero in either operand, output low known-0 bits.
769     // Also compute a conserative estimate for high known-0 bits.
770     // More trickiness is possible, but this is sufficient for the
771     // interesting case of alignment computation.
772     KnownOne.clear();
773     unsigned TrailZ = KnownZero.countTrailingOnes() +
774                       KnownZero2.countTrailingOnes();
775     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
776                                KnownZero2.countLeadingOnes(),
777                                BitWidth) - BitWidth;
778
779     TrailZ = std::min(TrailZ, BitWidth);
780     LeadZ = std::min(LeadZ, BitWidth);
781     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
782                 APInt::getHighBitsSet(BitWidth, LeadZ);
783     KnownZero &= Mask;
784     return;
785   }
786   case Instruction::UDiv: {
787     // For the purposes of computing leading zeros we can conservatively
788     // treat a udiv as a logical right shift by the power of 2 known to
789     // be less than the denominator.
790     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
791     ComputeMaskedBits(I->getOperand(0),
792                       AllOnes, KnownZero2, KnownOne2, Depth+1);
793     unsigned LeadZ = KnownZero2.countLeadingOnes();
794
795     KnownOne2.clear();
796     KnownZero2.clear();
797     ComputeMaskedBits(I->getOperand(1),
798                       AllOnes, KnownZero2, KnownOne2, Depth+1);
799     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
800     if (RHSUnknownLeadingOnes != BitWidth)
801       LeadZ = std::min(BitWidth,
802                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
803
804     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
805     return;
806   }
807   case Instruction::Select:
808     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
809     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
810     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
811     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
812
813     // Only known if known in both the LHS and RHS.
814     KnownOne &= KnownOne2;
815     KnownZero &= KnownZero2;
816     return;
817   case Instruction::FPTrunc:
818   case Instruction::FPExt:
819   case Instruction::FPToUI:
820   case Instruction::FPToSI:
821   case Instruction::SIToFP:
822   case Instruction::UIToFP:
823     return; // Can't work with floating point.
824   case Instruction::PtrToInt:
825   case Instruction::IntToPtr:
826     // We can't handle these if we don't know the pointer size.
827     if (!TD) return;
828     // FALL THROUGH and handle them the same as zext/trunc.
829   case Instruction::ZExt:
830   case Instruction::Trunc: {
831     // Note that we handle pointer operands here because of inttoptr/ptrtoint
832     // which fall through here.
833     const Type *SrcTy = I->getOperand(0)->getType();
834     uint32_t SrcBitWidth = TD ?
835       TD->getTypeSizeInBits(SrcTy) :
836       SrcTy->getPrimitiveSizeInBits();
837     APInt MaskIn(Mask);
838     MaskIn.zextOrTrunc(SrcBitWidth);
839     KnownZero.zextOrTrunc(SrcBitWidth);
840     KnownOne.zextOrTrunc(SrcBitWidth);
841     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
842     KnownZero.zextOrTrunc(BitWidth);
843     KnownOne.zextOrTrunc(BitWidth);
844     // Any top bits are known to be zero.
845     if (BitWidth > SrcBitWidth)
846       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
847     return;
848   }
849   case Instruction::BitCast: {
850     const Type *SrcTy = I->getOperand(0)->getType();
851     if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
852       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
853       return;
854     }
855     break;
856   }
857   case Instruction::SExt: {
858     // Compute the bits in the result that are not present in the input.
859     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
860     uint32_t SrcBitWidth = SrcTy->getBitWidth();
861       
862     APInt MaskIn(Mask); 
863     MaskIn.trunc(SrcBitWidth);
864     KnownZero.trunc(SrcBitWidth);
865     KnownOne.trunc(SrcBitWidth);
866     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
867     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
868     KnownZero.zext(BitWidth);
869     KnownOne.zext(BitWidth);
870
871     // If the sign bit of the input is known set or clear, then we know the
872     // top bits of the result.
873     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
874       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
875     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
876       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
877     return;
878   }
879   case Instruction::Shl:
880     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
881     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
882       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
883       APInt Mask2(Mask.lshr(ShiftAmt));
884       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
885       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
886       KnownZero <<= ShiftAmt;
887       KnownOne  <<= ShiftAmt;
888       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
889       return;
890     }
891     break;
892   case Instruction::LShr:
893     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
894     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
895       // Compute the new bits that are at the top now.
896       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
897       
898       // Unsigned shift right.
899       APInt Mask2(Mask.shl(ShiftAmt));
900       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
901       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
902       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
903       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
904       // high bits known zero.
905       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
906       return;
907     }
908     break;
909   case Instruction::AShr:
910     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
911     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
912       // Compute the new bits that are at the top now.
913       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
914       
915       // Signed shift right.
916       APInt Mask2(Mask.shl(ShiftAmt));
917       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
918       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
919       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
920       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
921         
922       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
923       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
924         KnownZero |= HighBits;
925       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
926         KnownOne |= HighBits;
927       return;
928     }
929     break;
930   case Instruction::Sub: {
931     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
932       // We know that the top bits of C-X are clear if X contains less bits
933       // than C (i.e. no wrap-around can happen).  For example, 20-X is
934       // positive if we can prove that X is >= 0 and < 16.
935       if (!CLHS->getValue().isNegative()) {
936         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
937         // NLZ can't be BitWidth with no sign bit
938         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
939         ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
940                           Depth+1);
941     
942         // If all of the MaskV bits are known to be zero, then we know the
943         // output top bits are zero, because we now know that the output is
944         // from [0-C].
945         if ((KnownZero2 & MaskV) == MaskV) {
946           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
947           // Top bits known zero.
948           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
949         }
950       }        
951     }
952   }
953   // fall through
954   case Instruction::Add: {
955     // Output known-0 bits are known if clear or set in both the low clear bits
956     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
957     // low 3 bits clear.
958     APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
959     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
960     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
961     unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
962
963     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
964     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
965     KnownZeroOut = std::min(KnownZeroOut, 
966                             KnownZero2.countTrailingOnes());
967
968     KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
969     return;
970   }
971   case Instruction::SRem:
972     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
973       APInt RA = Rem->getValue();
974       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
975         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
976         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
977         ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
978
979         // The sign of a remainder is equal to the sign of the first
980         // operand (zero being positive).
981         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
982           KnownZero2 |= ~LowBits;
983         else if (KnownOne2[BitWidth-1])
984           KnownOne2 |= ~LowBits;
985
986         KnownZero |= KnownZero2 & Mask;
987         KnownOne |= KnownOne2 & Mask;
988
989         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
990       }
991     }
992     break;
993   case Instruction::URem: {
994     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
995       APInt RA = Rem->getValue();
996       if (RA.isPowerOf2()) {
997         APInt LowBits = (RA - 1);
998         APInt Mask2 = LowBits & Mask;
999         KnownZero |= ~LowBits & Mask;
1000         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1001         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1002         break;
1003       }
1004     }
1005
1006     // Since the result is less than or equal to either operand, any leading
1007     // zero bits in either operand must also exist in the result.
1008     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1009     ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1010                       Depth+1);
1011     ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1012                       Depth+1);
1013
1014     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1015                                 KnownZero2.countLeadingOnes());
1016     KnownOne.clear();
1017     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1018     break;
1019   }
1020
1021   case Instruction::Alloca:
1022   case Instruction::Malloc: {
1023     AllocationInst *AI = cast<AllocationInst>(V);
1024     unsigned Align = AI->getAlignment();
1025     if (Align == 0 && TD) {
1026       if (isa<AllocaInst>(AI))
1027         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1028       else if (isa<MallocInst>(AI)) {
1029         // Malloc returns maximally aligned memory.
1030         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1031         Align =
1032           std::max(Align,
1033                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1034         Align =
1035           std::max(Align,
1036                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1037       }
1038     }
1039     
1040     if (Align > 0)
1041       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1042                                               CountTrailingZeros_32(Align));
1043     break;
1044   }
1045   case Instruction::GetElementPtr: {
1046     // Analyze all of the subscripts of this getelementptr instruction
1047     // to determine if we can prove known low zero bits.
1048     APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1049     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1050     ComputeMaskedBits(I->getOperand(0), LocalMask,
1051                       LocalKnownZero, LocalKnownOne, Depth+1);
1052     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1053
1054     gep_type_iterator GTI = gep_type_begin(I);
1055     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1056       Value *Index = I->getOperand(i);
1057       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1058         // Handle struct member offset arithmetic.
1059         if (!TD) return;
1060         const StructLayout *SL = TD->getStructLayout(STy);
1061         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1062         uint64_t Offset = SL->getElementOffset(Idx);
1063         TrailZ = std::min(TrailZ,
1064                           CountTrailingZeros_64(Offset));
1065       } else {
1066         // Handle array index arithmetic.
1067         const Type *IndexedTy = GTI.getIndexedType();
1068         if (!IndexedTy->isSized()) return;
1069         unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1070         uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1071         LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1072         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1073         ComputeMaskedBits(Index, LocalMask,
1074                           LocalKnownZero, LocalKnownOne, Depth+1);
1075         TrailZ = std::min(TrailZ,
1076                           CountTrailingZeros_64(TypeSize) +
1077                             LocalKnownZero.countTrailingOnes());
1078       }
1079     }
1080     
1081     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1082     break;
1083   }
1084   case Instruction::PHI: {
1085     PHINode *P = cast<PHINode>(I);
1086     // Handle the case of a simple two-predecessor recurrence PHI.
1087     // There's a lot more that could theoretically be done here, but
1088     // this is sufficient to catch some interesting cases.
1089     if (P->getNumIncomingValues() == 2) {
1090       for (unsigned i = 0; i != 2; ++i) {
1091         Value *L = P->getIncomingValue(i);
1092         Value *R = P->getIncomingValue(!i);
1093         User *LU = dyn_cast<User>(L);
1094         unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1095         // Check for operations that have the property that if
1096         // both their operands have low zero bits, the result
1097         // will have low zero bits.
1098         if (Opcode == Instruction::Add ||
1099             Opcode == Instruction::Sub ||
1100             Opcode == Instruction::And ||
1101             Opcode == Instruction::Or ||
1102             Opcode == Instruction::Mul) {
1103           Value *LL = LU->getOperand(0);
1104           Value *LR = LU->getOperand(1);
1105           // Find a recurrence.
1106           if (LL == I)
1107             L = LR;
1108           else if (LR == I)
1109             L = LL;
1110           else
1111             break;
1112           // Ok, we have a PHI of the form L op= R. Check for low
1113           // zero bits.
1114           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1115           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1116           Mask2 = APInt::getLowBitsSet(BitWidth,
1117                                        KnownZero2.countTrailingOnes());
1118           KnownOne2.clear();
1119           KnownZero2.clear();
1120           ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1121           KnownZero = Mask &
1122                       APInt::getLowBitsSet(BitWidth,
1123                                            KnownZero2.countTrailingOnes());
1124           break;
1125         }
1126       }
1127     }
1128     break;
1129   }
1130   case Instruction::Call:
1131     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1132       switch (II->getIntrinsicID()) {
1133       default: break;
1134       case Intrinsic::ctpop:
1135       case Intrinsic::ctlz:
1136       case Intrinsic::cttz: {
1137         unsigned LowBits = Log2_32(BitWidth)+1;
1138         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1139         break;
1140       }
1141       }
1142     }
1143     break;
1144   }
1145 }
1146
1147 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1148 /// this predicate to simplify operations downstream.  Mask is known to be zero
1149 /// for bits that V cannot have.
1150 bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1151                                      unsigned Depth) {
1152   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1153   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1154   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1155   return (KnownZero & Mask) == Mask;
1156 }
1157
1158 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
1159 /// specified instruction is a constant integer.  If so, check to see if there
1160 /// are any bits set in the constant that are not demanded.  If so, shrink the
1161 /// constant and return true.
1162 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
1163                                    APInt Demanded) {
1164   assert(I && "No instruction?");
1165   assert(OpNo < I->getNumOperands() && "Operand index too large");
1166
1167   // If the operand is not a constant integer, nothing to do.
1168   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1169   if (!OpC) return false;
1170
1171   // If there are no bits set that aren't demanded, nothing to do.
1172   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1173   if ((~Demanded & OpC->getValue()) == 0)
1174     return false;
1175
1176   // This instruction is producing bits that are not demanded. Shrink the RHS.
1177   Demanded &= OpC->getValue();
1178   I->setOperand(OpNo, ConstantInt::get(Demanded));
1179   return true;
1180 }
1181
1182 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
1183 // set of known zero and one bits, compute the maximum and minimum values that
1184 // could have the specified known zero and known one bits, returning them in
1185 // min/max.
1186 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1187                                                    const APInt& KnownZero,
1188                                                    const APInt& KnownOne,
1189                                                    APInt& Min, APInt& Max) {
1190   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1191   assert(KnownZero.getBitWidth() == BitWidth && 
1192          KnownOne.getBitWidth() == BitWidth &&
1193          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1194          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1195   APInt UnknownBits = ~(KnownZero|KnownOne);
1196
1197   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1198   // bit if it is unknown.
1199   Min = KnownOne;
1200   Max = KnownOne|UnknownBits;
1201   
1202   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1203     Min.set(BitWidth-1);
1204     Max.clear(BitWidth-1);
1205   }
1206 }
1207
1208 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1209 // a set of known zero and one bits, compute the maximum and minimum values that
1210 // could have the specified known zero and known one bits, returning them in
1211 // min/max.
1212 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1213                                                      const APInt &KnownZero,
1214                                                      const APInt &KnownOne,
1215                                                      APInt &Min, APInt &Max) {
1216   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
1217   assert(KnownZero.getBitWidth() == BitWidth && 
1218          KnownOne.getBitWidth() == BitWidth &&
1219          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1220          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1221   APInt UnknownBits = ~(KnownZero|KnownOne);
1222   
1223   // The minimum value is when the unknown bits are all zeros.
1224   Min = KnownOne;
1225   // The maximum value is when the unknown bits are all ones.
1226   Max = KnownOne|UnknownBits;
1227 }
1228
1229 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
1230 /// value based on the demanded bits. When this function is called, it is known
1231 /// that only the bits set in DemandedMask of the result of V are ever used
1232 /// downstream. Consequently, depending on the mask and V, it may be possible
1233 /// to replace V with a constant or one of its operands. In such cases, this
1234 /// function does the replacement and returns true. In all other cases, it
1235 /// returns false after analyzing the expression and setting KnownOne and known
1236 /// to be one in the expression. KnownZero contains all the bits that are known
1237 /// to be zero in the expression. These are provided to potentially allow the
1238 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1239 /// the expression. KnownOne and KnownZero always follow the invariant that 
1240 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1241 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
1242 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1243 /// and KnownOne must all be the same.
1244 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1245                                         APInt& KnownZero, APInt& KnownOne,
1246                                         unsigned Depth) {
1247   assert(V != 0 && "Null pointer of Value???");
1248   assert(Depth <= 6 && "Limit Search Depth");
1249   uint32_t BitWidth = DemandedMask.getBitWidth();
1250   const IntegerType *VTy = cast<IntegerType>(V->getType());
1251   assert(VTy->getBitWidth() == BitWidth && 
1252          KnownZero.getBitWidth() == BitWidth && 
1253          KnownOne.getBitWidth() == BitWidth &&
1254          "Value *V, DemandedMask, KnownZero and KnownOne \
1255           must have same BitWidth");
1256   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1257     // We know all of the bits for a constant!
1258     KnownOne = CI->getValue() & DemandedMask;
1259     KnownZero = ~KnownOne & DemandedMask;
1260     return false;
1261   }
1262   
1263   KnownZero.clear(); 
1264   KnownOne.clear();
1265   if (!V->hasOneUse()) {    // Other users may use these bits.
1266     if (Depth != 0) {       // Not at the root.
1267       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1268       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1269       return false;
1270     }
1271     // If this is the root being simplified, allow it to have multiple uses,
1272     // just set the DemandedMask to all bits.
1273     DemandedMask = APInt::getAllOnesValue(BitWidth);
1274   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
1275     if (V != UndefValue::get(VTy))
1276       return UpdateValueUsesWith(V, UndefValue::get(VTy));
1277     return false;
1278   } else if (Depth == 6) {        // Limit search depth.
1279     return false;
1280   }
1281   
1282   Instruction *I = dyn_cast<Instruction>(V);
1283   if (!I) return false;        // Only analyze instructions.
1284
1285   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1286   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1287   switch (I->getOpcode()) {
1288   default:
1289     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1290     break;
1291   case Instruction::And:
1292     // If either the LHS or the RHS are Zero, the result is zero.
1293     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1294                              RHSKnownZero, RHSKnownOne, Depth+1))
1295       return true;
1296     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1297            "Bits known to be one AND zero?"); 
1298
1299     // If something is known zero on the RHS, the bits aren't demanded on the
1300     // LHS.
1301     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1302                              LHSKnownZero, LHSKnownOne, Depth+1))
1303       return true;
1304     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1305            "Bits known to be one AND zero?"); 
1306
1307     // If all of the demanded bits are known 1 on one side, return the other.
1308     // These bits cannot contribute to the result of the 'and'.
1309     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1310         (DemandedMask & ~LHSKnownZero))
1311       return UpdateValueUsesWith(I, I->getOperand(0));
1312     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1313         (DemandedMask & ~RHSKnownZero))
1314       return UpdateValueUsesWith(I, I->getOperand(1));
1315     
1316     // If all of the demanded bits in the inputs are known zeros, return zero.
1317     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1318       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1319       
1320     // If the RHS is a constant, see if we can simplify it.
1321     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1322       return UpdateValueUsesWith(I, I);
1323       
1324     // Output known-1 bits are only known if set in both the LHS & RHS.
1325     RHSKnownOne &= LHSKnownOne;
1326     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1327     RHSKnownZero |= LHSKnownZero;
1328     break;
1329   case Instruction::Or:
1330     // If either the LHS or the RHS are One, the result is One.
1331     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1332                              RHSKnownZero, RHSKnownOne, Depth+1))
1333       return true;
1334     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1335            "Bits known to be one AND zero?"); 
1336     // If something is known one on the RHS, the bits aren't demanded on the
1337     // LHS.
1338     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1339                              LHSKnownZero, LHSKnownOne, Depth+1))
1340       return true;
1341     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1342            "Bits known to be one AND zero?"); 
1343     
1344     // If all of the demanded bits are known zero on one side, return the other.
1345     // These bits cannot contribute to the result of the 'or'.
1346     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1347         (DemandedMask & ~LHSKnownOne))
1348       return UpdateValueUsesWith(I, I->getOperand(0));
1349     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1350         (DemandedMask & ~RHSKnownOne))
1351       return UpdateValueUsesWith(I, I->getOperand(1));
1352
1353     // If all of the potentially set bits on one side are known to be set on
1354     // the other side, just use the 'other' side.
1355     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1356         (DemandedMask & (~RHSKnownZero)))
1357       return UpdateValueUsesWith(I, I->getOperand(0));
1358     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1359         (DemandedMask & (~LHSKnownZero)))
1360       return UpdateValueUsesWith(I, I->getOperand(1));
1361         
1362     // If the RHS is a constant, see if we can simplify it.
1363     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1364       return UpdateValueUsesWith(I, I);
1365           
1366     // Output known-0 bits are only known if clear in both the LHS & RHS.
1367     RHSKnownZero &= LHSKnownZero;
1368     // Output known-1 are known to be set if set in either the LHS | RHS.
1369     RHSKnownOne |= LHSKnownOne;
1370     break;
1371   case Instruction::Xor: {
1372     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1373                              RHSKnownZero, RHSKnownOne, Depth+1))
1374       return true;
1375     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1376            "Bits known to be one AND zero?"); 
1377     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1378                              LHSKnownZero, LHSKnownOne, Depth+1))
1379       return true;
1380     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1381            "Bits known to be one AND zero?"); 
1382     
1383     // If all of the demanded bits are known zero on one side, return the other.
1384     // These bits cannot contribute to the result of the 'xor'.
1385     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1386       return UpdateValueUsesWith(I, I->getOperand(0));
1387     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1388       return UpdateValueUsesWith(I, I->getOperand(1));
1389     
1390     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1391     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1392                          (RHSKnownOne & LHSKnownOne);
1393     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1394     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1395                         (RHSKnownOne & LHSKnownZero);
1396     
1397     // If all of the demanded bits are known to be zero on one side or the
1398     // other, turn this into an *inclusive* or.
1399     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1400     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1401       Instruction *Or =
1402         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1403                                  I->getName());
1404       InsertNewInstBefore(Or, *I);
1405       return UpdateValueUsesWith(I, Or);
1406     }
1407     
1408     // If all of the demanded bits on one side are known, and all of the set
1409     // bits on that side are also known to be set on the other side, turn this
1410     // into an AND, as we know the bits will be cleared.
1411     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1412     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1413       // all known
1414       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1415         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1416         Instruction *And = 
1417           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1418         InsertNewInstBefore(And, *I);
1419         return UpdateValueUsesWith(I, And);
1420       }
1421     }
1422     
1423     // If the RHS is a constant, see if we can simplify it.
1424     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1425     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1426       return UpdateValueUsesWith(I, I);
1427     
1428     RHSKnownZero = KnownZeroOut;
1429     RHSKnownOne  = KnownOneOut;
1430     break;
1431   }
1432   case Instruction::Select:
1433     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1434                              RHSKnownZero, RHSKnownOne, Depth+1))
1435       return true;
1436     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1437                              LHSKnownZero, LHSKnownOne, Depth+1))
1438       return true;
1439     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1440            "Bits known to be one AND zero?"); 
1441     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1442            "Bits known to be one AND zero?"); 
1443     
1444     // If the operands are constants, see if we can simplify them.
1445     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1446       return UpdateValueUsesWith(I, I);
1447     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1448       return UpdateValueUsesWith(I, I);
1449     
1450     // Only known if known in both the LHS and RHS.
1451     RHSKnownOne &= LHSKnownOne;
1452     RHSKnownZero &= LHSKnownZero;
1453     break;
1454   case Instruction::Trunc: {
1455     uint32_t truncBf = 
1456       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1457     DemandedMask.zext(truncBf);
1458     RHSKnownZero.zext(truncBf);
1459     RHSKnownOne.zext(truncBf);
1460     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1461                              RHSKnownZero, RHSKnownOne, Depth+1))
1462       return true;
1463     DemandedMask.trunc(BitWidth);
1464     RHSKnownZero.trunc(BitWidth);
1465     RHSKnownOne.trunc(BitWidth);
1466     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1467            "Bits known to be one AND zero?"); 
1468     break;
1469   }
1470   case Instruction::BitCast:
1471     if (!I->getOperand(0)->getType()->isInteger())
1472       return false;
1473       
1474     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1475                              RHSKnownZero, RHSKnownOne, Depth+1))
1476       return true;
1477     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1478            "Bits known to be one AND zero?"); 
1479     break;
1480   case Instruction::ZExt: {
1481     // Compute the bits in the result that are not present in the input.
1482     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1483     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1484     
1485     DemandedMask.trunc(SrcBitWidth);
1486     RHSKnownZero.trunc(SrcBitWidth);
1487     RHSKnownOne.trunc(SrcBitWidth);
1488     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1489                              RHSKnownZero, RHSKnownOne, Depth+1))
1490       return true;
1491     DemandedMask.zext(BitWidth);
1492     RHSKnownZero.zext(BitWidth);
1493     RHSKnownOne.zext(BitWidth);
1494     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1495            "Bits known to be one AND zero?"); 
1496     // The top bits are known to be zero.
1497     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1498     break;
1499   }
1500   case Instruction::SExt: {
1501     // Compute the bits in the result that are not present in the input.
1502     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1503     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1504     
1505     APInt InputDemandedBits = DemandedMask & 
1506                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1507
1508     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1509     // If any of the sign extended bits are demanded, we know that the sign
1510     // bit is demanded.
1511     if ((NewBits & DemandedMask) != 0)
1512       InputDemandedBits.set(SrcBitWidth-1);
1513       
1514     InputDemandedBits.trunc(SrcBitWidth);
1515     RHSKnownZero.trunc(SrcBitWidth);
1516     RHSKnownOne.trunc(SrcBitWidth);
1517     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1518                              RHSKnownZero, RHSKnownOne, Depth+1))
1519       return true;
1520     InputDemandedBits.zext(BitWidth);
1521     RHSKnownZero.zext(BitWidth);
1522     RHSKnownOne.zext(BitWidth);
1523     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1524            "Bits known to be one AND zero?"); 
1525       
1526     // If the sign bit of the input is known set or clear, then we know the
1527     // top bits of the result.
1528
1529     // If the input sign bit is known zero, or if the NewBits are not demanded
1530     // convert this into a zero extension.
1531     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1532     {
1533       // Convert to ZExt cast
1534       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1535       return UpdateValueUsesWith(I, NewCast);
1536     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1537       RHSKnownOne |= NewBits;
1538     }
1539     break;
1540   }
1541   case Instruction::Add: {
1542     // Figure out what the input bits are.  If the top bits of the and result
1543     // are not demanded, then the add doesn't demand them from its input
1544     // either.
1545     uint32_t NLZ = DemandedMask.countLeadingZeros();
1546       
1547     // If there is a constant on the RHS, there are a variety of xformations
1548     // we can do.
1549     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1550       // If null, this should be simplified elsewhere.  Some of the xforms here
1551       // won't work if the RHS is zero.
1552       if (RHS->isZero())
1553         break;
1554       
1555       // If the top bit of the output is demanded, demand everything from the
1556       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1557       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1558
1559       // Find information about known zero/one bits in the input.
1560       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1561                                LHSKnownZero, LHSKnownOne, Depth+1))
1562         return true;
1563
1564       // If the RHS of the add has bits set that can't affect the input, reduce
1565       // the constant.
1566       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1567         return UpdateValueUsesWith(I, I);
1568       
1569       // Avoid excess work.
1570       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1571         break;
1572       
1573       // Turn it into OR if input bits are zero.
1574       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1575         Instruction *Or =
1576           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1577                                    I->getName());
1578         InsertNewInstBefore(Or, *I);
1579         return UpdateValueUsesWith(I, Or);
1580       }
1581       
1582       // We can say something about the output known-zero and known-one bits,
1583       // depending on potential carries from the input constant and the
1584       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1585       // bits set and the RHS constant is 0x01001, then we know we have a known
1586       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1587       
1588       // To compute this, we first compute the potential carry bits.  These are
1589       // the bits which may be modified.  I'm not aware of a better way to do
1590       // this scan.
1591       const APInt& RHSVal = RHS->getValue();
1592       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1593       
1594       // Now that we know which bits have carries, compute the known-1/0 sets.
1595       
1596       // Bits are known one if they are known zero in one operand and one in the
1597       // other, and there is no input carry.
1598       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1599                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1600       
1601       // Bits are known zero if they are known zero in both operands and there
1602       // is no input carry.
1603       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1604     } else {
1605       // If the high-bits of this ADD are not demanded, then it does not demand
1606       // the high bits of its LHS or RHS.
1607       if (DemandedMask[BitWidth-1] == 0) {
1608         // Right fill the mask of bits for this ADD to demand the most
1609         // significant bit and all those below it.
1610         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1611         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1612                                  LHSKnownZero, LHSKnownOne, Depth+1))
1613           return true;
1614         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1615                                  LHSKnownZero, LHSKnownOne, Depth+1))
1616           return true;
1617       }
1618     }
1619     break;
1620   }
1621   case Instruction::Sub:
1622     // If the high-bits of this SUB are not demanded, then it does not demand
1623     // the high bits of its LHS or RHS.
1624     if (DemandedMask[BitWidth-1] == 0) {
1625       // Right fill the mask of bits for this SUB to demand the most
1626       // significant bit and all those below it.
1627       uint32_t NLZ = DemandedMask.countLeadingZeros();
1628       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1629       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1630                                LHSKnownZero, LHSKnownOne, Depth+1))
1631         return true;
1632       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1633                                LHSKnownZero, LHSKnownOne, Depth+1))
1634         return true;
1635     }
1636     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1637     // the known zeros and ones.
1638     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1639     break;
1640   case Instruction::Shl:
1641     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1642       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1643       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1644       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1645                                RHSKnownZero, RHSKnownOne, Depth+1))
1646         return true;
1647       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1648              "Bits known to be one AND zero?"); 
1649       RHSKnownZero <<= ShiftAmt;
1650       RHSKnownOne  <<= ShiftAmt;
1651       // low bits known zero.
1652       if (ShiftAmt)
1653         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1654     }
1655     break;
1656   case Instruction::LShr:
1657     // For a logical shift right
1658     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1659       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1660       
1661       // Unsigned shift right.
1662       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1663       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1664                                RHSKnownZero, RHSKnownOne, Depth+1))
1665         return true;
1666       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1667              "Bits known to be one AND zero?"); 
1668       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1669       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1670       if (ShiftAmt) {
1671         // Compute the new bits that are at the top now.
1672         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1673         RHSKnownZero |= HighBits;  // high bits known zero.
1674       }
1675     }
1676     break;
1677   case Instruction::AShr:
1678     // If this is an arithmetic shift right and only the low-bit is set, we can
1679     // always convert this into a logical shr, even if the shift amount is
1680     // variable.  The low bit of the shift cannot be an input sign bit unless
1681     // the shift amount is >= the size of the datatype, which is undefined.
1682     if (DemandedMask == 1) {
1683       // Perform the logical shift right.
1684       Value *NewVal = BinaryOperator::CreateLShr(
1685                         I->getOperand(0), I->getOperand(1), I->getName());
1686       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1687       return UpdateValueUsesWith(I, NewVal);
1688     }    
1689
1690     // If the sign bit is the only bit demanded by this ashr, then there is no
1691     // need to do it, the shift doesn't change the high bit.
1692     if (DemandedMask.isSignBit())
1693       return UpdateValueUsesWith(I, I->getOperand(0));
1694     
1695     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1696       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1697       
1698       // Signed shift right.
1699       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1700       // If any of the "high bits" are demanded, we should set the sign bit as
1701       // demanded.
1702       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1703         DemandedMaskIn.set(BitWidth-1);
1704       if (SimplifyDemandedBits(I->getOperand(0),
1705                                DemandedMaskIn,
1706                                RHSKnownZero, RHSKnownOne, Depth+1))
1707         return true;
1708       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1709              "Bits known to be one AND zero?"); 
1710       // Compute the new bits that are at the top now.
1711       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1712       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1713       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1714         
1715       // Handle the sign bits.
1716       APInt SignBit(APInt::getSignBit(BitWidth));
1717       // Adjust to where it is now in the mask.
1718       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1719         
1720       // If the input sign bit is known to be zero, or if none of the top bits
1721       // are demanded, turn this into an unsigned shift right.
1722       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1723           (HighBits & ~DemandedMask) == HighBits) {
1724         // Perform the logical shift right.
1725         Value *NewVal = BinaryOperator::CreateLShr(
1726                           I->getOperand(0), SA, I->getName());
1727         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1728         return UpdateValueUsesWith(I, NewVal);
1729       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1730         RHSKnownOne |= HighBits;
1731       }
1732     }
1733     break;
1734   case Instruction::SRem:
1735     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1736       APInt RA = Rem->getValue();
1737       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1738         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1739         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1740         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1741                                  LHSKnownZero, LHSKnownOne, Depth+1))
1742           return true;
1743
1744         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1745           LHSKnownZero |= ~LowBits;
1746         else if (LHSKnownOne[BitWidth-1])
1747           LHSKnownOne |= ~LowBits;
1748
1749         KnownZero |= LHSKnownZero & DemandedMask;
1750         KnownOne |= LHSKnownOne & DemandedMask;
1751
1752         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1753       }
1754     }
1755     break;
1756   case Instruction::URem: {
1757     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1758       APInt RA = Rem->getValue();
1759       if (RA.isPowerOf2()) {
1760         APInt LowBits = (RA - 1);
1761         APInt Mask2 = LowBits & DemandedMask;
1762         KnownZero |= ~LowBits & DemandedMask;
1763         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1764                                  KnownZero, KnownOne, Depth+1))
1765           return true;
1766
1767         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1768         break;
1769       }
1770     }
1771
1772     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1773     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1774     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1775                              KnownZero2, KnownOne2, Depth+1))
1776       return true;
1777
1778     uint32_t Leaders = KnownZero2.countLeadingOnes();
1779     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1780                              KnownZero2, KnownOne2, Depth+1))
1781       return true;
1782
1783     Leaders = std::max(Leaders,
1784                        KnownZero2.countLeadingOnes());
1785     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1786     break;
1787   }
1788   }
1789   
1790   // If the client is only demanding bits that we know, return the known
1791   // constant.
1792   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1793     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1794   return false;
1795 }
1796
1797
1798 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1799 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1800 /// actually used by the caller.  This method analyzes which elements of the
1801 /// operand are undef and returns that information in UndefElts.
1802 ///
1803 /// If the information about demanded elements can be used to simplify the
1804 /// operation, the operation is simplified, then the resultant value is
1805 /// returned.  This returns null if no change was made.
1806 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1807                                                 uint64_t &UndefElts,
1808                                                 unsigned Depth) {
1809   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1810   assert(VWidth <= 64 && "Vector too wide to analyze!");
1811   uint64_t EltMask = ~0ULL >> (64-VWidth);
1812   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1813          "Invalid DemandedElts!");
1814
1815   if (isa<UndefValue>(V)) {
1816     // If the entire vector is undefined, just return this info.
1817     UndefElts = EltMask;
1818     return 0;
1819   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1820     UndefElts = EltMask;
1821     return UndefValue::get(V->getType());
1822   }
1823   
1824   UndefElts = 0;
1825   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1826     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1827     Constant *Undef = UndefValue::get(EltTy);
1828
1829     std::vector<Constant*> Elts;
1830     for (unsigned i = 0; i != VWidth; ++i)
1831       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1832         Elts.push_back(Undef);
1833         UndefElts |= (1ULL << i);
1834       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1835         Elts.push_back(Undef);
1836         UndefElts |= (1ULL << i);
1837       } else {                               // Otherwise, defined.
1838         Elts.push_back(CP->getOperand(i));
1839       }
1840         
1841     // If we changed the constant, return it.
1842     Constant *NewCP = ConstantVector::get(Elts);
1843     return NewCP != CP ? NewCP : 0;
1844   } else if (isa<ConstantAggregateZero>(V)) {
1845     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1846     // set to undef.
1847     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1848     Constant *Zero = Constant::getNullValue(EltTy);
1849     Constant *Undef = UndefValue::get(EltTy);
1850     std::vector<Constant*> Elts;
1851     for (unsigned i = 0; i != VWidth; ++i)
1852       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1853     UndefElts = DemandedElts ^ EltMask;
1854     return ConstantVector::get(Elts);
1855   }
1856   
1857   if (!V->hasOneUse()) {    // Other users may use these bits.
1858     if (Depth != 0) {       // Not at the root.
1859       // TODO: Just compute the UndefElts information recursively.
1860       return false;
1861     }
1862     return false;
1863   } else if (Depth == 10) {        // Limit search depth.
1864     return false;
1865   }
1866   
1867   Instruction *I = dyn_cast<Instruction>(V);
1868   if (!I) return false;        // Only analyze instructions.
1869   
1870   bool MadeChange = false;
1871   uint64_t UndefElts2;
1872   Value *TmpV;
1873   switch (I->getOpcode()) {
1874   default: break;
1875     
1876   case Instruction::InsertElement: {
1877     // If this is a variable index, we don't know which element it overwrites.
1878     // demand exactly the same input as we produce.
1879     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1880     if (Idx == 0) {
1881       // Note that we can't propagate undef elt info, because we don't know
1882       // which elt is getting updated.
1883       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1884                                         UndefElts2, Depth+1);
1885       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1886       break;
1887     }
1888     
1889     // If this is inserting an element that isn't demanded, remove this
1890     // insertelement.
1891     unsigned IdxNo = Idx->getZExtValue();
1892     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1893       return AddSoonDeadInstToWorklist(*I, 0);
1894     
1895     // Otherwise, the element inserted overwrites whatever was there, so the
1896     // input demanded set is simpler than the output set.
1897     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1898                                       DemandedElts & ~(1ULL << IdxNo),
1899                                       UndefElts, Depth+1);
1900     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1901
1902     // The inserted element is defined.
1903     UndefElts |= 1ULL << IdxNo;
1904     break;
1905   }
1906   case Instruction::BitCast: {
1907     // Vector->vector casts only.
1908     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1909     if (!VTy) break;
1910     unsigned InVWidth = VTy->getNumElements();
1911     uint64_t InputDemandedElts = 0;
1912     unsigned Ratio;
1913
1914     if (VWidth == InVWidth) {
1915       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1916       // elements as are demanded of us.
1917       Ratio = 1;
1918       InputDemandedElts = DemandedElts;
1919     } else if (VWidth > InVWidth) {
1920       // Untested so far.
1921       break;
1922       
1923       // If there are more elements in the result than there are in the source,
1924       // then an input element is live if any of the corresponding output
1925       // elements are live.
1926       Ratio = VWidth/InVWidth;
1927       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1928         if (DemandedElts & (1ULL << OutIdx))
1929           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1930       }
1931     } else {
1932       // Untested so far.
1933       break;
1934       
1935       // If there are more elements in the source than there are in the result,
1936       // then an input element is live if the corresponding output element is
1937       // live.
1938       Ratio = InVWidth/VWidth;
1939       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1940         if (DemandedElts & (1ULL << InIdx/Ratio))
1941           InputDemandedElts |= 1ULL << InIdx;
1942     }
1943     
1944     // div/rem demand all inputs, because they don't want divide by zero.
1945     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1946                                       UndefElts2, Depth+1);
1947     if (TmpV) {
1948       I->setOperand(0, TmpV);
1949       MadeChange = true;
1950     }
1951     
1952     UndefElts = UndefElts2;
1953     if (VWidth > InVWidth) {
1954       assert(0 && "Unimp");
1955       // If there are more elements in the result than there are in the source,
1956       // then an output element is undef if the corresponding input element is
1957       // undef.
1958       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1959         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1960           UndefElts |= 1ULL << OutIdx;
1961     } else if (VWidth < InVWidth) {
1962       assert(0 && "Unimp");
1963       // If there are more elements in the source than there are in the result,
1964       // then a result element is undef if all of the corresponding input
1965       // elements are undef.
1966       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1967       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1968         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1969           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1970     }
1971     break;
1972   }
1973   case Instruction::And:
1974   case Instruction::Or:
1975   case Instruction::Xor:
1976   case Instruction::Add:
1977   case Instruction::Sub:
1978   case Instruction::Mul:
1979     // div/rem demand all inputs, because they don't want divide by zero.
1980     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1981                                       UndefElts, Depth+1);
1982     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1983     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1984                                       UndefElts2, Depth+1);
1985     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1986       
1987     // Output elements are undefined if both are undefined.  Consider things
1988     // like undef&0.  The result is known zero, not undef.
1989     UndefElts &= UndefElts2;
1990     break;
1991     
1992   case Instruction::Call: {
1993     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1994     if (!II) break;
1995     switch (II->getIntrinsicID()) {
1996     default: break;
1997       
1998     // Binary vector operations that work column-wise.  A dest element is a
1999     // function of the corresponding input elements from the two inputs.
2000     case Intrinsic::x86_sse_sub_ss:
2001     case Intrinsic::x86_sse_mul_ss:
2002     case Intrinsic::x86_sse_min_ss:
2003     case Intrinsic::x86_sse_max_ss:
2004     case Intrinsic::x86_sse2_sub_sd:
2005     case Intrinsic::x86_sse2_mul_sd:
2006     case Intrinsic::x86_sse2_min_sd:
2007     case Intrinsic::x86_sse2_max_sd:
2008       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2009                                         UndefElts, Depth+1);
2010       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2011       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2012                                         UndefElts2, Depth+1);
2013       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2014
2015       // If only the low elt is demanded and this is a scalarizable intrinsic,
2016       // scalarize it now.
2017       if (DemandedElts == 1) {
2018         switch (II->getIntrinsicID()) {
2019         default: break;
2020         case Intrinsic::x86_sse_sub_ss:
2021         case Intrinsic::x86_sse_mul_ss:
2022         case Intrinsic::x86_sse2_sub_sd:
2023         case Intrinsic::x86_sse2_mul_sd:
2024           // TODO: Lower MIN/MAX/ABS/etc
2025           Value *LHS = II->getOperand(1);
2026           Value *RHS = II->getOperand(2);
2027           // Extract the element as scalars.
2028           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2029           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2030           
2031           switch (II->getIntrinsicID()) {
2032           default: assert(0 && "Case stmts out of sync!");
2033           case Intrinsic::x86_sse_sub_ss:
2034           case Intrinsic::x86_sse2_sub_sd:
2035             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
2036                                                         II->getName()), *II);
2037             break;
2038           case Intrinsic::x86_sse_mul_ss:
2039           case Intrinsic::x86_sse2_mul_sd:
2040             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
2041                                                          II->getName()), *II);
2042             break;
2043           }
2044           
2045           Instruction *New =
2046             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2047                                       II->getName());
2048           InsertNewInstBefore(New, *II);
2049           AddSoonDeadInstToWorklist(*II, 0);
2050           return New;
2051         }            
2052       }
2053         
2054       // Output elements are undefined if both are undefined.  Consider things
2055       // like undef&0.  The result is known zero, not undef.
2056       UndefElts &= UndefElts2;
2057       break;
2058     }
2059     break;
2060   }
2061   }
2062   return MadeChange ? I : 0;
2063 }
2064
2065 /// ComputeNumSignBits - Return the number of times the sign bit of the
2066 /// register is replicated into the other bits.  We know that at least 1 bit
2067 /// is always equal to the sign bit (itself), but other cases can give us
2068 /// information.  For example, immediately after an "ashr X, 2", we know that
2069 /// the top 3 bits are all equal to each other, so we return 3.
2070 ///
2071 unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2072   const IntegerType *Ty = cast<IntegerType>(V->getType());
2073   unsigned TyBits = Ty->getBitWidth();
2074   unsigned Tmp, Tmp2;
2075   unsigned FirstAnswer = 1;
2076
2077   if (Depth == 6)
2078     return 1;  // Limit search depth.
2079
2080   User *U = dyn_cast<User>(V);
2081   switch (getOpcode(V)) {
2082   default: break;
2083   case Instruction::SExt:
2084     Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2085     return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2086     
2087   case Instruction::AShr:
2088     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2089     // ashr X, C   -> adds C sign bits.
2090     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2091       Tmp += C->getZExtValue();
2092       if (Tmp > TyBits) Tmp = TyBits;
2093     }
2094     return Tmp;
2095   case Instruction::Shl:
2096     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2097       // shl destroys sign bits.
2098       Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2099       if (C->getZExtValue() >= TyBits ||      // Bad shift.
2100           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
2101       return Tmp - C->getZExtValue();
2102     }
2103     break;
2104   case Instruction::And:
2105   case Instruction::Or:
2106   case Instruction::Xor:    // NOT is handled here.
2107     // Logical binary ops preserve the number of sign bits at the worst.
2108     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2109     if (Tmp != 1) {
2110       Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2111       FirstAnswer = std::min(Tmp, Tmp2);
2112       // We computed what we know about the sign bits as our first
2113       // answer. Now proceed to the generic code that uses
2114       // ComputeMaskedBits, and pick whichever answer is better.
2115     }
2116     break;
2117
2118   case Instruction::Select:
2119     Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
2120     if (Tmp == 1) return 1;  // Early out.
2121     Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
2122     return std::min(Tmp, Tmp2);
2123     
2124   case Instruction::Add:
2125     // Add can have at most one carry bit.  Thus we know that the output
2126     // is, at worst, one more bit than the inputs.
2127     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2128     if (Tmp == 1) return 1;  // Early out.
2129       
2130     // Special case decrementing a value (ADD X, -1):
2131     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2132       if (CRHS->isAllOnesValue()) {
2133         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2134         APInt Mask = APInt::getAllOnesValue(TyBits);
2135         ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2136         
2137         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2138         // sign bits set.
2139         if ((KnownZero | APInt(TyBits, 1)) == Mask)
2140           return TyBits;
2141         
2142         // If we are subtracting one from a positive number, there is no carry
2143         // out of the result.
2144         if (KnownZero.isNegative())
2145           return Tmp;
2146       }
2147       
2148     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2149     if (Tmp2 == 1) return 1;
2150       return std::min(Tmp, Tmp2)-1;
2151     break;
2152     
2153   case Instruction::Sub:
2154     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2155     if (Tmp2 == 1) return 1;
2156       
2157     // Handle NEG.
2158     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2159       if (CLHS->isNullValue()) {
2160         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2161         APInt Mask = APInt::getAllOnesValue(TyBits);
2162         ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2163         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2164         // sign bits set.
2165         if ((KnownZero | APInt(TyBits, 1)) == Mask)
2166           return TyBits;
2167         
2168         // If the input is known to be positive (the sign bit is known clear),
2169         // the output of the NEG has the same number of sign bits as the input.
2170         if (KnownZero.isNegative())
2171           return Tmp2;
2172         
2173         // Otherwise, we treat this like a SUB.
2174       }
2175     
2176     // Sub can have at most one carry bit.  Thus we know that the output
2177     // is, at worst, one more bit than the inputs.
2178     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2179     if (Tmp == 1) return 1;  // Early out.
2180       return std::min(Tmp, Tmp2)-1;
2181     break;
2182   case Instruction::Trunc:
2183     // FIXME: it's tricky to do anything useful for this, but it is an important
2184     // case for targets like X86.
2185     break;
2186   }
2187   
2188   // Finally, if we can prove that the top bits of the result are 0's or 1's,
2189   // use this information.
2190   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2191   APInt Mask = APInt::getAllOnesValue(TyBits);
2192   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2193   
2194   if (KnownZero.isNegative()) {        // sign bit is 0
2195     Mask = KnownZero;
2196   } else if (KnownOne.isNegative()) {  // sign bit is 1;
2197     Mask = KnownOne;
2198   } else {
2199     // Nothing known.
2200     return FirstAnswer;
2201   }
2202   
2203   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
2204   // the number of identical bits in the top of the input value.
2205   Mask = ~Mask;
2206   Mask <<= Mask.getBitWidth()-TyBits;
2207   // Return # leading zeros.  We use 'min' here in case Val was zero before
2208   // shifting.  We don't want to return '64' as for an i32 "0".
2209   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2210 }
2211
2212
2213 /// AssociativeOpt - Perform an optimization on an associative operator.  This
2214 /// function is designed to check a chain of associative operators for a
2215 /// potential to apply a certain optimization.  Since the optimization may be
2216 /// applicable if the expression was reassociated, this checks the chain, then
2217 /// reassociates the expression as necessary to expose the optimization
2218 /// opportunity.  This makes use of a special Functor, which must define
2219 /// 'shouldApply' and 'apply' methods.
2220 ///
2221 template<typename Functor>
2222 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2223   unsigned Opcode = Root.getOpcode();
2224   Value *LHS = Root.getOperand(0);
2225
2226   // Quick check, see if the immediate LHS matches...
2227   if (F.shouldApply(LHS))
2228     return F.apply(Root);
2229
2230   // Otherwise, if the LHS is not of the same opcode as the root, return.
2231   Instruction *LHSI = dyn_cast<Instruction>(LHS);
2232   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2233     // Should we apply this transform to the RHS?
2234     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2235
2236     // If not to the RHS, check to see if we should apply to the LHS...
2237     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2238       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
2239       ShouldApply = true;
2240     }
2241
2242     // If the functor wants to apply the optimization to the RHS of LHSI,
2243     // reassociate the expression from ((? op A) op B) to (? op (A op B))
2244     if (ShouldApply) {
2245       BasicBlock *BB = Root.getParent();
2246
2247       // Now all of the instructions are in the current basic block, go ahead
2248       // and perform the reassociation.
2249       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2250
2251       // First move the selected RHS to the LHS of the root...
2252       Root.setOperand(0, LHSI->getOperand(1));
2253
2254       // Make what used to be the LHS of the root be the user of the root...
2255       Value *ExtraOperand = TmpLHSI->getOperand(1);
2256       if (&Root == TmpLHSI) {
2257         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2258         return 0;
2259       }
2260       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
2261       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
2262       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2263       BasicBlock::iterator ARI = &Root; ++ARI;
2264       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
2265       ARI = Root;
2266
2267       // Now propagate the ExtraOperand down the chain of instructions until we
2268       // get to LHSI.
2269       while (TmpLHSI != LHSI) {
2270         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2271         // Move the instruction to immediately before the chain we are
2272         // constructing to avoid breaking dominance properties.
2273         NextLHSI->getParent()->getInstList().remove(NextLHSI);
2274         BB->getInstList().insert(ARI, NextLHSI);
2275         ARI = NextLHSI;
2276
2277         Value *NextOp = NextLHSI->getOperand(1);
2278         NextLHSI->setOperand(1, ExtraOperand);
2279         TmpLHSI = NextLHSI;
2280         ExtraOperand = NextOp;
2281       }
2282
2283       // Now that the instructions are reassociated, have the functor perform
2284       // the transformation...
2285       return F.apply(Root);
2286     }
2287
2288     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2289   }
2290   return 0;
2291 }
2292
2293 namespace {
2294
2295 // AddRHS - Implements: X + X --> X << 1
2296 struct AddRHS {
2297   Value *RHS;
2298   AddRHS(Value *rhs) : RHS(rhs) {}
2299   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2300   Instruction *apply(BinaryOperator &Add) const {
2301     return BinaryOperator::CreateShl(Add.getOperand(0),
2302                                   ConstantInt::get(Add.getType(), 1));
2303   }
2304 };
2305
2306 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2307 //                 iff C1&C2 == 0
2308 struct AddMaskingAnd {
2309   Constant *C2;
2310   AddMaskingAnd(Constant *c) : C2(c) {}
2311   bool shouldApply(Value *LHS) const {
2312     ConstantInt *C1;
2313     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2314            ConstantExpr::getAnd(C1, C2)->isNullValue();
2315   }
2316   Instruction *apply(BinaryOperator &Add) const {
2317     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
2318   }
2319 };
2320
2321 }
2322
2323 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2324                                              InstCombiner *IC) {
2325   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2326     if (Constant *SOC = dyn_cast<Constant>(SO))
2327       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2328
2329     return IC->InsertNewInstBefore(CastInst::Create(
2330           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2331   }
2332
2333   // Figure out if the constant is the left or the right argument.
2334   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2335   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2336
2337   if (Constant *SOC = dyn_cast<Constant>(SO)) {
2338     if (ConstIsRHS)
2339       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2340     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2341   }
2342
2343   Value *Op0 = SO, *Op1 = ConstOperand;
2344   if (!ConstIsRHS)
2345     std::swap(Op0, Op1);
2346   Instruction *New;
2347   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2348     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
2349   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2350     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
2351                           SO->getName()+".cmp");
2352   else {
2353     assert(0 && "Unknown binary instruction type!");
2354     abort();
2355   }
2356   return IC->InsertNewInstBefore(New, I);
2357 }
2358
2359 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2360 // constant as the other operand, try to fold the binary operator into the
2361 // select arguments.  This also works for Cast instructions, which obviously do
2362 // not have a second operand.
2363 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2364                                      InstCombiner *IC) {
2365   // Don't modify shared select instructions
2366   if (!SI->hasOneUse()) return 0;
2367   Value *TV = SI->getOperand(1);
2368   Value *FV = SI->getOperand(2);
2369
2370   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2371     // Bool selects with constant operands can be folded to logical ops.
2372     if (SI->getType() == Type::Int1Ty) return 0;
2373
2374     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2375     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2376
2377     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2378                               SelectFalseVal);
2379   }
2380   return 0;
2381 }
2382
2383
2384 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2385 /// node as operand #0, see if we can fold the instruction into the PHI (which
2386 /// is only possible if all operands to the PHI are constants).
2387 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2388   PHINode *PN = cast<PHINode>(I.getOperand(0));
2389   unsigned NumPHIValues = PN->getNumIncomingValues();
2390   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2391
2392   // Check to see if all of the operands of the PHI are constants.  If there is
2393   // one non-constant value, remember the BB it is.  If there is more than one
2394   // or if *it* is a PHI, bail out.
2395   BasicBlock *NonConstBB = 0;
2396   for (unsigned i = 0; i != NumPHIValues; ++i)
2397     if (!isa<Constant>(PN->getIncomingValue(i))) {
2398       if (NonConstBB) return 0;  // More than one non-const value.
2399       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2400       NonConstBB = PN->getIncomingBlock(i);
2401       
2402       // If the incoming non-constant value is in I's block, we have an infinite
2403       // loop.
2404       if (NonConstBB == I.getParent())
2405         return 0;
2406     }
2407   
2408   // If there is exactly one non-constant value, we can insert a copy of the
2409   // operation in that block.  However, if this is a critical edge, we would be
2410   // inserting the computation one some other paths (e.g. inside a loop).  Only
2411   // do this if the pred block is unconditionally branching into the phi block.
2412   if (NonConstBB) {
2413     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2414     if (!BI || !BI->isUnconditional()) return 0;
2415   }
2416
2417   // Okay, we can do the transformation: create the new PHI node.
2418   PHINode *NewPN = PHINode::Create(I.getType(), "");
2419   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2420   InsertNewInstBefore(NewPN, *PN);
2421   NewPN->takeName(PN);
2422
2423   // Next, add all of the operands to the PHI.
2424   if (I.getNumOperands() == 2) {
2425     Constant *C = cast<Constant>(I.getOperand(1));
2426     for (unsigned i = 0; i != NumPHIValues; ++i) {
2427       Value *InV = 0;
2428       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2429         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2430           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2431         else
2432           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2433       } else {
2434         assert(PN->getIncomingBlock(i) == NonConstBB);
2435         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2436           InV = BinaryOperator::Create(BO->getOpcode(),
2437                                        PN->getIncomingValue(i), C, "phitmp",
2438                                        NonConstBB->getTerminator());
2439         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2440           InV = CmpInst::Create(CI->getOpcode(), 
2441                                 CI->getPredicate(),
2442                                 PN->getIncomingValue(i), C, "phitmp",
2443                                 NonConstBB->getTerminator());
2444         else
2445           assert(0 && "Unknown binop!");
2446         
2447         AddToWorkList(cast<Instruction>(InV));
2448       }
2449       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2450     }
2451   } else { 
2452     CastInst *CI = cast<CastInst>(&I);
2453     const Type *RetTy = CI->getType();
2454     for (unsigned i = 0; i != NumPHIValues; ++i) {
2455       Value *InV;
2456       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2457         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2458       } else {
2459         assert(PN->getIncomingBlock(i) == NonConstBB);
2460         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2461                                I.getType(), "phitmp", 
2462                                NonConstBB->getTerminator());
2463         AddToWorkList(cast<Instruction>(InV));
2464       }
2465       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2466     }
2467   }
2468   return ReplaceInstUsesWith(I, NewPN);
2469 }
2470
2471
2472 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
2473 /// value is never equal to -0.0.
2474 ///
2475 /// Note that this function will need to be revisited when we support nondefault
2476 /// rounding modes!
2477 ///
2478 static bool CannotBeNegativeZero(const Value *V) {
2479   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2480     return !CFP->getValueAPF().isNegZero();
2481
2482   if (const Instruction *I = dyn_cast<Instruction>(V)) {
2483     // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2484     if (I->getOpcode() == Instruction::Add &&
2485         isa<ConstantFP>(I->getOperand(1)) && 
2486         cast<ConstantFP>(I->getOperand(1))->isNullValue())
2487       return true;
2488     
2489     // sitofp and uitofp turn into +0.0 for zero.
2490     if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2491       return true;
2492     
2493     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2494       if (II->getIntrinsicID() == Intrinsic::sqrt)
2495         return CannotBeNegativeZero(II->getOperand(1));
2496     
2497     if (const CallInst *CI = dyn_cast<CallInst>(I))
2498       if (const Function *F = CI->getCalledFunction()) {
2499         if (F->isDeclaration()) {
2500           switch (F->getNameLen()) {
2501           case 3:  // abs(x) != -0.0
2502             if (!strcmp(F->getNameStart(), "abs")) return true;
2503             break;
2504           case 4:  // abs[lf](x) != -0.0
2505             if (!strcmp(F->getNameStart(), "absf")) return true;
2506             if (!strcmp(F->getNameStart(), "absl")) return true;
2507             break;
2508           }
2509         }
2510       }
2511   }
2512   
2513   return false;
2514 }
2515
2516 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2517 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2518 /// This basically requires proving that the add in the original type would not
2519 /// overflow to change the sign bit or have a carry out.
2520 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2521   // There are different heuristics we can use for this.  Here are some simple
2522   // ones.
2523   
2524   // Add has the property that adding any two 2's complement numbers can only 
2525   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2526   // have at least two sign bits, we know that the addition of the two values will
2527   // sign extend fine.
2528   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2529     return true;
2530   
2531   
2532   // If one of the operands only has one non-zero bit, and if the other operand
2533   // has a known-zero bit in a more significant place than it (not including the
2534   // sign bit) the ripple may go up to and fill the zero, but won't change the
2535   // sign.  For example, (X & ~4) + 1.
2536   
2537   // TODO: Implement.
2538   
2539   return false;
2540 }
2541
2542
2543 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2544   bool Changed = SimplifyCommutative(I);
2545   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2546
2547   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2548     // X + undef -> undef
2549     if (isa<UndefValue>(RHS))
2550       return ReplaceInstUsesWith(I, RHS);
2551
2552     // X + 0 --> X
2553     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2554       if (RHSC->isNullValue())
2555         return ReplaceInstUsesWith(I, LHS);
2556     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2557       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2558                               (I.getType())->getValueAPF()))
2559         return ReplaceInstUsesWith(I, LHS);
2560     }
2561
2562     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2563       // X + (signbit) --> X ^ signbit
2564       const APInt& Val = CI->getValue();
2565       uint32_t BitWidth = Val.getBitWidth();
2566       if (Val == APInt::getSignBit(BitWidth))
2567         return BinaryOperator::CreateXor(LHS, RHS);
2568       
2569       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2570       // (X & 254)+1 -> (X&254)|1
2571       if (!isa<VectorType>(I.getType())) {
2572         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2573         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2574                                  KnownZero, KnownOne))
2575           return &I;
2576       }
2577     }
2578
2579     if (isa<PHINode>(LHS))
2580       if (Instruction *NV = FoldOpIntoPhi(I))
2581         return NV;
2582     
2583     ConstantInt *XorRHS = 0;
2584     Value *XorLHS = 0;
2585     if (isa<ConstantInt>(RHSC) &&
2586         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2587       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2588       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2589       
2590       uint32_t Size = TySizeBits / 2;
2591       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2592       APInt CFF80Val(-C0080Val);
2593       do {
2594         if (TySizeBits > Size) {
2595           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2596           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2597           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2598               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2599             // This is a sign extend if the top bits are known zero.
2600             if (!MaskedValueIsZero(XorLHS, 
2601                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2602               Size = 0;  // Not a sign ext, but can't be any others either.
2603             break;
2604           }
2605         }
2606         Size >>= 1;
2607         C0080Val = APIntOps::lshr(C0080Val, Size);
2608         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2609       } while (Size >= 1);
2610       
2611       // FIXME: This shouldn't be necessary. When the backends can handle types
2612       // with funny bit widths then this switch statement should be removed. It
2613       // is just here to get the size of the "middle" type back up to something
2614       // that the back ends can handle.
2615       const Type *MiddleType = 0;
2616       switch (Size) {
2617         default: break;
2618         case 32: MiddleType = Type::Int32Ty; break;
2619         case 16: MiddleType = Type::Int16Ty; break;
2620         case  8: MiddleType = Type::Int8Ty; break;
2621       }
2622       if (MiddleType) {
2623         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2624         InsertNewInstBefore(NewTrunc, I);
2625         return new SExtInst(NewTrunc, I.getType(), I.getName());
2626       }
2627     }
2628   }
2629
2630   // X + X --> X << 1
2631   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2632     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2633
2634     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2635       if (RHSI->getOpcode() == Instruction::Sub)
2636         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2637           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2638     }
2639     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2640       if (LHSI->getOpcode() == Instruction::Sub)
2641         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2642           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2643     }
2644   }
2645
2646   // -A + B  -->  B - A
2647   // -A + -B  -->  -(A + B)
2648   if (Value *LHSV = dyn_castNegVal(LHS)) {
2649     if (LHS->getType()->isIntOrIntVector()) {
2650       if (Value *RHSV = dyn_castNegVal(RHS)) {
2651         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2652         InsertNewInstBefore(NewAdd, I);
2653         return BinaryOperator::CreateNeg(NewAdd);
2654       }
2655     }
2656     
2657     return BinaryOperator::CreateSub(RHS, LHSV);
2658   }
2659
2660   // A + -B  -->  A - B
2661   if (!isa<Constant>(RHS))
2662     if (Value *V = dyn_castNegVal(RHS))
2663       return BinaryOperator::CreateSub(LHS, V);
2664
2665
2666   ConstantInt *C2;
2667   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2668     if (X == RHS)   // X*C + X --> X * (C+1)
2669       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2670
2671     // X*C1 + X*C2 --> X * (C1+C2)
2672     ConstantInt *C1;
2673     if (X == dyn_castFoldableMul(RHS, C1))
2674       return BinaryOperator::CreateMul(X, Add(C1, C2));
2675   }
2676
2677   // X + X*C --> X * (C+1)
2678   if (dyn_castFoldableMul(RHS, C2) == LHS)
2679     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2680
2681   // X + ~X --> -1   since   ~X = -X-1
2682   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2683     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2684   
2685
2686   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2687   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2688     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2689       return R;
2690   
2691   // A+B --> A|B iff A and B have no bits set in common.
2692   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2693     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2694     APInt LHSKnownOne(IT->getBitWidth(), 0);
2695     APInt LHSKnownZero(IT->getBitWidth(), 0);
2696     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2697     if (LHSKnownZero != 0) {
2698       APInt RHSKnownOne(IT->getBitWidth(), 0);
2699       APInt RHSKnownZero(IT->getBitWidth(), 0);
2700       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2701       
2702       // No bits in common -> bitwise or.
2703       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2704         return BinaryOperator::CreateOr(LHS, RHS);
2705     }
2706   }
2707
2708   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2709   if (I.getType()->isIntOrIntVector()) {
2710     Value *W, *X, *Y, *Z;
2711     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2712         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2713       if (W != Y) {
2714         if (W == Z) {
2715           std::swap(Y, Z);
2716         } else if (Y == X) {
2717           std::swap(W, X);
2718         } else if (X == Z) {
2719           std::swap(Y, Z);
2720           std::swap(W, X);
2721         }
2722       }
2723
2724       if (W == Y) {
2725         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2726                                                             LHS->getName()), I);
2727         return BinaryOperator::CreateMul(W, NewAdd);
2728       }
2729     }
2730   }
2731
2732   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2733     Value *X = 0;
2734     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2735       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2736
2737     // (X & FF00) + xx00  -> (X+xx00) & FF00
2738     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2739       Constant *Anded = And(CRHS, C2);
2740       if (Anded == CRHS) {
2741         // See if all bits from the first bit set in the Add RHS up are included
2742         // in the mask.  First, get the rightmost bit.
2743         const APInt& AddRHSV = CRHS->getValue();
2744
2745         // Form a mask of all bits from the lowest bit added through the top.
2746         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2747
2748         // See if the and mask includes all of these bits.
2749         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2750
2751         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2752           // Okay, the xform is safe.  Insert the new add pronto.
2753           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2754                                                             LHS->getName()), I);
2755           return BinaryOperator::CreateAnd(NewAdd, C2);
2756         }
2757       }
2758     }
2759
2760     // Try to fold constant add into select arguments.
2761     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2762       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2763         return R;
2764   }
2765
2766   // add (cast *A to intptrtype) B -> 
2767   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2768   {
2769     CastInst *CI = dyn_cast<CastInst>(LHS);
2770     Value *Other = RHS;
2771     if (!CI) {
2772       CI = dyn_cast<CastInst>(RHS);
2773       Other = LHS;
2774     }
2775     if (CI && CI->getType()->isSized() && 
2776         (CI->getType()->getPrimitiveSizeInBits() == 
2777          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2778         && isa<PointerType>(CI->getOperand(0)->getType())) {
2779       unsigned AS =
2780         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2781       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2782                                       PointerType::get(Type::Int8Ty, AS), I);
2783       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2784       return new PtrToIntInst(I2, CI->getType());
2785     }
2786   }
2787   
2788   // add (select X 0 (sub n A)) A  -->  select X A n
2789   {
2790     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2791     Value *Other = RHS;
2792     if (!SI) {
2793       SI = dyn_cast<SelectInst>(RHS);
2794       Other = LHS;
2795     }
2796     if (SI && SI->hasOneUse()) {
2797       Value *TV = SI->getTrueValue();
2798       Value *FV = SI->getFalseValue();
2799       Value *A, *N;
2800
2801       // Can we fold the add into the argument of the select?
2802       // We check both true and false select arguments for a matching subtract.
2803       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2804           A == Other)  // Fold the add into the true select value.
2805         return SelectInst::Create(SI->getCondition(), N, A);
2806       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2807           A == Other)  // Fold the add into the false select value.
2808         return SelectInst::Create(SI->getCondition(), A, N);
2809     }
2810   }
2811   
2812   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2813   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2814     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2815       return ReplaceInstUsesWith(I, LHS);
2816
2817   // Check for (add (sext x), y), see if we can merge this into an
2818   // integer add followed by a sext.
2819   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2820     // (add (sext x), cst) --> (sext (add x, cst'))
2821     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2822       Constant *CI = 
2823         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2824       if (LHSConv->hasOneUse() &&
2825           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2826           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2827         // Insert the new, smaller add.
2828         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2829                                                         CI, "addconv");
2830         InsertNewInstBefore(NewAdd, I);
2831         return new SExtInst(NewAdd, I.getType());
2832       }
2833     }
2834     
2835     // (add (sext x), (sext y)) --> (sext (add int x, y))
2836     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2837       // Only do this if x/y have the same type, if at last one of them has a
2838       // single use (so we don't increase the number of sexts), and if the
2839       // integer add will not overflow.
2840       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2841           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2842           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2843                                    RHSConv->getOperand(0))) {
2844         // Insert the new integer add.
2845         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2846                                                         RHSConv->getOperand(0),
2847                                                         "addconv");
2848         InsertNewInstBefore(NewAdd, I);
2849         return new SExtInst(NewAdd, I.getType());
2850       }
2851     }
2852   }
2853   
2854   // Check for (add double (sitofp x), y), see if we can merge this into an
2855   // integer add followed by a promotion.
2856   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2857     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2858     // ... if the constant fits in the integer value.  This is useful for things
2859     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2860     // requires a constant pool load, and generally allows the add to be better
2861     // instcombined.
2862     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2863       Constant *CI = 
2864       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2865       if (LHSConv->hasOneUse() &&
2866           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2867           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2868         // Insert the new integer add.
2869         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2870                                                         CI, "addconv");
2871         InsertNewInstBefore(NewAdd, I);
2872         return new SIToFPInst(NewAdd, I.getType());
2873       }
2874     }
2875     
2876     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2877     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2878       // Only do this if x/y have the same type, if at last one of them has a
2879       // single use (so we don't increase the number of int->fp conversions),
2880       // and if the integer add will not overflow.
2881       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2882           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2883           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2884                                    RHSConv->getOperand(0))) {
2885         // Insert the new integer add.
2886         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2887                                                         RHSConv->getOperand(0),
2888                                                         "addconv");
2889         InsertNewInstBefore(NewAdd, I);
2890         return new SIToFPInst(NewAdd, I.getType());
2891       }
2892     }
2893   }
2894   
2895   return Changed ? &I : 0;
2896 }
2897
2898 // isSignBit - Return true if the value represented by the constant only has the
2899 // highest order bit set.
2900 static bool isSignBit(ConstantInt *CI) {
2901   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2902   return CI->getValue() == APInt::getSignBit(NumBits);
2903 }
2904
2905 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2906   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2907
2908   if (Op0 == Op1)         // sub X, X  -> 0
2909     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2910
2911   // If this is a 'B = x-(-A)', change to B = x+A...
2912   if (Value *V = dyn_castNegVal(Op1))
2913     return BinaryOperator::CreateAdd(Op0, V);
2914
2915   if (isa<UndefValue>(Op0))
2916     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2917   if (isa<UndefValue>(Op1))
2918     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2919
2920   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2921     // Replace (-1 - A) with (~A)...
2922     if (C->isAllOnesValue())
2923       return BinaryOperator::CreateNot(Op1);
2924
2925     // C - ~X == X + (1+C)
2926     Value *X = 0;
2927     if (match(Op1, m_Not(m_Value(X))))
2928       return BinaryOperator::CreateAdd(X, AddOne(C));
2929
2930     // -(X >>u 31) -> (X >>s 31)
2931     // -(X >>s 31) -> (X >>u 31)
2932     if (C->isZero()) {
2933       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2934         if (SI->getOpcode() == Instruction::LShr) {
2935           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2936             // Check to see if we are shifting out everything but the sign bit.
2937             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2938                 SI->getType()->getPrimitiveSizeInBits()-1) {
2939               // Ok, the transformation is safe.  Insert AShr.
2940               return BinaryOperator::Create(Instruction::AShr, 
2941                                           SI->getOperand(0), CU, SI->getName());
2942             }
2943           }
2944         }
2945         else if (SI->getOpcode() == Instruction::AShr) {
2946           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2947             // Check to see if we are shifting out everything but the sign bit.
2948             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2949                 SI->getType()->getPrimitiveSizeInBits()-1) {
2950               // Ok, the transformation is safe.  Insert LShr. 
2951               return BinaryOperator::CreateLShr(
2952                                           SI->getOperand(0), CU, SI->getName());
2953             }
2954           }
2955         }
2956       }
2957     }
2958
2959     // Try to fold constant sub into select arguments.
2960     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2961       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2962         return R;
2963
2964     if (isa<PHINode>(Op0))
2965       if (Instruction *NV = FoldOpIntoPhi(I))
2966         return NV;
2967   }
2968
2969   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2970     if (Op1I->getOpcode() == Instruction::Add &&
2971         !Op0->getType()->isFPOrFPVector()) {
2972       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2973         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2974       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2975         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2976       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2977         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2978           // C1-(X+C2) --> (C1-C2)-X
2979           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2980                                            Op1I->getOperand(0));
2981       }
2982     }
2983
2984     if (Op1I->hasOneUse()) {
2985       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2986       // is not used by anyone else...
2987       //
2988       if (Op1I->getOpcode() == Instruction::Sub &&
2989           !Op1I->getType()->isFPOrFPVector()) {
2990         // Swap the two operands of the subexpr...
2991         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2992         Op1I->setOperand(0, IIOp1);
2993         Op1I->setOperand(1, IIOp0);
2994
2995         // Create the new top level add instruction...
2996         return BinaryOperator::CreateAdd(Op0, Op1);
2997       }
2998
2999       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3000       //
3001       if (Op1I->getOpcode() == Instruction::And &&
3002           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3003         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3004
3005         Value *NewNot =
3006           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3007         return BinaryOperator::CreateAnd(Op0, NewNot);
3008       }
3009
3010       // 0 - (X sdiv C)  -> (X sdiv -C)
3011       if (Op1I->getOpcode() == Instruction::SDiv)
3012         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3013           if (CSI->isZero())
3014             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
3015               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
3016                                                ConstantExpr::getNeg(DivRHS));
3017
3018       // X - X*C --> X * (1-C)
3019       ConstantInt *C2 = 0;
3020       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
3021         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
3022         return BinaryOperator::CreateMul(Op0, CP1);
3023       }
3024
3025       // X - ((X / Y) * Y) --> X % Y
3026       if (Op1I->getOpcode() == Instruction::Mul)
3027         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3028           if (Op0 == I->getOperand(0) &&
3029               Op1I->getOperand(1) == I->getOperand(1)) {
3030             if (I->getOpcode() == Instruction::SDiv)
3031               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
3032             if (I->getOpcode() == Instruction::UDiv)
3033               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
3034           }
3035     }
3036   }
3037
3038   if (!Op0->getType()->isFPOrFPVector())
3039     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3040       if (Op0I->getOpcode() == Instruction::Add) {
3041         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
3042           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3043         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
3044           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3045       } else if (Op0I->getOpcode() == Instruction::Sub) {
3046         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
3047           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
3048       }
3049     }
3050
3051   ConstantInt *C1;
3052   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
3053     if (X == Op1)  // X*C - X --> X * (C-1)
3054       return BinaryOperator::CreateMul(Op1, SubOne(C1));
3055
3056     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
3057     if (X == dyn_castFoldableMul(Op1, C2))
3058       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
3059   }
3060   return 0;
3061 }
3062
3063 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
3064 /// comparison only checks the sign bit.  If it only checks the sign bit, set
3065 /// TrueIfSigned if the result of the comparison is true when the input value is
3066 /// signed.
3067 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3068                            bool &TrueIfSigned) {
3069   switch (pred) {
3070   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
3071     TrueIfSigned = true;
3072     return RHS->isZero();
3073   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
3074     TrueIfSigned = true;
3075     return RHS->isAllOnesValue();
3076   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
3077     TrueIfSigned = false;
3078     return RHS->isAllOnesValue();
3079   case ICmpInst::ICMP_UGT:
3080     // True if LHS u> RHS and RHS == high-bit-mask - 1
3081     TrueIfSigned = true;
3082     return RHS->getValue() ==
3083       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3084   case ICmpInst::ICMP_UGE: 
3085     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3086     TrueIfSigned = true;
3087     return RHS->getValue() == 
3088       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
3089   default:
3090     return false;
3091   }
3092 }
3093
3094 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3095   bool Changed = SimplifyCommutative(I);
3096   Value *Op0 = I.getOperand(0);
3097
3098   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
3099     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3100
3101   // Simplify mul instructions with a constant RHS...
3102   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3103     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3104
3105       // ((X << C1)*C2) == (X * (C2 << C1))
3106       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3107         if (SI->getOpcode() == Instruction::Shl)
3108           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
3109             return BinaryOperator::CreateMul(SI->getOperand(0),
3110                                              ConstantExpr::getShl(CI, ShOp));
3111
3112       if (CI->isZero())
3113         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
3114       if (CI->equalsInt(1))                  // X * 1  == X
3115         return ReplaceInstUsesWith(I, Op0);
3116       if (CI->isAllOnesValue())              // X * -1 == 0 - X
3117         return BinaryOperator::CreateNeg(Op0, I.getName());
3118
3119       const APInt& Val = cast<ConstantInt>(CI)->getValue();
3120       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
3121         return BinaryOperator::CreateShl(Op0,
3122                  ConstantInt::get(Op0->getType(), Val.logBase2()));
3123       }
3124     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
3125       if (Op1F->isNullValue())
3126         return ReplaceInstUsesWith(I, Op1);
3127
3128       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
3129       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3130       // We need a better interface for long double here.
3131       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3132         if (Op1F->isExactlyValue(1.0))
3133           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
3134     }
3135     
3136     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3137       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
3138           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
3139         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
3140         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
3141                                                      Op1, "tmp");
3142         InsertNewInstBefore(Add, I);
3143         Value *C1C2 = ConstantExpr::getMul(Op1, 
3144                                            cast<Constant>(Op0I->getOperand(1)));
3145         return BinaryOperator::CreateAdd(Add, C1C2);
3146         
3147       }
3148
3149     // Try to fold constant mul into select arguments.
3150     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3151       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3152         return R;
3153
3154     if (isa<PHINode>(Op0))
3155       if (Instruction *NV = FoldOpIntoPhi(I))
3156         return NV;
3157   }
3158
3159   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3160     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
3161       return BinaryOperator::CreateMul(Op0v, Op1v);
3162
3163   // If one of the operands of the multiply is a cast from a boolean value, then
3164   // we know the bool is either zero or one, so this is a 'masking' multiply.
3165   // See if we can simplify things based on how the boolean was originally
3166   // formed.
3167   CastInst *BoolCast = 0;
3168   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
3169     if (CI->getOperand(0)->getType() == Type::Int1Ty)
3170       BoolCast = CI;
3171   if (!BoolCast)
3172     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
3173       if (CI->getOperand(0)->getType() == Type::Int1Ty)
3174         BoolCast = CI;
3175   if (BoolCast) {
3176     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
3177       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3178       const Type *SCOpTy = SCIOp0->getType();
3179       bool TIS = false;
3180       
3181       // If the icmp is true iff the sign bit of X is set, then convert this
3182       // multiply into a shift/and combination.
3183       if (isa<ConstantInt>(SCIOp1) &&
3184           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3185           TIS) {
3186         // Shift the X value right to turn it into "all signbits".
3187         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
3188                                           SCOpTy->getPrimitiveSizeInBits()-1);
3189         Value *V =
3190           InsertNewInstBefore(
3191             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
3192                                             BoolCast->getOperand(0)->getName()+
3193                                             ".mask"), I);
3194
3195         // If the multiply type is not the same as the source type, sign extend
3196         // or truncate to the multiply type.
3197         if (I.getType() != V->getType()) {
3198           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3199           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
3200           Instruction::CastOps opcode = 
3201             (SrcBits == DstBits ? Instruction::BitCast : 
3202              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3203           V = InsertCastBefore(opcode, V, I.getType(), I);
3204         }
3205
3206         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
3207         return BinaryOperator::CreateAnd(V, OtherOp);
3208       }
3209     }
3210   }
3211
3212   return Changed ? &I : 0;
3213 }
3214
3215 /// This function implements the transforms on div instructions that work
3216 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3217 /// used by the visitors to those instructions.
3218 /// @brief Transforms common to all three div instructions
3219 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3220   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3221
3222   // undef / X -> 0        for integer.
3223   // undef / X -> undef    for FP (the undef could be a snan).
3224   if (isa<UndefValue>(Op0)) {
3225     if (Op0->getType()->isFPOrFPVector())
3226       return ReplaceInstUsesWith(I, Op0);
3227     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3228   }
3229
3230   // X / undef -> undef
3231   if (isa<UndefValue>(Op1))
3232     return ReplaceInstUsesWith(I, Op1);
3233
3234   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3235   // This does not apply for fdiv.
3236   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3237     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
3238     // the same basic block, then we replace the select with Y, and the
3239     // condition of the select with false (if the cond value is in the same BB).
3240     // If the select has uses other than the div, this allows them to be
3241     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3242     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
3243       if (ST->isNullValue()) {
3244         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3245         if (CondI && CondI->getParent() == I.getParent())
3246           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3247         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3248           I.setOperand(1, SI->getOperand(2));
3249         else
3250           UpdateValueUsesWith(SI, SI->getOperand(2));
3251         return &I;
3252       }
3253
3254     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3255     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
3256       if (ST->isNullValue()) {
3257         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3258         if (CondI && CondI->getParent() == I.getParent())
3259           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3260         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3261           I.setOperand(1, SI->getOperand(1));
3262         else
3263           UpdateValueUsesWith(SI, SI->getOperand(1));
3264         return &I;
3265       }
3266   }
3267
3268   return 0;
3269 }
3270
3271 /// This function implements the transforms common to both integer division
3272 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3273 /// division instructions.
3274 /// @brief Common integer divide transforms
3275 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3276   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3277
3278   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3279   if (Op0 == Op1)
3280     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3281   
3282   if (Instruction *Common = commonDivTransforms(I))
3283     return Common;
3284
3285   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3286     // div X, 1 == X
3287     if (RHS->equalsInt(1))
3288       return ReplaceInstUsesWith(I, Op0);
3289
3290     // (X / C1) / C2  -> X / (C1*C2)
3291     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3292       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3293         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3294           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3295             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3296           else 
3297             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3298                                           Multiply(RHS, LHSRHS));
3299         }
3300
3301     if (!RHS->isZero()) { // avoid X udiv 0
3302       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3303         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3304           return R;
3305       if (isa<PHINode>(Op0))
3306         if (Instruction *NV = FoldOpIntoPhi(I))
3307           return NV;
3308     }
3309   }
3310
3311   // 0 / X == 0, we don't need to preserve faults!
3312   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3313     if (LHS->equalsInt(0))
3314       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3315
3316   return 0;
3317 }
3318
3319 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3320   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3321
3322   // Handle the integer div common cases
3323   if (Instruction *Common = commonIDivTransforms(I))
3324     return Common;
3325
3326   // X udiv C^2 -> X >> C
3327   // Check to see if this is an unsigned division with an exact power of 2,
3328   // if so, convert to a right shift.
3329   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3330     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3331       return BinaryOperator::CreateLShr(Op0, 
3332                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3333   }
3334
3335   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3336   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3337     if (RHSI->getOpcode() == Instruction::Shl &&
3338         isa<ConstantInt>(RHSI->getOperand(0))) {
3339       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3340       if (C1.isPowerOf2()) {
3341         Value *N = RHSI->getOperand(1);
3342         const Type *NTy = N->getType();
3343         if (uint32_t C2 = C1.logBase2()) {
3344           Constant *C2V = ConstantInt::get(NTy, C2);
3345           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3346         }
3347         return BinaryOperator::CreateLShr(Op0, N);
3348       }
3349     }
3350   }
3351   
3352   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3353   // where C1&C2 are powers of two.
3354   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3355     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3356       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3357         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3358         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3359           // Compute the shift amounts
3360           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3361           // Construct the "on true" case of the select
3362           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3363           Instruction *TSI = BinaryOperator::CreateLShr(
3364                                                  Op0, TC, SI->getName()+".t");
3365           TSI = InsertNewInstBefore(TSI, I);
3366   
3367           // Construct the "on false" case of the select
3368           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3369           Instruction *FSI = BinaryOperator::CreateLShr(
3370                                                  Op0, FC, SI->getName()+".f");
3371           FSI = InsertNewInstBefore(FSI, I);
3372
3373           // construct the select instruction and return it.
3374           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3375         }
3376       }
3377   return 0;
3378 }
3379
3380 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3381   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3382
3383   // Handle the integer div common cases
3384   if (Instruction *Common = commonIDivTransforms(I))
3385     return Common;
3386
3387   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3388     // sdiv X, -1 == -X
3389     if (RHS->isAllOnesValue())
3390       return BinaryOperator::CreateNeg(Op0);
3391
3392     // -X/C -> X/-C
3393     if (Value *LHSNeg = dyn_castNegVal(Op0))
3394       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3395   }
3396
3397   // If the sign bits of both operands are zero (i.e. we can prove they are
3398   // unsigned inputs), turn this into a udiv.
3399   if (I.getType()->isInteger()) {
3400     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3401     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3402       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3403       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3404     }
3405   }      
3406   
3407   return 0;
3408 }
3409
3410 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3411   return commonDivTransforms(I);
3412 }
3413
3414 /// This function implements the transforms on rem instructions that work
3415 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3416 /// is used by the visitors to those instructions.
3417 /// @brief Transforms common to all three rem instructions
3418 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3419   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3420
3421   // 0 % X == 0 for integer, we don't need to preserve faults!
3422   if (Constant *LHS = dyn_cast<Constant>(Op0))
3423     if (LHS->isNullValue())
3424       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3425
3426   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3427     if (I.getType()->isFPOrFPVector())
3428       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3429     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3430   }
3431   if (isa<UndefValue>(Op1))
3432     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3433
3434   // Handle cases involving: rem X, (select Cond, Y, Z)
3435   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3436     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
3437     // the same basic block, then we replace the select with Y, and the
3438     // condition of the select with false (if the cond value is in the same
3439     // BB).  If the select has uses other than the div, this allows them to be
3440     // simplified also.
3441     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3442       if (ST->isNullValue()) {
3443         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3444         if (CondI && CondI->getParent() == I.getParent())
3445           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3446         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3447           I.setOperand(1, SI->getOperand(2));
3448         else
3449           UpdateValueUsesWith(SI, SI->getOperand(2));
3450         return &I;
3451       }
3452     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3453     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3454       if (ST->isNullValue()) {
3455         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3456         if (CondI && CondI->getParent() == I.getParent())
3457           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3458         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3459           I.setOperand(1, SI->getOperand(1));
3460         else
3461           UpdateValueUsesWith(SI, SI->getOperand(1));
3462         return &I;
3463       }
3464   }
3465
3466   return 0;
3467 }
3468
3469 /// This function implements the transforms common to both integer remainder
3470 /// instructions (urem and srem). It is called by the visitors to those integer
3471 /// remainder instructions.
3472 /// @brief Common integer remainder transforms
3473 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3474   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3475
3476   if (Instruction *common = commonRemTransforms(I))
3477     return common;
3478
3479   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3480     // X % 0 == undef, we don't need to preserve faults!
3481     if (RHS->equalsInt(0))
3482       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3483     
3484     if (RHS->equalsInt(1))  // X % 1 == 0
3485       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3486
3487     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3488       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3489         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3490           return R;
3491       } else if (isa<PHINode>(Op0I)) {
3492         if (Instruction *NV = FoldOpIntoPhi(I))
3493           return NV;
3494       }
3495
3496       // See if we can fold away this rem instruction.
3497       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3498       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3499       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3500                                KnownZero, KnownOne))
3501         return &I;
3502     }
3503   }
3504
3505   return 0;
3506 }
3507
3508 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3509   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3510
3511   if (Instruction *common = commonIRemTransforms(I))
3512     return common;
3513   
3514   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3515     // X urem C^2 -> X and C
3516     // Check to see if this is an unsigned remainder with an exact power of 2,
3517     // if so, convert to a bitwise and.
3518     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3519       if (C->getValue().isPowerOf2())
3520         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3521   }
3522
3523   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3524     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3525     if (RHSI->getOpcode() == Instruction::Shl &&
3526         isa<ConstantInt>(RHSI->getOperand(0))) {
3527       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3528         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3529         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3530                                                                    "tmp"), I);
3531         return BinaryOperator::CreateAnd(Op0, Add);
3532       }
3533     }
3534   }
3535
3536   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3537   // where C1&C2 are powers of two.
3538   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3539     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3540       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3541         // STO == 0 and SFO == 0 handled above.
3542         if ((STO->getValue().isPowerOf2()) && 
3543             (SFO->getValue().isPowerOf2())) {
3544           Value *TrueAnd = InsertNewInstBefore(
3545             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3546           Value *FalseAnd = InsertNewInstBefore(
3547             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3548           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3549         }
3550       }
3551   }
3552   
3553   return 0;
3554 }
3555
3556 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3557   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3558
3559   // Handle the integer rem common cases
3560   if (Instruction *common = commonIRemTransforms(I))
3561     return common;
3562   
3563   if (Value *RHSNeg = dyn_castNegVal(Op1))
3564     if (!isa<ConstantInt>(RHSNeg) || 
3565         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3566       // X % -Y -> X % Y
3567       AddUsesToWorkList(I);
3568       I.setOperand(1, RHSNeg);
3569       return &I;
3570     }
3571  
3572   // If the sign bits of both operands are zero (i.e. we can prove they are
3573   // unsigned inputs), turn this into a urem.
3574   if (I.getType()->isInteger()) {
3575     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3576     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3577       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3578       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3579     }
3580   }
3581
3582   return 0;
3583 }
3584
3585 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3586   return commonRemTransforms(I);
3587 }
3588
3589 // isMaxValueMinusOne - return true if this is Max-1
3590 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3591   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3592   if (!isSigned)
3593     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3594   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3595 }
3596
3597 // isMinValuePlusOne - return true if this is Min+1
3598 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3599   if (!isSigned)
3600     return C->getValue() == 1; // unsigned
3601     
3602   // Calculate 1111111111000000000000
3603   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3604   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3605 }
3606
3607 // isOneBitSet - Return true if there is exactly one bit set in the specified
3608 // constant.
3609 static bool isOneBitSet(const ConstantInt *CI) {
3610   return CI->getValue().isPowerOf2();
3611 }
3612
3613 // isHighOnes - Return true if the constant is of the form 1+0+.
3614 // This is the same as lowones(~X).
3615 static bool isHighOnes(const ConstantInt *CI) {
3616   return (~CI->getValue() + 1).isPowerOf2();
3617 }
3618
3619 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3620 /// are carefully arranged to allow folding of expressions such as:
3621 ///
3622 ///      (A < B) | (A > B) --> (A != B)
3623 ///
3624 /// Note that this is only valid if the first and second predicates have the
3625 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3626 ///
3627 /// Three bits are used to represent the condition, as follows:
3628 ///   0  A > B
3629 ///   1  A == B
3630 ///   2  A < B
3631 ///
3632 /// <=>  Value  Definition
3633 /// 000     0   Always false
3634 /// 001     1   A >  B
3635 /// 010     2   A == B
3636 /// 011     3   A >= B
3637 /// 100     4   A <  B
3638 /// 101     5   A != B
3639 /// 110     6   A <= B
3640 /// 111     7   Always true
3641 ///  
3642 static unsigned getICmpCode(const ICmpInst *ICI) {
3643   switch (ICI->getPredicate()) {
3644     // False -> 0
3645   case ICmpInst::ICMP_UGT: return 1;  // 001
3646   case ICmpInst::ICMP_SGT: return 1;  // 001
3647   case ICmpInst::ICMP_EQ:  return 2;  // 010
3648   case ICmpInst::ICMP_UGE: return 3;  // 011
3649   case ICmpInst::ICMP_SGE: return 3;  // 011
3650   case ICmpInst::ICMP_ULT: return 4;  // 100
3651   case ICmpInst::ICMP_SLT: return 4;  // 100
3652   case ICmpInst::ICMP_NE:  return 5;  // 101
3653   case ICmpInst::ICMP_ULE: return 6;  // 110
3654   case ICmpInst::ICMP_SLE: return 6;  // 110
3655     // True -> 7
3656   default:
3657     assert(0 && "Invalid ICmp predicate!");
3658     return 0;
3659   }
3660 }
3661
3662 /// getICmpValue - This is the complement of getICmpCode, which turns an
3663 /// opcode and two operands into either a constant true or false, or a brand 
3664 /// new ICmp instruction. The sign is passed in to determine which kind
3665 /// of predicate to use in new icmp instructions.
3666 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3667   switch (code) {
3668   default: assert(0 && "Illegal ICmp code!");
3669   case  0: return ConstantInt::getFalse();
3670   case  1: 
3671     if (sign)
3672       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3673     else
3674       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3675   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3676   case  3: 
3677     if (sign)
3678       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3679     else
3680       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3681   case  4: 
3682     if (sign)
3683       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3684     else
3685       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3686   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3687   case  6: 
3688     if (sign)
3689       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3690     else
3691       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3692   case  7: return ConstantInt::getTrue();
3693   }
3694 }
3695
3696 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3697   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3698     (ICmpInst::isSignedPredicate(p1) && 
3699      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3700     (ICmpInst::isSignedPredicate(p2) && 
3701      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3702 }
3703
3704 namespace { 
3705 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3706 struct FoldICmpLogical {
3707   InstCombiner &IC;
3708   Value *LHS, *RHS;
3709   ICmpInst::Predicate pred;
3710   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3711     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3712       pred(ICI->getPredicate()) {}
3713   bool shouldApply(Value *V) const {
3714     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3715       if (PredicatesFoldable(pred, ICI->getPredicate()))
3716         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3717                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3718     return false;
3719   }
3720   Instruction *apply(Instruction &Log) const {
3721     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3722     if (ICI->getOperand(0) != LHS) {
3723       assert(ICI->getOperand(1) == LHS);
3724       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3725     }
3726
3727     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3728     unsigned LHSCode = getICmpCode(ICI);
3729     unsigned RHSCode = getICmpCode(RHSICI);
3730     unsigned Code;
3731     switch (Log.getOpcode()) {
3732     case Instruction::And: Code = LHSCode & RHSCode; break;
3733     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3734     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3735     default: assert(0 && "Illegal logical opcode!"); return 0;
3736     }
3737
3738     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3739                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3740       
3741     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3742     if (Instruction *I = dyn_cast<Instruction>(RV))
3743       return I;
3744     // Otherwise, it's a constant boolean value...
3745     return IC.ReplaceInstUsesWith(Log, RV);
3746   }
3747 };
3748 } // end anonymous namespace
3749
3750 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3751 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3752 // guaranteed to be a binary operator.
3753 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3754                                     ConstantInt *OpRHS,
3755                                     ConstantInt *AndRHS,
3756                                     BinaryOperator &TheAnd) {
3757   Value *X = Op->getOperand(0);
3758   Constant *Together = 0;
3759   if (!Op->isShift())
3760     Together = And(AndRHS, OpRHS);
3761
3762   switch (Op->getOpcode()) {
3763   case Instruction::Xor:
3764     if (Op->hasOneUse()) {
3765       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3766       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3767       InsertNewInstBefore(And, TheAnd);
3768       And->takeName(Op);
3769       return BinaryOperator::CreateXor(And, Together);
3770     }
3771     break;
3772   case Instruction::Or:
3773     if (Together == AndRHS) // (X | C) & C --> C
3774       return ReplaceInstUsesWith(TheAnd, AndRHS);
3775
3776     if (Op->hasOneUse() && Together != OpRHS) {
3777       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3778       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3779       InsertNewInstBefore(Or, TheAnd);
3780       Or->takeName(Op);
3781       return BinaryOperator::CreateAnd(Or, AndRHS);
3782     }
3783     break;
3784   case Instruction::Add:
3785     if (Op->hasOneUse()) {
3786       // Adding a one to a single bit bit-field should be turned into an XOR
3787       // of the bit.  First thing to check is to see if this AND is with a
3788       // single bit constant.
3789       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3790
3791       // If there is only one bit set...
3792       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3793         // Ok, at this point, we know that we are masking the result of the
3794         // ADD down to exactly one bit.  If the constant we are adding has
3795         // no bits set below this bit, then we can eliminate the ADD.
3796         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3797
3798         // Check to see if any bits below the one bit set in AndRHSV are set.
3799         if ((AddRHS & (AndRHSV-1)) == 0) {
3800           // If not, the only thing that can effect the output of the AND is
3801           // the bit specified by AndRHSV.  If that bit is set, the effect of
3802           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3803           // no effect.
3804           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3805             TheAnd.setOperand(0, X);
3806             return &TheAnd;
3807           } else {
3808             // Pull the XOR out of the AND.
3809             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3810             InsertNewInstBefore(NewAnd, TheAnd);
3811             NewAnd->takeName(Op);
3812             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3813           }
3814         }
3815       }
3816     }
3817     break;
3818
3819   case Instruction::Shl: {
3820     // We know that the AND will not produce any of the bits shifted in, so if
3821     // the anded constant includes them, clear them now!
3822     //
3823     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3824     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3825     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3826     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3827
3828     if (CI->getValue() == ShlMask) { 
3829     // Masking out bits that the shift already masks
3830       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3831     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3832       TheAnd.setOperand(1, CI);
3833       return &TheAnd;
3834     }
3835     break;
3836   }
3837   case Instruction::LShr:
3838   {
3839     // We know that the AND will not produce any of the bits shifted in, so if
3840     // the anded constant includes them, clear them now!  This only applies to
3841     // unsigned shifts, because a signed shr may bring in set bits!
3842     //
3843     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3844     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3845     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3846     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3847
3848     if (CI->getValue() == ShrMask) {   
3849     // Masking out bits that the shift already masks.
3850       return ReplaceInstUsesWith(TheAnd, Op);
3851     } else if (CI != AndRHS) {
3852       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3853       return &TheAnd;
3854     }
3855     break;
3856   }
3857   case Instruction::AShr:
3858     // Signed shr.
3859     // See if this is shifting in some sign extension, then masking it out
3860     // with an and.
3861     if (Op->hasOneUse()) {
3862       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3863       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3864       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3865       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3866       if (C == AndRHS) {          // Masking out bits shifted in.
3867         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3868         // Make the argument unsigned.
3869         Value *ShVal = Op->getOperand(0);
3870         ShVal = InsertNewInstBefore(
3871             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3872                                    Op->getName()), TheAnd);
3873         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3874       }
3875     }
3876     break;
3877   }
3878   return 0;
3879 }
3880
3881
3882 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3883 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3884 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3885 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3886 /// insert new instructions.
3887 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3888                                            bool isSigned, bool Inside, 
3889                                            Instruction &IB) {
3890   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3891             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3892          "Lo is not <= Hi in range emission code!");
3893     
3894   if (Inside) {
3895     if (Lo == Hi)  // Trivially false.
3896       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3897
3898     // V >= Min && V < Hi --> V < Hi
3899     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3900       ICmpInst::Predicate pred = (isSigned ? 
3901         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3902       return new ICmpInst(pred, V, Hi);
3903     }
3904
3905     // Emit V-Lo <u Hi-Lo
3906     Constant *NegLo = ConstantExpr::getNeg(Lo);
3907     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3908     InsertNewInstBefore(Add, IB);
3909     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3910     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3911   }
3912
3913   if (Lo == Hi)  // Trivially true.
3914     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3915
3916   // V < Min || V >= Hi -> V > Hi-1
3917   Hi = SubOne(cast<ConstantInt>(Hi));
3918   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3919     ICmpInst::Predicate pred = (isSigned ? 
3920         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3921     return new ICmpInst(pred, V, Hi);
3922   }
3923
3924   // Emit V-Lo >u Hi-1-Lo
3925   // Note that Hi has already had one subtracted from it, above.
3926   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3927   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3928   InsertNewInstBefore(Add, IB);
3929   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3930   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3931 }
3932
3933 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3934 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3935 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3936 // not, since all 1s are not contiguous.
3937 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3938   const APInt& V = Val->getValue();
3939   uint32_t BitWidth = Val->getType()->getBitWidth();
3940   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3941
3942   // look for the first zero bit after the run of ones
3943   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3944   // look for the first non-zero bit
3945   ME = V.getActiveBits(); 
3946   return true;
3947 }
3948
3949 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3950 /// where isSub determines whether the operator is a sub.  If we can fold one of
3951 /// the following xforms:
3952 /// 
3953 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3954 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3955 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3956 ///
3957 /// return (A +/- B).
3958 ///
3959 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3960                                         ConstantInt *Mask, bool isSub,
3961                                         Instruction &I) {
3962   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3963   if (!LHSI || LHSI->getNumOperands() != 2 ||
3964       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3965
3966   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3967
3968   switch (LHSI->getOpcode()) {
3969   default: return 0;
3970   case Instruction::And:
3971     if (And(N, Mask) == Mask) {
3972       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3973       if ((Mask->getValue().countLeadingZeros() + 
3974            Mask->getValue().countPopulation()) == 
3975           Mask->getValue().getBitWidth())
3976         break;
3977
3978       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3979       // part, we don't need any explicit masks to take them out of A.  If that
3980       // is all N is, ignore it.
3981       uint32_t MB = 0, ME = 0;
3982       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3983         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3984         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3985         if (MaskedValueIsZero(RHS, Mask))
3986           break;
3987       }
3988     }
3989     return 0;
3990   case Instruction::Or:
3991   case Instruction::Xor:
3992     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3993     if ((Mask->getValue().countLeadingZeros() + 
3994          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3995         && And(N, Mask)->isZero())
3996       break;
3997     return 0;
3998   }
3999   
4000   Instruction *New;
4001   if (isSub)
4002     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
4003   else
4004     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
4005   return InsertNewInstBefore(New, I);
4006 }
4007
4008 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4009   bool Changed = SimplifyCommutative(I);
4010   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4011
4012   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4013     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4014
4015   // and X, X = X
4016   if (Op0 == Op1)
4017     return ReplaceInstUsesWith(I, Op1);
4018
4019   // See if we can simplify any instructions used by the instruction whose sole 
4020   // purpose is to compute bits we don't care about.
4021   if (!isa<VectorType>(I.getType())) {
4022     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4023     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4024     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4025                              KnownZero, KnownOne))
4026       return &I;
4027   } else {
4028     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4029       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4030         return ReplaceInstUsesWith(I, I.getOperand(0));
4031     } else if (isa<ConstantAggregateZero>(Op1)) {
4032       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4033     }
4034   }
4035   
4036   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4037     const APInt& AndRHSMask = AndRHS->getValue();
4038     APInt NotAndRHS(~AndRHSMask);
4039
4040     // Optimize a variety of ((val OP C1) & C2) combinations...
4041     if (isa<BinaryOperator>(Op0)) {
4042       Instruction *Op0I = cast<Instruction>(Op0);
4043       Value *Op0LHS = Op0I->getOperand(0);
4044       Value *Op0RHS = Op0I->getOperand(1);
4045       switch (Op0I->getOpcode()) {
4046       case Instruction::Xor:
4047       case Instruction::Or:
4048         // If the mask is only needed on one incoming arm, push it up.
4049         if (Op0I->hasOneUse()) {
4050           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4051             // Not masking anything out for the LHS, move to RHS.
4052             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4053                                                    Op0RHS->getName()+".masked");
4054             InsertNewInstBefore(NewRHS, I);
4055             return BinaryOperator::Create(
4056                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4057           }
4058           if (!isa<Constant>(Op0RHS) &&
4059               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4060             // Not masking anything out for the RHS, move to LHS.
4061             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4062                                                    Op0LHS->getName()+".masked");
4063             InsertNewInstBefore(NewLHS, I);
4064             return BinaryOperator::Create(
4065                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4066           }
4067         }
4068
4069         break;
4070       case Instruction::Add:
4071         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4072         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4073         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4074         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4075           return BinaryOperator::CreateAnd(V, AndRHS);
4076         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4077           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4078         break;
4079
4080       case Instruction::Sub:
4081         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4082         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4083         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4084         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4085           return BinaryOperator::CreateAnd(V, AndRHS);
4086         break;
4087       }
4088
4089       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4090         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4091           return Res;
4092     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4093       // If this is an integer truncation or change from signed-to-unsigned, and
4094       // if the source is an and/or with immediate, transform it.  This
4095       // frequently occurs for bitfield accesses.
4096       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4097         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4098             CastOp->getNumOperands() == 2)
4099           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4100             if (CastOp->getOpcode() == Instruction::And) {
4101               // Change: and (cast (and X, C1) to T), C2
4102               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4103               // This will fold the two constants together, which may allow 
4104               // other simplifications.
4105               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4106                 CastOp->getOperand(0), I.getType(), 
4107                 CastOp->getName()+".shrunk");
4108               NewCast = InsertNewInstBefore(NewCast, I);
4109               // trunc_or_bitcast(C1)&C2
4110               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4111               C3 = ConstantExpr::getAnd(C3, AndRHS);
4112               return BinaryOperator::CreateAnd(NewCast, C3);
4113             } else if (CastOp->getOpcode() == Instruction::Or) {
4114               // Change: and (cast (or X, C1) to T), C2
4115               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4116               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4117               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
4118                 return ReplaceInstUsesWith(I, AndRHS);
4119             }
4120           }
4121       }
4122     }
4123
4124     // Try to fold constant and into select arguments.
4125     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4126       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4127         return R;
4128     if (isa<PHINode>(Op0))
4129       if (Instruction *NV = FoldOpIntoPhi(I))
4130         return NV;
4131   }
4132
4133   Value *Op0NotVal = dyn_castNotVal(Op0);
4134   Value *Op1NotVal = dyn_castNotVal(Op1);
4135
4136   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4137     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4138
4139   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4140   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4141     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4142                                                I.getName()+".demorgan");
4143     InsertNewInstBefore(Or, I);
4144     return BinaryOperator::CreateNot(Or);
4145   }
4146   
4147   {
4148     Value *A = 0, *B = 0, *C = 0, *D = 0;
4149     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4150       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4151         return ReplaceInstUsesWith(I, Op1);
4152     
4153       // (A|B) & ~(A&B) -> A^B
4154       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4155         if ((A == C && B == D) || (A == D && B == C))
4156           return BinaryOperator::CreateXor(A, B);
4157       }
4158     }
4159     
4160     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4161       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4162         return ReplaceInstUsesWith(I, Op0);
4163
4164       // ~(A&B) & (A|B) -> A^B
4165       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4166         if ((A == C && B == D) || (A == D && B == C))
4167           return BinaryOperator::CreateXor(A, B);
4168       }
4169     }
4170     
4171     if (Op0->hasOneUse() &&
4172         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4173       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4174         I.swapOperands();     // Simplify below
4175         std::swap(Op0, Op1);
4176       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4177         cast<BinaryOperator>(Op0)->swapOperands();
4178         I.swapOperands();     // Simplify below
4179         std::swap(Op0, Op1);
4180       }
4181     }
4182     if (Op1->hasOneUse() &&
4183         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4184       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4185         cast<BinaryOperator>(Op1)->swapOperands();
4186         std::swap(A, B);
4187       }
4188       if (A == Op0) {                                // A&(A^B) -> A & ~B
4189         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4190         InsertNewInstBefore(NotB, I);
4191         return BinaryOperator::CreateAnd(A, NotB);
4192       }
4193     }
4194   }
4195   
4196   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4197     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4198     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4199       return R;
4200
4201     Value *LHSVal, *RHSVal;
4202     ConstantInt *LHSCst, *RHSCst;
4203     ICmpInst::Predicate LHSCC, RHSCC;
4204     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4205       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4206         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
4207             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4208             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4209             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4210             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4211             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4212             
4213             // Don't try to fold ICMP_SLT + ICMP_ULT.
4214             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4215              ICmpInst::isSignedPredicate(LHSCC) == 
4216                  ICmpInst::isSignedPredicate(RHSCC))) {
4217           // Ensure that the larger constant is on the RHS.
4218           ICmpInst::Predicate GT;
4219           if (ICmpInst::isSignedPredicate(LHSCC) ||
4220               (ICmpInst::isEquality(LHSCC) && 
4221                ICmpInst::isSignedPredicate(RHSCC)))
4222             GT = ICmpInst::ICMP_SGT;
4223           else
4224             GT = ICmpInst::ICMP_UGT;
4225           
4226           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4227           ICmpInst *LHS = cast<ICmpInst>(Op0);
4228           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4229             std::swap(LHS, RHS);
4230             std::swap(LHSCst, RHSCst);
4231             std::swap(LHSCC, RHSCC);
4232           }
4233
4234           // At this point, we know we have have two icmp instructions
4235           // comparing a value against two constants and and'ing the result
4236           // together.  Because of the above check, we know that we only have
4237           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4238           // (from the FoldICmpLogical check above), that the two constants 
4239           // are not equal and that the larger constant is on the RHS
4240           assert(LHSCst != RHSCst && "Compares not folded above?");
4241
4242           switch (LHSCC) {
4243           default: assert(0 && "Unknown integer condition code!");
4244           case ICmpInst::ICMP_EQ:
4245             switch (RHSCC) {
4246             default: assert(0 && "Unknown integer condition code!");
4247             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4248             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4249             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4250               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4251             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4252             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4253             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4254               return ReplaceInstUsesWith(I, LHS);
4255             }
4256           case ICmpInst::ICMP_NE:
4257             switch (RHSCC) {
4258             default: assert(0 && "Unknown integer condition code!");
4259             case ICmpInst::ICMP_ULT:
4260               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4261                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4262               break;                        // (X != 13 & X u< 15) -> no change
4263             case ICmpInst::ICMP_SLT:
4264               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4265                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4266               break;                        // (X != 13 & X s< 15) -> no change
4267             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4268             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4269             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4270               return ReplaceInstUsesWith(I, RHS);
4271             case ICmpInst::ICMP_NE:
4272               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4273                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4274                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4275                                                       LHSVal->getName()+".off");
4276                 InsertNewInstBefore(Add, I);
4277                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4278                                     ConstantInt::get(Add->getType(), 1));
4279               }
4280               break;                        // (X != 13 & X != 15) -> no change
4281             }
4282             break;
4283           case ICmpInst::ICMP_ULT:
4284             switch (RHSCC) {
4285             default: assert(0 && "Unknown integer condition code!");
4286             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4287             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4288               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4289             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4290               break;
4291             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4292             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4293               return ReplaceInstUsesWith(I, LHS);
4294             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4295               break;
4296             }
4297             break;
4298           case ICmpInst::ICMP_SLT:
4299             switch (RHSCC) {
4300             default: assert(0 && "Unknown integer condition code!");
4301             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4302             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4303               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4304             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4305               break;
4306             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4307             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4308               return ReplaceInstUsesWith(I, LHS);
4309             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4310               break;
4311             }
4312             break;
4313           case ICmpInst::ICMP_UGT:
4314             switch (RHSCC) {
4315             default: assert(0 && "Unknown integer condition code!");
4316             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
4317               return ReplaceInstUsesWith(I, LHS);
4318             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4319               return ReplaceInstUsesWith(I, RHS);
4320             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4321               break;
4322             case ICmpInst::ICMP_NE:
4323               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4324                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4325               break;                        // (X u> 13 & X != 15) -> no change
4326             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
4327               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
4328                                      true, I);
4329             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4330               break;
4331             }
4332             break;
4333           case ICmpInst::ICMP_SGT:
4334             switch (RHSCC) {
4335             default: assert(0 && "Unknown integer condition code!");
4336             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4337             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4338               return ReplaceInstUsesWith(I, RHS);
4339             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4340               break;
4341             case ICmpInst::ICMP_NE:
4342               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4343                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4344               break;                        // (X s> 13 & X != 15) -> no change
4345             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
4346               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
4347                                      true, I);
4348             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4349               break;
4350             }
4351             break;
4352           }
4353         }
4354   }
4355
4356   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4357   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4358     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4359       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4360         const Type *SrcTy = Op0C->getOperand(0)->getType();
4361         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4362             // Only do this if the casts both really cause code to be generated.
4363             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4364                               I.getType(), TD) &&
4365             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4366                               I.getType(), TD)) {
4367           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4368                                                          Op1C->getOperand(0),
4369                                                          I.getName());
4370           InsertNewInstBefore(NewOp, I);
4371           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4372         }
4373       }
4374     
4375   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4376   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4377     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4378       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4379           SI0->getOperand(1) == SI1->getOperand(1) &&
4380           (SI0->hasOneUse() || SI1->hasOneUse())) {
4381         Instruction *NewOp =
4382           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4383                                                         SI1->getOperand(0),
4384                                                         SI0->getName()), I);
4385         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4386                                       SI1->getOperand(1));
4387       }
4388   }
4389
4390   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4391   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4392     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4393       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4394           RHS->getPredicate() == FCmpInst::FCMP_ORD)
4395         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4396           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4397             // If either of the constants are nans, then the whole thing returns
4398             // false.
4399             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4400               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4401             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4402                                 RHS->getOperand(0));
4403           }
4404     }
4405   }
4406       
4407   return Changed ? &I : 0;
4408 }
4409
4410 /// CollectBSwapParts - Look to see if the specified value defines a single byte
4411 /// in the result.  If it does, and if the specified byte hasn't been filled in
4412 /// yet, fill it in and return false.
4413 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4414   Instruction *I = dyn_cast<Instruction>(V);
4415   if (I == 0) return true;
4416
4417   // If this is an or instruction, it is an inner node of the bswap.
4418   if (I->getOpcode() == Instruction::Or)
4419     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4420            CollectBSwapParts(I->getOperand(1), ByteValues);
4421   
4422   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4423   // If this is a shift by a constant int, and it is "24", then its operand
4424   // defines a byte.  We only handle unsigned types here.
4425   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4426     // Not shifting the entire input by N-1 bytes?
4427     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4428         8*(ByteValues.size()-1))
4429       return true;
4430     
4431     unsigned DestNo;
4432     if (I->getOpcode() == Instruction::Shl) {
4433       // X << 24 defines the top byte with the lowest of the input bytes.
4434       DestNo = ByteValues.size()-1;
4435     } else {
4436       // X >>u 24 defines the low byte with the highest of the input bytes.
4437       DestNo = 0;
4438     }
4439     
4440     // If the destination byte value is already defined, the values are or'd
4441     // together, which isn't a bswap (unless it's an or of the same bits).
4442     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4443       return true;
4444     ByteValues[DestNo] = I->getOperand(0);
4445     return false;
4446   }
4447   
4448   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
4449   // don't have this.
4450   Value *Shift = 0, *ShiftLHS = 0;
4451   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4452   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4453       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4454     return true;
4455   Instruction *SI = cast<Instruction>(Shift);
4456
4457   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4458   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4459       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4460     return true;
4461   
4462   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4463   unsigned DestByte;
4464   if (AndAmt->getValue().getActiveBits() > 64)
4465     return true;
4466   uint64_t AndAmtVal = AndAmt->getZExtValue();
4467   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4468     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4469       break;
4470   // Unknown mask for bswap.
4471   if (DestByte == ByteValues.size()) return true;
4472   
4473   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4474   unsigned SrcByte;
4475   if (SI->getOpcode() == Instruction::Shl)
4476     SrcByte = DestByte - ShiftBytes;
4477   else
4478     SrcByte = DestByte + ShiftBytes;
4479   
4480   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4481   if (SrcByte != ByteValues.size()-DestByte-1)
4482     return true;
4483   
4484   // If the destination byte value is already defined, the values are or'd
4485   // together, which isn't a bswap (unless it's an or of the same bits).
4486   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4487     return true;
4488   ByteValues[DestByte] = SI->getOperand(0);
4489   return false;
4490 }
4491
4492 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4493 /// If so, insert the new bswap intrinsic and return it.
4494 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4495   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4496   if (!ITy || ITy->getBitWidth() % 16) 
4497     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4498   
4499   /// ByteValues - For each byte of the result, we keep track of which value
4500   /// defines each byte.
4501   SmallVector<Value*, 8> ByteValues;
4502   ByteValues.resize(ITy->getBitWidth()/8);
4503     
4504   // Try to find all the pieces corresponding to the bswap.
4505   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4506       CollectBSwapParts(I.getOperand(1), ByteValues))
4507     return 0;
4508   
4509   // Check to see if all of the bytes come from the same value.
4510   Value *V = ByteValues[0];
4511   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4512   
4513   // Check to make sure that all of the bytes come from the same value.
4514   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4515     if (ByteValues[i] != V)
4516       return 0;
4517   const Type *Tys[] = { ITy };
4518   Module *M = I.getParent()->getParent()->getParent();
4519   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4520   return CallInst::Create(F, V);
4521 }
4522
4523
4524 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4525   bool Changed = SimplifyCommutative(I);
4526   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4527
4528   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4529     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4530
4531   // or X, X = X
4532   if (Op0 == Op1)
4533     return ReplaceInstUsesWith(I, Op0);
4534
4535   // See if we can simplify any instructions used by the instruction whose sole 
4536   // purpose is to compute bits we don't care about.
4537   if (!isa<VectorType>(I.getType())) {
4538     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4539     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4540     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4541                              KnownZero, KnownOne))
4542       return &I;
4543   } else if (isa<ConstantAggregateZero>(Op1)) {
4544     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4545   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4546     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4547       return ReplaceInstUsesWith(I, I.getOperand(1));
4548   }
4549     
4550
4551   
4552   // or X, -1 == -1
4553   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4554     ConstantInt *C1 = 0; Value *X = 0;
4555     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4556     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4557       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4558       InsertNewInstBefore(Or, I);
4559       Or->takeName(Op0);
4560       return BinaryOperator::CreateAnd(Or, 
4561                ConstantInt::get(RHS->getValue() | C1->getValue()));
4562     }
4563
4564     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4565     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4566       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4567       InsertNewInstBefore(Or, I);
4568       Or->takeName(Op0);
4569       return BinaryOperator::CreateXor(Or,
4570                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4571     }
4572
4573     // Try to fold constant and into select arguments.
4574     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4575       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4576         return R;
4577     if (isa<PHINode>(Op0))
4578       if (Instruction *NV = FoldOpIntoPhi(I))
4579         return NV;
4580   }
4581
4582   Value *A = 0, *B = 0;
4583   ConstantInt *C1 = 0, *C2 = 0;
4584
4585   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4586     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4587       return ReplaceInstUsesWith(I, Op1);
4588   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4589     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4590       return ReplaceInstUsesWith(I, Op0);
4591
4592   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4593   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4594   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4595       match(Op1, m_Or(m_Value(), m_Value())) ||
4596       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4597        match(Op1, m_Shift(m_Value(), m_Value())))) {
4598     if (Instruction *BSwap = MatchBSwap(I))
4599       return BSwap;
4600   }
4601   
4602   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4603   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4604       MaskedValueIsZero(Op1, C1->getValue())) {
4605     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4606     InsertNewInstBefore(NOr, I);
4607     NOr->takeName(Op0);
4608     return BinaryOperator::CreateXor(NOr, C1);
4609   }
4610
4611   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4612   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4613       MaskedValueIsZero(Op0, C1->getValue())) {
4614     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4615     InsertNewInstBefore(NOr, I);
4616     NOr->takeName(Op0);
4617     return BinaryOperator::CreateXor(NOr, C1);
4618   }
4619
4620   // (A & C)|(B & D)
4621   Value *C = 0, *D = 0;
4622   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4623       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4624     Value *V1 = 0, *V2 = 0, *V3 = 0;
4625     C1 = dyn_cast<ConstantInt>(C);
4626     C2 = dyn_cast<ConstantInt>(D);
4627     if (C1 && C2) {  // (A & C1)|(B & C2)
4628       // If we have: ((V + N) & C1) | (V & C2)
4629       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4630       // replace with V+N.
4631       if (C1->getValue() == ~C2->getValue()) {
4632         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4633             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4634           // Add commutes, try both ways.
4635           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4636             return ReplaceInstUsesWith(I, A);
4637           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4638             return ReplaceInstUsesWith(I, A);
4639         }
4640         // Or commutes, try both ways.
4641         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4642             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4643           // Add commutes, try both ways.
4644           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4645             return ReplaceInstUsesWith(I, B);
4646           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4647             return ReplaceInstUsesWith(I, B);
4648         }
4649       }
4650       V1 = 0; V2 = 0; V3 = 0;
4651     }
4652     
4653     // Check to see if we have any common things being and'ed.  If so, find the
4654     // terms for V1 & (V2|V3).
4655     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4656       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4657         V1 = A, V2 = C, V3 = D;
4658       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4659         V1 = A, V2 = B, V3 = C;
4660       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4661         V1 = C, V2 = A, V3 = D;
4662       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4663         V1 = C, V2 = A, V3 = B;
4664       
4665       if (V1) {
4666         Value *Or =
4667           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4668         return BinaryOperator::CreateAnd(V1, Or);
4669       }
4670     }
4671   }
4672   
4673   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4674   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4675     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4676       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4677           SI0->getOperand(1) == SI1->getOperand(1) &&
4678           (SI0->hasOneUse() || SI1->hasOneUse())) {
4679         Instruction *NewOp =
4680         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4681                                                      SI1->getOperand(0),
4682                                                      SI0->getName()), I);
4683         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4684                                       SI1->getOperand(1));
4685       }
4686   }
4687
4688   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4689     if (A == Op1)   // ~A | A == -1
4690       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4691   } else {
4692     A = 0;
4693   }
4694   // Note, A is still live here!
4695   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4696     if (Op0 == B)
4697       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4698
4699     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4700     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4701       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4702                                               I.getName()+".demorgan"), I);
4703       return BinaryOperator::CreateNot(And);
4704     }
4705   }
4706
4707   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4708   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4709     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4710       return R;
4711
4712     Value *LHSVal, *RHSVal;
4713     ConstantInt *LHSCst, *RHSCst;
4714     ICmpInst::Predicate LHSCC, RHSCC;
4715     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4716       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4717         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4718             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4719             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4720             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4721             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4722             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4723             // We can't fold (ugt x, C) | (sgt x, C2).
4724             PredicatesFoldable(LHSCC, RHSCC)) {
4725           // Ensure that the larger constant is on the RHS.
4726           ICmpInst *LHS = cast<ICmpInst>(Op0);
4727           bool NeedsSwap;
4728           if (ICmpInst::isSignedPredicate(LHSCC))
4729             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4730           else
4731             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4732             
4733           if (NeedsSwap) {
4734             std::swap(LHS, RHS);
4735             std::swap(LHSCst, RHSCst);
4736             std::swap(LHSCC, RHSCC);
4737           }
4738
4739           // At this point, we know we have have two icmp instructions
4740           // comparing a value against two constants and or'ing the result
4741           // together.  Because of the above check, we know that we only have
4742           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4743           // FoldICmpLogical check above), that the two constants are not
4744           // equal.
4745           assert(LHSCst != RHSCst && "Compares not folded above?");
4746
4747           switch (LHSCC) {
4748           default: assert(0 && "Unknown integer condition code!");
4749           case ICmpInst::ICMP_EQ:
4750             switch (RHSCC) {
4751             default: assert(0 && "Unknown integer condition code!");
4752             case ICmpInst::ICMP_EQ:
4753               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4754                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4755                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4756                                                       LHSVal->getName()+".off");
4757                 InsertNewInstBefore(Add, I);
4758                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4759                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4760               }
4761               break;                         // (X == 13 | X == 15) -> no change
4762             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4763             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4764               break;
4765             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4766             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4767             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4768               return ReplaceInstUsesWith(I, RHS);
4769             }
4770             break;
4771           case ICmpInst::ICMP_NE:
4772             switch (RHSCC) {
4773             default: assert(0 && "Unknown integer condition code!");
4774             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4775             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4776             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4777               return ReplaceInstUsesWith(I, LHS);
4778             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4779             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4780             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4781               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4782             }
4783             break;
4784           case ICmpInst::ICMP_ULT:
4785             switch (RHSCC) {
4786             default: assert(0 && "Unknown integer condition code!");
4787             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4788               break;
4789             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4790               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4791               // this can cause overflow.
4792               if (RHSCst->isMaxValue(false))
4793                 return ReplaceInstUsesWith(I, LHS);
4794               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4795                                      false, I);
4796             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4797               break;
4798             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4799             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4800               return ReplaceInstUsesWith(I, RHS);
4801             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4802               break;
4803             }
4804             break;
4805           case ICmpInst::ICMP_SLT:
4806             switch (RHSCC) {
4807             default: assert(0 && "Unknown integer condition code!");
4808             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4809               break;
4810             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4811               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4812               // this can cause overflow.
4813               if (RHSCst->isMaxValue(true))
4814                 return ReplaceInstUsesWith(I, LHS);
4815               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4816                                      false, I);
4817             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4818               break;
4819             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4820             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4821               return ReplaceInstUsesWith(I, RHS);
4822             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4823               break;
4824             }
4825             break;
4826           case ICmpInst::ICMP_UGT:
4827             switch (RHSCC) {
4828             default: assert(0 && "Unknown integer condition code!");
4829             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4830             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4831               return ReplaceInstUsesWith(I, LHS);
4832             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4833               break;
4834             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4835             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4836               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4837             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4838               break;
4839             }
4840             break;
4841           case ICmpInst::ICMP_SGT:
4842             switch (RHSCC) {
4843             default: assert(0 && "Unknown integer condition code!");
4844             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4845             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4846               return ReplaceInstUsesWith(I, LHS);
4847             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4848               break;
4849             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4850             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4851               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4852             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4853               break;
4854             }
4855             break;
4856           }
4857         }
4858   }
4859     
4860   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4861   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4862     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4863       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4864         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4865             !isa<ICmpInst>(Op1C->getOperand(0))) {
4866           const Type *SrcTy = Op0C->getOperand(0)->getType();
4867           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4868               // Only do this if the casts both really cause code to be
4869               // generated.
4870               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4871                                 I.getType(), TD) &&
4872               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4873                                 I.getType(), TD)) {
4874             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4875                                                           Op1C->getOperand(0),
4876                                                           I.getName());
4877             InsertNewInstBefore(NewOp, I);
4878             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4879           }
4880         }
4881       }
4882   }
4883   
4884     
4885   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4886   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4887     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4888       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4889           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4890           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4891         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4892           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4893             // If either of the constants are nans, then the whole thing returns
4894             // true.
4895             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4896               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4897             
4898             // Otherwise, no need to compare the two constants, compare the
4899             // rest.
4900             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4901                                 RHS->getOperand(0));
4902           }
4903     }
4904   }
4905
4906   return Changed ? &I : 0;
4907 }
4908
4909 namespace {
4910
4911 // XorSelf - Implements: X ^ X --> 0
4912 struct XorSelf {
4913   Value *RHS;
4914   XorSelf(Value *rhs) : RHS(rhs) {}
4915   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4916   Instruction *apply(BinaryOperator &Xor) const {
4917     return &Xor;
4918   }
4919 };
4920
4921 }
4922
4923 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4924   bool Changed = SimplifyCommutative(I);
4925   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4926
4927   if (isa<UndefValue>(Op1)) {
4928     if (isa<UndefValue>(Op0))
4929       // Handle undef ^ undef -> 0 special case. This is a common
4930       // idiom (misuse).
4931       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4932     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4933   }
4934
4935   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4936   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4937     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4938     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4939   }
4940   
4941   // See if we can simplify any instructions used by the instruction whose sole 
4942   // purpose is to compute bits we don't care about.
4943   if (!isa<VectorType>(I.getType())) {
4944     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4945     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4946     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4947                              KnownZero, KnownOne))
4948       return &I;
4949   } else if (isa<ConstantAggregateZero>(Op1)) {
4950     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4951   }
4952
4953   // Is this a ~ operation?
4954   if (Value *NotOp = dyn_castNotVal(&I)) {
4955     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4956     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4957     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4958       if (Op0I->getOpcode() == Instruction::And || 
4959           Op0I->getOpcode() == Instruction::Or) {
4960         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4961         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4962           Instruction *NotY =
4963             BinaryOperator::CreateNot(Op0I->getOperand(1),
4964                                       Op0I->getOperand(1)->getName()+".not");
4965           InsertNewInstBefore(NotY, I);
4966           if (Op0I->getOpcode() == Instruction::And)
4967             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4968           else
4969             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4970         }
4971       }
4972     }
4973   }
4974   
4975   
4976   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4977     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4978     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4979       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4980         return new ICmpInst(ICI->getInversePredicate(),
4981                             ICI->getOperand(0), ICI->getOperand(1));
4982
4983       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4984         return new FCmpInst(FCI->getInversePredicate(),
4985                             FCI->getOperand(0), FCI->getOperand(1));
4986     }
4987
4988     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4989       // ~(c-X) == X-c-1 == X+(-c-1)
4990       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4991         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4992           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4993           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4994                                               ConstantInt::get(I.getType(), 1));
4995           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4996         }
4997           
4998       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4999         if (Op0I->getOpcode() == Instruction::Add) {
5000           // ~(X-c) --> (-c-1)-X
5001           if (RHS->isAllOnesValue()) {
5002             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5003             return BinaryOperator::CreateSub(
5004                            ConstantExpr::getSub(NegOp0CI,
5005                                              ConstantInt::get(I.getType(), 1)),
5006                                           Op0I->getOperand(0));
5007           } else if (RHS->getValue().isSignBit()) {
5008             // (X + C) ^ signbit -> (X + C + signbit)
5009             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
5010             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5011
5012           }
5013         } else if (Op0I->getOpcode() == Instruction::Or) {
5014           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5015           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5016             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5017             // Anything in both C1 and C2 is known to be zero, remove it from
5018             // NewRHS.
5019             Constant *CommonBits = And(Op0CI, RHS);
5020             NewRHS = ConstantExpr::getAnd(NewRHS, 
5021                                           ConstantExpr::getNot(CommonBits));
5022             AddToWorkList(Op0I);
5023             I.setOperand(0, Op0I->getOperand(0));
5024             I.setOperand(1, NewRHS);
5025             return &I;
5026           }
5027         }
5028       }
5029     }
5030
5031     // Try to fold constant and into select arguments.
5032     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5033       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5034         return R;
5035     if (isa<PHINode>(Op0))
5036       if (Instruction *NV = FoldOpIntoPhi(I))
5037         return NV;
5038   }
5039
5040   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5041     if (X == Op1)
5042       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5043
5044   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5045     if (X == Op0)
5046       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5047
5048   
5049   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5050   if (Op1I) {
5051     Value *A, *B;
5052     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5053       if (A == Op0) {              // B^(B|A) == (A|B)^B
5054         Op1I->swapOperands();
5055         I.swapOperands();
5056         std::swap(Op0, Op1);
5057       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5058         I.swapOperands();     // Simplified below.
5059         std::swap(Op0, Op1);
5060       }
5061     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5062       if (Op0 == A)                                          // A^(A^B) == B
5063         return ReplaceInstUsesWith(I, B);
5064       else if (Op0 == B)                                     // A^(B^A) == B
5065         return ReplaceInstUsesWith(I, A);
5066     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5067       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5068         Op1I->swapOperands();
5069         std::swap(A, B);
5070       }
5071       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5072         I.swapOperands();     // Simplified below.
5073         std::swap(Op0, Op1);
5074       }
5075     }
5076   }
5077   
5078   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5079   if (Op0I) {
5080     Value *A, *B;
5081     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5082       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5083         std::swap(A, B);
5084       if (B == Op1) {                                // (A|B)^B == A & ~B
5085         Instruction *NotB =
5086           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5087         return BinaryOperator::CreateAnd(A, NotB);
5088       }
5089     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5090       if (Op1 == A)                                          // (A^B)^A == B
5091         return ReplaceInstUsesWith(I, B);
5092       else if (Op1 == B)                                     // (B^A)^A == B
5093         return ReplaceInstUsesWith(I, A);
5094     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5095       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5096         std::swap(A, B);
5097       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5098           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5099         Instruction *N =
5100           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5101         return BinaryOperator::CreateAnd(N, Op1);
5102       }
5103     }
5104   }
5105   
5106   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5107   if (Op0I && Op1I && Op0I->isShift() && 
5108       Op0I->getOpcode() == Op1I->getOpcode() && 
5109       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5110       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5111     Instruction *NewOp =
5112       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5113                                                     Op1I->getOperand(0),
5114                                                     Op0I->getName()), I);
5115     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5116                                   Op1I->getOperand(1));
5117   }
5118     
5119   if (Op0I && Op1I) {
5120     Value *A, *B, *C, *D;
5121     // (A & B)^(A | B) -> A ^ B
5122     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5123         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5124       if ((A == C && B == D) || (A == D && B == C)) 
5125         return BinaryOperator::CreateXor(A, B);
5126     }
5127     // (A | B)^(A & B) -> A ^ B
5128     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5129         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5130       if ((A == C && B == D) || (A == D && B == C)) 
5131         return BinaryOperator::CreateXor(A, B);
5132     }
5133     
5134     // (A & B)^(C & D)
5135     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5136         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5137         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5138       // (X & Y)^(X & Y) -> (Y^Z) & X
5139       Value *X = 0, *Y = 0, *Z = 0;
5140       if (A == C)
5141         X = A, Y = B, Z = D;
5142       else if (A == D)
5143         X = A, Y = B, Z = C;
5144       else if (B == C)
5145         X = B, Y = A, Z = D;
5146       else if (B == D)
5147         X = B, Y = A, Z = C;
5148       
5149       if (X) {
5150         Instruction *NewOp =
5151         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5152         return BinaryOperator::CreateAnd(NewOp, X);
5153       }
5154     }
5155   }
5156     
5157   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5158   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5159     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5160       return R;
5161
5162   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5163   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5164     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5165       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5166         const Type *SrcTy = Op0C->getOperand(0)->getType();
5167         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5168             // Only do this if the casts both really cause code to be generated.
5169             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5170                               I.getType(), TD) &&
5171             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5172                               I.getType(), TD)) {
5173           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5174                                                          Op1C->getOperand(0),
5175                                                          I.getName());
5176           InsertNewInstBefore(NewOp, I);
5177           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5178         }
5179       }
5180   }
5181   return Changed ? &I : 0;
5182 }
5183
5184 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5185 /// overflowed for this type.
5186 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5187                             ConstantInt *In2, bool IsSigned = false) {
5188   Result = cast<ConstantInt>(Add(In1, In2));
5189
5190   if (IsSigned)
5191     if (In2->getValue().isNegative())
5192       return Result->getValue().sgt(In1->getValue());
5193     else
5194       return Result->getValue().slt(In1->getValue());
5195   else
5196     return Result->getValue().ult(In1->getValue());
5197 }
5198
5199 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5200 /// code necessary to compute the offset from the base pointer (without adding
5201 /// in the base pointer).  Return the result as a signed integer of intptr size.
5202 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5203   TargetData &TD = IC.getTargetData();
5204   gep_type_iterator GTI = gep_type_begin(GEP);
5205   const Type *IntPtrTy = TD.getIntPtrType();
5206   Value *Result = Constant::getNullValue(IntPtrTy);
5207
5208   // Build a mask for high order bits.
5209   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5210   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5211
5212   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5213     Value *Op = GEP->getOperand(i);
5214     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5215     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5216       if (OpC->isZero()) continue;
5217       
5218       // Handle a struct index, which adds its field offset to the pointer.
5219       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5220         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5221         
5222         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5223           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5224         else
5225           Result = IC.InsertNewInstBefore(
5226                    BinaryOperator::CreateAdd(Result,
5227                                              ConstantInt::get(IntPtrTy, Size),
5228                                              GEP->getName()+".offs"), I);
5229         continue;
5230       }
5231       
5232       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5233       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5234       Scale = ConstantExpr::getMul(OC, Scale);
5235       if (Constant *RC = dyn_cast<Constant>(Result))
5236         Result = ConstantExpr::getAdd(RC, Scale);
5237       else {
5238         // Emit an add instruction.
5239         Result = IC.InsertNewInstBefore(
5240            BinaryOperator::CreateAdd(Result, Scale,
5241                                      GEP->getName()+".offs"), I);
5242       }
5243       continue;
5244     }
5245     // Convert to correct type.
5246     if (Op->getType() != IntPtrTy) {
5247       if (Constant *OpC = dyn_cast<Constant>(Op))
5248         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5249       else
5250         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5251                                                  Op->getName()+".c"), I);
5252     }
5253     if (Size != 1) {
5254       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5255       if (Constant *OpC = dyn_cast<Constant>(Op))
5256         Op = ConstantExpr::getMul(OpC, Scale);
5257       else    // We'll let instcombine(mul) convert this to a shl if possible.
5258         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5259                                                   GEP->getName()+".idx"), I);
5260     }
5261
5262     // Emit an add instruction.
5263     if (isa<Constant>(Op) && isa<Constant>(Result))
5264       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5265                                     cast<Constant>(Result));
5266     else
5267       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5268                                                   GEP->getName()+".offs"), I);
5269   }
5270   return Result;
5271 }
5272
5273
5274 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5275 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5276 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5277 /// complex, and scales are involved.  The above expression would also be legal
5278 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5279 /// later form is less amenable to optimization though, and we are allowed to
5280 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5281 ///
5282 /// If we can't emit an optimized form for this expression, this returns null.
5283 /// 
5284 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5285                                           InstCombiner &IC) {
5286   TargetData &TD = IC.getTargetData();
5287   gep_type_iterator GTI = gep_type_begin(GEP);
5288
5289   // Check to see if this gep only has a single variable index.  If so, and if
5290   // any constant indices are a multiple of its scale, then we can compute this
5291   // in terms of the scale of the variable index.  For example, if the GEP
5292   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5293   // because the expression will cross zero at the same point.
5294   unsigned i, e = GEP->getNumOperands();
5295   int64_t Offset = 0;
5296   for (i = 1; i != e; ++i, ++GTI) {
5297     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5298       // Compute the aggregate offset of constant indices.
5299       if (CI->isZero()) continue;
5300
5301       // Handle a struct index, which adds its field offset to the pointer.
5302       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5303         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5304       } else {
5305         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5306         Offset += Size*CI->getSExtValue();
5307       }
5308     } else {
5309       // Found our variable index.
5310       break;
5311     }
5312   }
5313   
5314   // If there are no variable indices, we must have a constant offset, just
5315   // evaluate it the general way.
5316   if (i == e) return 0;
5317   
5318   Value *VariableIdx = GEP->getOperand(i);
5319   // Determine the scale factor of the variable element.  For example, this is
5320   // 4 if the variable index is into an array of i32.
5321   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5322   
5323   // Verify that there are no other variable indices.  If so, emit the hard way.
5324   for (++i, ++GTI; i != e; ++i, ++GTI) {
5325     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5326     if (!CI) return 0;
5327    
5328     // Compute the aggregate offset of constant indices.
5329     if (CI->isZero()) continue;
5330     
5331     // Handle a struct index, which adds its field offset to the pointer.
5332     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5333       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5334     } else {
5335       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5336       Offset += Size*CI->getSExtValue();
5337     }
5338   }
5339   
5340   // Okay, we know we have a single variable index, which must be a
5341   // pointer/array/vector index.  If there is no offset, life is simple, return
5342   // the index.
5343   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5344   if (Offset == 0) {
5345     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5346     // we don't need to bother extending: the extension won't affect where the
5347     // computation crosses zero.
5348     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5349       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5350                                   VariableIdx->getNameStart(), &I);
5351     return VariableIdx;
5352   }
5353   
5354   // Otherwise, there is an index.  The computation we will do will be modulo
5355   // the pointer size, so get it.
5356   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5357   
5358   Offset &= PtrSizeMask;
5359   VariableScale &= PtrSizeMask;
5360
5361   // To do this transformation, any constant index must be a multiple of the
5362   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5363   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5364   // multiple of the variable scale.
5365   int64_t NewOffs = Offset / (int64_t)VariableScale;
5366   if (Offset != NewOffs*(int64_t)VariableScale)
5367     return 0;
5368
5369   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5370   const Type *IntPtrTy = TD.getIntPtrType();
5371   if (VariableIdx->getType() != IntPtrTy)
5372     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5373                                               true /*SExt*/, 
5374                                               VariableIdx->getNameStart(), &I);
5375   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5376   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5377 }
5378
5379
5380 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5381 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5382 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5383                                        ICmpInst::Predicate Cond,
5384                                        Instruction &I) {
5385   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5386
5387   // Look through bitcasts.
5388   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5389     RHS = BCI->getOperand(0);
5390
5391   Value *PtrBase = GEPLHS->getOperand(0);
5392   if (PtrBase == RHS) {
5393     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5394     // This transformation (ignoring the base and scales) is valid because we
5395     // know pointers can't overflow.  See if we can output an optimized form.
5396     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5397     
5398     // If not, synthesize the offset the hard way.
5399     if (Offset == 0)
5400       Offset = EmitGEPOffset(GEPLHS, I, *this);
5401     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5402                         Constant::getNullValue(Offset->getType()));
5403   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5404     // If the base pointers are different, but the indices are the same, just
5405     // compare the base pointer.
5406     if (PtrBase != GEPRHS->getOperand(0)) {
5407       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5408       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5409                         GEPRHS->getOperand(0)->getType();
5410       if (IndicesTheSame)
5411         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5412           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5413             IndicesTheSame = false;
5414             break;
5415           }
5416
5417       // If all indices are the same, just compare the base pointers.
5418       if (IndicesTheSame)
5419         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5420                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5421
5422       // Otherwise, the base pointers are different and the indices are
5423       // different, bail out.
5424       return 0;
5425     }
5426
5427     // If one of the GEPs has all zero indices, recurse.
5428     bool AllZeros = true;
5429     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5430       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5431           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5432         AllZeros = false;
5433         break;
5434       }
5435     if (AllZeros)
5436       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5437                           ICmpInst::getSwappedPredicate(Cond), I);
5438
5439     // If the other GEP has all zero indices, recurse.
5440     AllZeros = true;
5441     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5442       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5443           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5444         AllZeros = false;
5445         break;
5446       }
5447     if (AllZeros)
5448       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5449
5450     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5451       // If the GEPs only differ by one index, compare it.
5452       unsigned NumDifferences = 0;  // Keep track of # differences.
5453       unsigned DiffOperand = 0;     // The operand that differs.
5454       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5455         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5456           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5457                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5458             // Irreconcilable differences.
5459             NumDifferences = 2;
5460             break;
5461           } else {
5462             if (NumDifferences++) break;
5463             DiffOperand = i;
5464           }
5465         }
5466
5467       if (NumDifferences == 0)   // SAME GEP?
5468         return ReplaceInstUsesWith(I, // No comparison is needed here.
5469                                    ConstantInt::get(Type::Int1Ty,
5470                                              ICmpInst::isTrueWhenEqual(Cond)));
5471
5472       else if (NumDifferences == 1) {
5473         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5474         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5475         // Make sure we do a signed comparison here.
5476         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5477       }
5478     }
5479
5480     // Only lower this if the icmp is the only user of the GEP or if we expect
5481     // the result to fold to a constant!
5482     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5483         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5484       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5485       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5486       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5487       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5488     }
5489   }
5490   return 0;
5491 }
5492
5493 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5494 ///
5495 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5496                                                 Instruction *LHSI,
5497                                                 Constant *RHSC) {
5498   if (!isa<ConstantFP>(RHSC)) return 0;
5499   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5500   
5501   // Get the width of the mantissa.  We don't want to hack on conversions that
5502   // might lose information from the integer, e.g. "i64 -> float"
5503   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5504   if (MantissaWidth == -1) return 0;  // Unknown.
5505   
5506   // Check to see that the input is converted from an integer type that is small
5507   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5508   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5509   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5510   
5511   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5512   if (isa<UIToFPInst>(LHSI))
5513     ++InputSize;
5514   
5515   // If the conversion would lose info, don't hack on this.
5516   if ((int)InputSize > MantissaWidth)
5517     return 0;
5518   
5519   // Otherwise, we can potentially simplify the comparison.  We know that it
5520   // will always come through as an integer value and we know the constant is
5521   // not a NAN (it would have been previously simplified).
5522   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5523   
5524   ICmpInst::Predicate Pred;
5525   switch (I.getPredicate()) {
5526   default: assert(0 && "Unexpected predicate!");
5527   case FCmpInst::FCMP_UEQ:
5528   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5529   case FCmpInst::FCMP_UGT:
5530   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5531   case FCmpInst::FCMP_UGE:
5532   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5533   case FCmpInst::FCMP_ULT:
5534   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5535   case FCmpInst::FCMP_ULE:
5536   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5537   case FCmpInst::FCMP_UNE:
5538   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5539   case FCmpInst::FCMP_ORD:
5540     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5541   case FCmpInst::FCMP_UNO:
5542     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5543   }
5544   
5545   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5546   
5547   // Now we know that the APFloat is a normal number, zero or inf.
5548   
5549   // See if the FP constant is too large for the integer.  For example,
5550   // comparing an i8 to 300.0.
5551   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5552   
5553   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5554   // and large values. 
5555   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5556   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5557                         APFloat::rmNearestTiesToEven);
5558   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5559     if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5560       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5561     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5562   }
5563   
5564   // See if the RHS value is < SignedMin.
5565   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5566   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5567                         APFloat::rmNearestTiesToEven);
5568   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5569     if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5570       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5571     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5572   }
5573
5574   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5575   // it may still be fractional.  See if it is fractional by casting the FP
5576   // value to the integer value and back, checking for equality.  Don't do this
5577   // for zero, because -0.0 is not fractional.
5578   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5579   if (!RHS.isZero() &&
5580       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5581     // If we had a comparison against a fractional value, we have to adjust
5582     // the compare predicate and sometimes the value.  RHSC is rounded towards
5583     // zero at this point.
5584     switch (Pred) {
5585     default: assert(0 && "Unexpected integer comparison!");
5586     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5587       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5588     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5589       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5590     case ICmpInst::ICMP_SLE:
5591       // (float)int <= 4.4   --> int <= 4
5592       // (float)int <= -4.4  --> int < -4
5593       if (RHS.isNegative())
5594         Pred = ICmpInst::ICMP_SLT;
5595       break;
5596     case ICmpInst::ICMP_SLT:
5597       // (float)int < -4.4   --> int < -4
5598       // (float)int < 4.4    --> int <= 4
5599       if (!RHS.isNegative())
5600         Pred = ICmpInst::ICMP_SLE;
5601       break;
5602     case ICmpInst::ICMP_SGT:
5603       // (float)int > 4.4    --> int > 4
5604       // (float)int > -4.4   --> int >= -4
5605       if (RHS.isNegative())
5606         Pred = ICmpInst::ICMP_SGE;
5607       break;
5608     case ICmpInst::ICMP_SGE:
5609       // (float)int >= -4.4   --> int >= -4
5610       // (float)int >= 4.4    --> int > 4
5611       if (!RHS.isNegative())
5612         Pred = ICmpInst::ICMP_SGT;
5613       break;
5614     }
5615   }
5616
5617   // Lower this FP comparison into an appropriate integer version of the
5618   // comparison.
5619   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5620 }
5621
5622 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5623   bool Changed = SimplifyCompare(I);
5624   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5625
5626   // Fold trivial predicates.
5627   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5628     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5629   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5630     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5631   
5632   // Simplify 'fcmp pred X, X'
5633   if (Op0 == Op1) {
5634     switch (I.getPredicate()) {
5635     default: assert(0 && "Unknown predicate!");
5636     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5637     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5638     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5639       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5640     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5641     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5642     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5643       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5644       
5645     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5646     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5647     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5648     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5649       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5650       I.setPredicate(FCmpInst::FCMP_UNO);
5651       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5652       return &I;
5653       
5654     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5655     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5656     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5657     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5658       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5659       I.setPredicate(FCmpInst::FCMP_ORD);
5660       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5661       return &I;
5662     }
5663   }
5664     
5665   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5666     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5667
5668   // Handle fcmp with constant RHS
5669   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5670     // If the constant is a nan, see if we can fold the comparison based on it.
5671     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5672       if (CFP->getValueAPF().isNaN()) {
5673         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5674           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5675         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5676                "Comparison must be either ordered or unordered!");
5677         // True if unordered.
5678         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5679       }
5680     }
5681     
5682     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5683       switch (LHSI->getOpcode()) {
5684       case Instruction::PHI:
5685         if (Instruction *NV = FoldOpIntoPhi(I))
5686           return NV;
5687         break;
5688       case Instruction::SIToFP:
5689       case Instruction::UIToFP:
5690         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5691           return NV;
5692         break;
5693       case Instruction::Select:
5694         // If either operand of the select is a constant, we can fold the
5695         // comparison into the select arms, which will cause one to be
5696         // constant folded and the select turned into a bitwise or.
5697         Value *Op1 = 0, *Op2 = 0;
5698         if (LHSI->hasOneUse()) {
5699           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5700             // Fold the known value into the constant operand.
5701             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5702             // Insert a new FCmp of the other select operand.
5703             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5704                                                       LHSI->getOperand(2), RHSC,
5705                                                       I.getName()), I);
5706           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5707             // Fold the known value into the constant operand.
5708             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5709             // Insert a new FCmp of the other select operand.
5710             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5711                                                       LHSI->getOperand(1), RHSC,
5712                                                       I.getName()), I);
5713           }
5714         }
5715
5716         if (Op1)
5717           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5718         break;
5719       }
5720   }
5721
5722   return Changed ? &I : 0;
5723 }
5724
5725 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5726   bool Changed = SimplifyCompare(I);
5727   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5728   const Type *Ty = Op0->getType();
5729
5730   // icmp X, X
5731   if (Op0 == Op1)
5732     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5733                                                    I.isTrueWhenEqual()));
5734
5735   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5736     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5737   
5738   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5739   // addresses never equal each other!  We already know that Op0 != Op1.
5740   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5741        isa<ConstantPointerNull>(Op0)) &&
5742       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5743        isa<ConstantPointerNull>(Op1)))
5744     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5745                                                    !I.isTrueWhenEqual()));
5746
5747   // icmp's with boolean values can always be turned into bitwise operations
5748   if (Ty == Type::Int1Ty) {
5749     switch (I.getPredicate()) {
5750     default: assert(0 && "Invalid icmp instruction!");
5751     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
5752       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5753       InsertNewInstBefore(Xor, I);
5754       return BinaryOperator::CreateNot(Xor);
5755     }
5756     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
5757       return BinaryOperator::CreateXor(Op0, Op1);
5758
5759     case ICmpInst::ICMP_UGT:
5760     case ICmpInst::ICMP_SGT:
5761       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
5762       // FALL THROUGH
5763     case ICmpInst::ICMP_ULT:
5764     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
5765       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5766       InsertNewInstBefore(Not, I);
5767       return BinaryOperator::CreateAnd(Not, Op1);
5768     }
5769     case ICmpInst::ICMP_UGE:
5770     case ICmpInst::ICMP_SGE:
5771       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
5772       // FALL THROUGH
5773     case ICmpInst::ICMP_ULE:
5774     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
5775       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5776       InsertNewInstBefore(Not, I);
5777       return BinaryOperator::CreateOr(Not, Op1);
5778     }
5779     }
5780   }
5781
5782   // See if we are doing a comparison between a constant and an instruction that
5783   // can be folded into the comparison.
5784   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5785       Value *A, *B;
5786     
5787     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5788     if (I.isEquality() && CI->isNullValue() &&
5789         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5790       // (icmp cond A B) if cond is equality
5791       return new ICmpInst(I.getPredicate(), A, B);
5792     }
5793     
5794     switch (I.getPredicate()) {
5795     default: break;
5796     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5797       if (CI->isMinValue(false))
5798         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5799       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5800         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5801       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5802         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5803       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5804       if (CI->isMinValue(true))
5805         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5806                             ConstantInt::getAllOnesValue(Op0->getType()));
5807           
5808       break;
5809
5810     case ICmpInst::ICMP_SLT:
5811       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5812         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5813       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5814         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5815       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5816         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5817       break;
5818
5819     case ICmpInst::ICMP_UGT:
5820       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5821         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5822       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5823         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5824       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5825         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5826         
5827       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5828       if (CI->isMaxValue(true))
5829         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5830                             ConstantInt::getNullValue(Op0->getType()));
5831       break;
5832
5833     case ICmpInst::ICMP_SGT:
5834       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5835         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5836       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5837         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5838       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5839         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5840       break;
5841
5842     case ICmpInst::ICMP_ULE:
5843       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5844         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5845       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5846         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5847       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5848         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5849       break;
5850
5851     case ICmpInst::ICMP_SLE:
5852       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5853         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5854       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5855         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5856       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5857         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5858       break;
5859
5860     case ICmpInst::ICMP_UGE:
5861       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5862         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5863       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5864         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5865       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5866         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5867       break;
5868
5869     case ICmpInst::ICMP_SGE:
5870       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5871         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5872       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5873         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5874       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5875         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5876       break;
5877     }
5878
5879     // If we still have a icmp le or icmp ge instruction, turn it into the
5880     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5881     // already been handled above, this requires little checking.
5882     //
5883     switch (I.getPredicate()) {
5884     default: break;
5885     case ICmpInst::ICMP_ULE: 
5886       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5887     case ICmpInst::ICMP_SLE:
5888       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5889     case ICmpInst::ICMP_UGE:
5890       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5891     case ICmpInst::ICMP_SGE:
5892       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5893     }
5894     
5895     // See if we can fold the comparison based on bits known to be zero or one
5896     // in the input.  If this comparison is a normal comparison, it demands all
5897     // bits, if it is a sign bit comparison, it only demands the sign bit.
5898     
5899     bool UnusedBit;
5900     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5901     
5902     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5903     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5904     if (SimplifyDemandedBits(Op0, 
5905                              isSignBit ? APInt::getSignBit(BitWidth)
5906                                        : APInt::getAllOnesValue(BitWidth),
5907                              KnownZero, KnownOne, 0))
5908       return &I;
5909         
5910     // Given the known and unknown bits, compute a range that the LHS could be
5911     // in.
5912     if ((KnownOne | KnownZero) != 0) {
5913       // Compute the Min, Max and RHS values based on the known bits. For the
5914       // EQ and NE we use unsigned values.
5915       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5916       const APInt& RHSVal = CI->getValue();
5917       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5918         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5919                                                Max);
5920       } else {
5921         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5922                                                  Max);
5923       }
5924       switch (I.getPredicate()) {  // LE/GE have been folded already.
5925       default: assert(0 && "Unknown icmp opcode!");
5926       case ICmpInst::ICMP_EQ:
5927         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5928           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5929         break;
5930       case ICmpInst::ICMP_NE:
5931         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5932           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5933         break;
5934       case ICmpInst::ICMP_ULT:
5935         if (Max.ult(RHSVal))
5936           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5937         if (Min.uge(RHSVal))
5938           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5939         break;
5940       case ICmpInst::ICMP_UGT:
5941         if (Min.ugt(RHSVal))
5942           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5943         if (Max.ule(RHSVal))
5944           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5945         break;
5946       case ICmpInst::ICMP_SLT:
5947         if (Max.slt(RHSVal))
5948           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5949         if (Min.sgt(RHSVal))
5950           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5951         break;
5952       case ICmpInst::ICMP_SGT: 
5953         if (Min.sgt(RHSVal))
5954           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5955         if (Max.sle(RHSVal))
5956           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5957         break;
5958       }
5959     }
5960           
5961     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5962     // instruction, see if that instruction also has constants so that the 
5963     // instruction can be folded into the icmp 
5964     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5965       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5966         return Res;
5967   }
5968
5969   // Handle icmp with constant (but not simple integer constant) RHS
5970   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5971     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5972       switch (LHSI->getOpcode()) {
5973       case Instruction::GetElementPtr:
5974         if (RHSC->isNullValue()) {
5975           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5976           bool isAllZeros = true;
5977           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5978             if (!isa<Constant>(LHSI->getOperand(i)) ||
5979                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5980               isAllZeros = false;
5981               break;
5982             }
5983           if (isAllZeros)
5984             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5985                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5986         }
5987         break;
5988
5989       case Instruction::PHI:
5990         if (Instruction *NV = FoldOpIntoPhi(I))
5991           return NV;
5992         break;
5993       case Instruction::Select: {
5994         // If either operand of the select is a constant, we can fold the
5995         // comparison into the select arms, which will cause one to be
5996         // constant folded and the select turned into a bitwise or.
5997         Value *Op1 = 0, *Op2 = 0;
5998         if (LHSI->hasOneUse()) {
5999           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6000             // Fold the known value into the constant operand.
6001             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6002             // Insert a new ICmp of the other select operand.
6003             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6004                                                    LHSI->getOperand(2), RHSC,
6005                                                    I.getName()), I);
6006           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6007             // Fold the known value into the constant operand.
6008             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6009             // Insert a new ICmp of the other select operand.
6010             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6011                                                    LHSI->getOperand(1), RHSC,
6012                                                    I.getName()), I);
6013           }
6014         }
6015
6016         if (Op1)
6017           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6018         break;
6019       }
6020       case Instruction::Malloc:
6021         // If we have (malloc != null), and if the malloc has a single use, we
6022         // can assume it is successful and remove the malloc.
6023         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6024           AddToWorkList(LHSI);
6025           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6026                                                          !I.isTrueWhenEqual()));
6027         }
6028         break;
6029       }
6030   }
6031
6032   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6033   if (User *GEP = dyn_castGetElementPtr(Op0))
6034     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6035       return NI;
6036   if (User *GEP = dyn_castGetElementPtr(Op1))
6037     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6038                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6039       return NI;
6040
6041   // Test to see if the operands of the icmp are casted versions of other
6042   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6043   // now.
6044   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6045     if (isa<PointerType>(Op0->getType()) && 
6046         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6047       // We keep moving the cast from the left operand over to the right
6048       // operand, where it can often be eliminated completely.
6049       Op0 = CI->getOperand(0);
6050
6051       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6052       // so eliminate it as well.
6053       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6054         Op1 = CI2->getOperand(0);
6055
6056       // If Op1 is a constant, we can fold the cast into the constant.
6057       if (Op0->getType() != Op1->getType()) {
6058         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6059           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6060         } else {
6061           // Otherwise, cast the RHS right before the icmp
6062           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6063         }
6064       }
6065       return new ICmpInst(I.getPredicate(), Op0, Op1);
6066     }
6067   }
6068   
6069   if (isa<CastInst>(Op0)) {
6070     // Handle the special case of: icmp (cast bool to X), <cst>
6071     // This comes up when you have code like
6072     //   int X = A < B;
6073     //   if (X) ...
6074     // For generality, we handle any zero-extension of any operand comparison
6075     // with a constant or another cast from the same type.
6076     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6077       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6078         return R;
6079   }
6080   
6081   // ~x < ~y --> y < x
6082   { Value *A, *B;
6083     if (match(Op0, m_Not(m_Value(A))) &&
6084         match(Op1, m_Not(m_Value(B))))
6085       return new ICmpInst(I.getPredicate(), B, A);
6086   }
6087   
6088   if (I.isEquality()) {
6089     Value *A, *B, *C, *D;
6090     
6091     // -x == -y --> x == y
6092     if (match(Op0, m_Neg(m_Value(A))) &&
6093         match(Op1, m_Neg(m_Value(B))))
6094       return new ICmpInst(I.getPredicate(), A, B);
6095     
6096     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6097       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6098         Value *OtherVal = A == Op1 ? B : A;
6099         return new ICmpInst(I.getPredicate(), OtherVal,
6100                             Constant::getNullValue(A->getType()));
6101       }
6102
6103       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6104         // A^c1 == C^c2 --> A == C^(c1^c2)
6105         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6106           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6107             if (Op1->hasOneUse()) {
6108               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6109               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6110               return new ICmpInst(I.getPredicate(), A,
6111                                   InsertNewInstBefore(Xor, I));
6112             }
6113         
6114         // A^B == A^D -> B == D
6115         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6116         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6117         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6118         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6119       }
6120     }
6121     
6122     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6123         (A == Op0 || B == Op0)) {
6124       // A == (A^B)  ->  B == 0
6125       Value *OtherVal = A == Op0 ? B : A;
6126       return new ICmpInst(I.getPredicate(), OtherVal,
6127                           Constant::getNullValue(A->getType()));
6128     }
6129     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
6130       // (A-B) == A  ->  B == 0
6131       return new ICmpInst(I.getPredicate(), B,
6132                           Constant::getNullValue(B->getType()));
6133     }
6134     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
6135       // A == (A-B)  ->  B == 0
6136       return new ICmpInst(I.getPredicate(), B,
6137                           Constant::getNullValue(B->getType()));
6138     }
6139     
6140     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6141     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6142         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6143         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6144       Value *X = 0, *Y = 0, *Z = 0;
6145       
6146       if (A == C) {
6147         X = B; Y = D; Z = A;
6148       } else if (A == D) {
6149         X = B; Y = C; Z = A;
6150       } else if (B == C) {
6151         X = A; Y = D; Z = B;
6152       } else if (B == D) {
6153         X = A; Y = C; Z = B;
6154       }
6155       
6156       if (X) {   // Build (X^Y) & Z
6157         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6158         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6159         I.setOperand(0, Op1);
6160         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6161         return &I;
6162       }
6163     }
6164   }
6165   return Changed ? &I : 0;
6166 }
6167
6168
6169 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6170 /// and CmpRHS are both known to be integer constants.
6171 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6172                                           ConstantInt *DivRHS) {
6173   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6174   const APInt &CmpRHSV = CmpRHS->getValue();
6175   
6176   // FIXME: If the operand types don't match the type of the divide 
6177   // then don't attempt this transform. The code below doesn't have the
6178   // logic to deal with a signed divide and an unsigned compare (and
6179   // vice versa). This is because (x /s C1) <s C2  produces different 
6180   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6181   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6182   // work. :(  The if statement below tests that condition and bails 
6183   // if it finds it. 
6184   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6185   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6186     return 0;
6187   if (DivRHS->isZero())
6188     return 0; // The ProdOV computation fails on divide by zero.
6189
6190   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6191   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6192   // C2 (CI). By solving for X we can turn this into a range check 
6193   // instead of computing a divide. 
6194   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6195
6196   // Determine if the product overflows by seeing if the product is
6197   // not equal to the divide. Make sure we do the same kind of divide
6198   // as in the LHS instruction that we're folding. 
6199   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6200                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6201
6202   // Get the ICmp opcode
6203   ICmpInst::Predicate Pred = ICI.getPredicate();
6204
6205   // Figure out the interval that is being checked.  For example, a comparison
6206   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6207   // Compute this interval based on the constants involved and the signedness of
6208   // the compare/divide.  This computes a half-open interval, keeping track of
6209   // whether either value in the interval overflows.  After analysis each
6210   // overflow variable is set to 0 if it's corresponding bound variable is valid
6211   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6212   int LoOverflow = 0, HiOverflow = 0;
6213   ConstantInt *LoBound = 0, *HiBound = 0;
6214   
6215   
6216   if (!DivIsSigned) {  // udiv
6217     // e.g. X/5 op 3  --> [15, 20)
6218     LoBound = Prod;
6219     HiOverflow = LoOverflow = ProdOV;
6220     if (!HiOverflow)
6221       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6222   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6223     if (CmpRHSV == 0) {       // (X / pos) op 0
6224       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6225       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6226       HiBound = DivRHS;
6227     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6228       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6229       HiOverflow = LoOverflow = ProdOV;
6230       if (!HiOverflow)
6231         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6232     } else {                       // (X / pos) op neg
6233       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6234       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6235       LoOverflow = AddWithOverflow(LoBound, Prod,
6236                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
6237       HiBound = AddOne(Prod);
6238       HiOverflow = ProdOV ? -1 : 0;
6239     }
6240   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6241     if (CmpRHSV == 0) {       // (X / neg) op 0
6242       // e.g. X/-5 op 0  --> [-4, 5)
6243       LoBound = AddOne(DivRHS);
6244       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6245       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6246         HiOverflow = 1;            // [INTMIN+1, overflow)
6247         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6248       }
6249     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6250       // e.g. X/-5 op 3  --> [-19, -14)
6251       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6252       if (!LoOverflow)
6253         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
6254       HiBound = AddOne(Prod);
6255     } else {                       // (X / neg) op neg
6256       // e.g. X/-5 op -3  --> [15, 20)
6257       LoBound = Prod;
6258       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
6259       HiBound = Subtract(Prod, DivRHS);
6260     }
6261     
6262     // Dividing by a negative swaps the condition.  LT <-> GT
6263     Pred = ICmpInst::getSwappedPredicate(Pred);
6264   }
6265
6266   Value *X = DivI->getOperand(0);
6267   switch (Pred) {
6268   default: assert(0 && "Unhandled icmp opcode!");
6269   case ICmpInst::ICMP_EQ:
6270     if (LoOverflow && HiOverflow)
6271       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6272     else if (HiOverflow)
6273       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6274                           ICmpInst::ICMP_UGE, X, LoBound);
6275     else if (LoOverflow)
6276       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6277                           ICmpInst::ICMP_ULT, X, HiBound);
6278     else
6279       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6280   case ICmpInst::ICMP_NE:
6281     if (LoOverflow && HiOverflow)
6282       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6283     else if (HiOverflow)
6284       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6285                           ICmpInst::ICMP_ULT, X, LoBound);
6286     else if (LoOverflow)
6287       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6288                           ICmpInst::ICMP_UGE, X, HiBound);
6289     else
6290       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6291   case ICmpInst::ICMP_ULT:
6292   case ICmpInst::ICMP_SLT:
6293     if (LoOverflow == +1)   // Low bound is greater than input range.
6294       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6295     if (LoOverflow == -1)   // Low bound is less than input range.
6296       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6297     return new ICmpInst(Pred, X, LoBound);
6298   case ICmpInst::ICMP_UGT:
6299   case ICmpInst::ICMP_SGT:
6300     if (HiOverflow == +1)       // High bound greater than input range.
6301       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6302     else if (HiOverflow == -1)  // High bound less than input range.
6303       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6304     if (Pred == ICmpInst::ICMP_UGT)
6305       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6306     else
6307       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6308   }
6309 }
6310
6311
6312 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6313 ///
6314 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6315                                                           Instruction *LHSI,
6316                                                           ConstantInt *RHS) {
6317   const APInt &RHSV = RHS->getValue();
6318   
6319   switch (LHSI->getOpcode()) {
6320   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6321     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6322       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6323       // fold the xor.
6324       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6325           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6326         Value *CompareVal = LHSI->getOperand(0);
6327         
6328         // If the sign bit of the XorCST is not set, there is no change to
6329         // the operation, just stop using the Xor.
6330         if (!XorCST->getValue().isNegative()) {
6331           ICI.setOperand(0, CompareVal);
6332           AddToWorkList(LHSI);
6333           return &ICI;
6334         }
6335         
6336         // Was the old condition true if the operand is positive?
6337         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6338         
6339         // If so, the new one isn't.
6340         isTrueIfPositive ^= true;
6341         
6342         if (isTrueIfPositive)
6343           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6344         else
6345           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6346       }
6347     }
6348     break;
6349   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6350     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6351         LHSI->getOperand(0)->hasOneUse()) {
6352       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6353       
6354       // If the LHS is an AND of a truncating cast, we can widen the
6355       // and/compare to be the input width without changing the value
6356       // produced, eliminating a cast.
6357       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6358         // We can do this transformation if either the AND constant does not
6359         // have its sign bit set or if it is an equality comparison. 
6360         // Extending a relational comparison when we're checking the sign
6361         // bit would not work.
6362         if (Cast->hasOneUse() &&
6363             (ICI.isEquality() ||
6364              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6365           uint32_t BitWidth = 
6366             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6367           APInt NewCST = AndCST->getValue();
6368           NewCST.zext(BitWidth);
6369           APInt NewCI = RHSV;
6370           NewCI.zext(BitWidth);
6371           Instruction *NewAnd = 
6372             BinaryOperator::CreateAnd(Cast->getOperand(0),
6373                                       ConstantInt::get(NewCST),LHSI->getName());
6374           InsertNewInstBefore(NewAnd, ICI);
6375           return new ICmpInst(ICI.getPredicate(), NewAnd,
6376                               ConstantInt::get(NewCI));
6377         }
6378       }
6379       
6380       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6381       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6382       // happens a LOT in code produced by the C front-end, for bitfield
6383       // access.
6384       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6385       if (Shift && !Shift->isShift())
6386         Shift = 0;
6387       
6388       ConstantInt *ShAmt;
6389       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6390       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6391       const Type *AndTy = AndCST->getType();          // Type of the and.
6392       
6393       // We can fold this as long as we can't shift unknown bits
6394       // into the mask.  This can only happen with signed shift
6395       // rights, as they sign-extend.
6396       if (ShAmt) {
6397         bool CanFold = Shift->isLogicalShift();
6398         if (!CanFold) {
6399           // To test for the bad case of the signed shr, see if any
6400           // of the bits shifted in could be tested after the mask.
6401           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6402           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6403           
6404           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6405           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6406                AndCST->getValue()) == 0)
6407             CanFold = true;
6408         }
6409         
6410         if (CanFold) {
6411           Constant *NewCst;
6412           if (Shift->getOpcode() == Instruction::Shl)
6413             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6414           else
6415             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6416           
6417           // Check to see if we are shifting out any of the bits being
6418           // compared.
6419           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6420             // If we shifted bits out, the fold is not going to work out.
6421             // As a special case, check to see if this means that the
6422             // result is always true or false now.
6423             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6424               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6425             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6426               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6427           } else {
6428             ICI.setOperand(1, NewCst);
6429             Constant *NewAndCST;
6430             if (Shift->getOpcode() == Instruction::Shl)
6431               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6432             else
6433               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6434             LHSI->setOperand(1, NewAndCST);
6435             LHSI->setOperand(0, Shift->getOperand(0));
6436             AddToWorkList(Shift); // Shift is dead.
6437             AddUsesToWorkList(ICI);
6438             return &ICI;
6439           }
6440         }
6441       }
6442       
6443       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6444       // preferable because it allows the C<<Y expression to be hoisted out
6445       // of a loop if Y is invariant and X is not.
6446       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6447           ICI.isEquality() && !Shift->isArithmeticShift() &&
6448           isa<Instruction>(Shift->getOperand(0))) {
6449         // Compute C << Y.
6450         Value *NS;
6451         if (Shift->getOpcode() == Instruction::LShr) {
6452           NS = BinaryOperator::CreateShl(AndCST, 
6453                                          Shift->getOperand(1), "tmp");
6454         } else {
6455           // Insert a logical shift.
6456           NS = BinaryOperator::CreateLShr(AndCST,
6457                                           Shift->getOperand(1), "tmp");
6458         }
6459         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6460         
6461         // Compute X & (C << Y).
6462         Instruction *NewAnd = 
6463           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6464         InsertNewInstBefore(NewAnd, ICI);
6465         
6466         ICI.setOperand(0, NewAnd);
6467         return &ICI;
6468       }
6469     }
6470     break;
6471     
6472   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6473     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6474     if (!ShAmt) break;
6475     
6476     uint32_t TypeBits = RHSV.getBitWidth();
6477     
6478     // Check that the shift amount is in range.  If not, don't perform
6479     // undefined shifts.  When the shift is visited it will be
6480     // simplified.
6481     if (ShAmt->uge(TypeBits))
6482       break;
6483     
6484     if (ICI.isEquality()) {
6485       // If we are comparing against bits always shifted out, the
6486       // comparison cannot succeed.
6487       Constant *Comp =
6488         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6489       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6490         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6491         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6492         return ReplaceInstUsesWith(ICI, Cst);
6493       }
6494       
6495       if (LHSI->hasOneUse()) {
6496         // Otherwise strength reduce the shift into an and.
6497         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6498         Constant *Mask =
6499           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6500         
6501         Instruction *AndI =
6502           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6503                                     Mask, LHSI->getName()+".mask");
6504         Value *And = InsertNewInstBefore(AndI, ICI);
6505         return new ICmpInst(ICI.getPredicate(), And,
6506                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6507       }
6508     }
6509     
6510     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6511     bool TrueIfSigned = false;
6512     if (LHSI->hasOneUse() &&
6513         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6514       // (X << 31) <s 0  --> (X&1) != 0
6515       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6516                                            (TypeBits-ShAmt->getZExtValue()-1));
6517       Instruction *AndI =
6518         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6519                                   Mask, LHSI->getName()+".mask");
6520       Value *And = InsertNewInstBefore(AndI, ICI);
6521       
6522       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6523                           And, Constant::getNullValue(And->getType()));
6524     }
6525     break;
6526   }
6527     
6528   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6529   case Instruction::AShr: {
6530     // Only handle equality comparisons of shift-by-constant.
6531     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6532     if (!ShAmt || !ICI.isEquality()) break;
6533
6534     // Check that the shift amount is in range.  If not, don't perform
6535     // undefined shifts.  When the shift is visited it will be
6536     // simplified.
6537     uint32_t TypeBits = RHSV.getBitWidth();
6538     if (ShAmt->uge(TypeBits))
6539       break;
6540     
6541     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6542       
6543     // If we are comparing against bits always shifted out, the
6544     // comparison cannot succeed.
6545     APInt Comp = RHSV << ShAmtVal;
6546     if (LHSI->getOpcode() == Instruction::LShr)
6547       Comp = Comp.lshr(ShAmtVal);
6548     else
6549       Comp = Comp.ashr(ShAmtVal);
6550     
6551     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6552       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6553       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6554       return ReplaceInstUsesWith(ICI, Cst);
6555     }
6556     
6557     // Otherwise, check to see if the bits shifted out are known to be zero.
6558     // If so, we can compare against the unshifted value:
6559     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6560     if (LHSI->hasOneUse() &&
6561         MaskedValueIsZero(LHSI->getOperand(0), 
6562                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6563       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6564                           ConstantExpr::getShl(RHS, ShAmt));
6565     }
6566       
6567     if (LHSI->hasOneUse()) {
6568       // Otherwise strength reduce the shift into an and.
6569       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6570       Constant *Mask = ConstantInt::get(Val);
6571       
6572       Instruction *AndI =
6573         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6574                                   Mask, LHSI->getName()+".mask");
6575       Value *And = InsertNewInstBefore(AndI, ICI);
6576       return new ICmpInst(ICI.getPredicate(), And,
6577                           ConstantExpr::getShl(RHS, ShAmt));
6578     }
6579     break;
6580   }
6581     
6582   case Instruction::SDiv:
6583   case Instruction::UDiv:
6584     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6585     // Fold this div into the comparison, producing a range check. 
6586     // Determine, based on the divide type, what the range is being 
6587     // checked.  If there is an overflow on the low or high side, remember 
6588     // it, otherwise compute the range [low, hi) bounding the new value.
6589     // See: InsertRangeTest above for the kinds of replacements possible.
6590     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6591       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6592                                           DivRHS))
6593         return R;
6594     break;
6595
6596   case Instruction::Add:
6597     // Fold: icmp pred (add, X, C1), C2
6598
6599     if (!ICI.isEquality()) {
6600       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6601       if (!LHSC) break;
6602       const APInt &LHSV = LHSC->getValue();
6603
6604       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6605                             .subtract(LHSV);
6606
6607       if (ICI.isSignedPredicate()) {
6608         if (CR.getLower().isSignBit()) {
6609           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6610                               ConstantInt::get(CR.getUpper()));
6611         } else if (CR.getUpper().isSignBit()) {
6612           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6613                               ConstantInt::get(CR.getLower()));
6614         }
6615       } else {
6616         if (CR.getLower().isMinValue()) {
6617           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6618                               ConstantInt::get(CR.getUpper()));
6619         } else if (CR.getUpper().isMinValue()) {
6620           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6621                               ConstantInt::get(CR.getLower()));
6622         }
6623       }
6624     }
6625     break;
6626   }
6627   
6628   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6629   if (ICI.isEquality()) {
6630     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6631     
6632     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6633     // the second operand is a constant, simplify a bit.
6634     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6635       switch (BO->getOpcode()) {
6636       case Instruction::SRem:
6637         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6638         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6639           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6640           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6641             Instruction *NewRem =
6642               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6643                                          BO->getName());
6644             InsertNewInstBefore(NewRem, ICI);
6645             return new ICmpInst(ICI.getPredicate(), NewRem, 
6646                                 Constant::getNullValue(BO->getType()));
6647           }
6648         }
6649         break;
6650       case Instruction::Add:
6651         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6652         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6653           if (BO->hasOneUse())
6654             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6655                                 Subtract(RHS, BOp1C));
6656         } else if (RHSV == 0) {
6657           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6658           // efficiently invertible, or if the add has just this one use.
6659           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6660           
6661           if (Value *NegVal = dyn_castNegVal(BOp1))
6662             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6663           else if (Value *NegVal = dyn_castNegVal(BOp0))
6664             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6665           else if (BO->hasOneUse()) {
6666             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6667             InsertNewInstBefore(Neg, ICI);
6668             Neg->takeName(BO);
6669             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6670           }
6671         }
6672         break;
6673       case Instruction::Xor:
6674         // For the xor case, we can xor two constants together, eliminating
6675         // the explicit xor.
6676         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6677           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6678                               ConstantExpr::getXor(RHS, BOC));
6679         
6680         // FALLTHROUGH
6681       case Instruction::Sub:
6682         // Replace (([sub|xor] A, B) != 0) with (A != B)
6683         if (RHSV == 0)
6684           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6685                               BO->getOperand(1));
6686         break;
6687         
6688       case Instruction::Or:
6689         // If bits are being or'd in that are not present in the constant we
6690         // are comparing against, then the comparison could never succeed!
6691         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6692           Constant *NotCI = ConstantExpr::getNot(RHS);
6693           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6694             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6695                                                              isICMP_NE));
6696         }
6697         break;
6698         
6699       case Instruction::And:
6700         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6701           // If bits are being compared against that are and'd out, then the
6702           // comparison can never succeed!
6703           if ((RHSV & ~BOC->getValue()) != 0)
6704             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6705                                                              isICMP_NE));
6706           
6707           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6708           if (RHS == BOC && RHSV.isPowerOf2())
6709             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6710                                 ICmpInst::ICMP_NE, LHSI,
6711                                 Constant::getNullValue(RHS->getType()));
6712           
6713           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6714           if (isSignBit(BOC)) {
6715             Value *X = BO->getOperand(0);
6716             Constant *Zero = Constant::getNullValue(X->getType());
6717             ICmpInst::Predicate pred = isICMP_NE ? 
6718               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6719             return new ICmpInst(pred, X, Zero);
6720           }
6721           
6722           // ((X & ~7) == 0) --> X < 8
6723           if (RHSV == 0 && isHighOnes(BOC)) {
6724             Value *X = BO->getOperand(0);
6725             Constant *NegX = ConstantExpr::getNeg(BOC);
6726             ICmpInst::Predicate pred = isICMP_NE ? 
6727               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6728             return new ICmpInst(pred, X, NegX);
6729           }
6730         }
6731       default: break;
6732       }
6733     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6734       // Handle icmp {eq|ne} <intrinsic>, intcst.
6735       if (II->getIntrinsicID() == Intrinsic::bswap) {
6736         AddToWorkList(II);
6737         ICI.setOperand(0, II->getOperand(1));
6738         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6739         return &ICI;
6740       }
6741     }
6742   } else {  // Not a ICMP_EQ/ICMP_NE
6743             // If the LHS is a cast from an integral value of the same size, 
6744             // then since we know the RHS is a constant, try to simlify.
6745     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6746       Value *CastOp = Cast->getOperand(0);
6747       const Type *SrcTy = CastOp->getType();
6748       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6749       if (SrcTy->isInteger() && 
6750           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6751         // If this is an unsigned comparison, try to make the comparison use
6752         // smaller constant values.
6753         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6754           // X u< 128 => X s> -1
6755           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6756                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6757         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6758                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6759           // X u> 127 => X s< 0
6760           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6761                               Constant::getNullValue(SrcTy));
6762         }
6763       }
6764     }
6765   }
6766   return 0;
6767 }
6768
6769 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6770 /// We only handle extending casts so far.
6771 ///
6772 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6773   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6774   Value *LHSCIOp        = LHSCI->getOperand(0);
6775   const Type *SrcTy     = LHSCIOp->getType();
6776   const Type *DestTy    = LHSCI->getType();
6777   Value *RHSCIOp;
6778
6779   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6780   // integer type is the same size as the pointer type.
6781   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6782       getTargetData().getPointerSizeInBits() == 
6783          cast<IntegerType>(DestTy)->getBitWidth()) {
6784     Value *RHSOp = 0;
6785     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6786       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6787     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6788       RHSOp = RHSC->getOperand(0);
6789       // If the pointer types don't match, insert a bitcast.
6790       if (LHSCIOp->getType() != RHSOp->getType())
6791         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6792     }
6793
6794     if (RHSOp)
6795       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6796   }
6797   
6798   // The code below only handles extension cast instructions, so far.
6799   // Enforce this.
6800   if (LHSCI->getOpcode() != Instruction::ZExt &&
6801       LHSCI->getOpcode() != Instruction::SExt)
6802     return 0;
6803
6804   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6805   bool isSignedCmp = ICI.isSignedPredicate();
6806
6807   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6808     // Not an extension from the same type?
6809     RHSCIOp = CI->getOperand(0);
6810     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6811       return 0;
6812     
6813     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6814     // and the other is a zext), then we can't handle this.
6815     if (CI->getOpcode() != LHSCI->getOpcode())
6816       return 0;
6817
6818     // Deal with equality cases early.
6819     if (ICI.isEquality())
6820       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6821
6822     // A signed comparison of sign extended values simplifies into a
6823     // signed comparison.
6824     if (isSignedCmp && isSignedExt)
6825       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6826
6827     // The other three cases all fold into an unsigned comparison.
6828     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6829   }
6830
6831   // If we aren't dealing with a constant on the RHS, exit early
6832   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6833   if (!CI)
6834     return 0;
6835
6836   // Compute the constant that would happen if we truncated to SrcTy then
6837   // reextended to DestTy.
6838   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6839   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6840
6841   // If the re-extended constant didn't change...
6842   if (Res2 == CI) {
6843     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6844     // For example, we might have:
6845     //    %A = sext short %X to uint
6846     //    %B = icmp ugt uint %A, 1330
6847     // It is incorrect to transform this into 
6848     //    %B = icmp ugt short %X, 1330 
6849     // because %A may have negative value. 
6850     //
6851     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6852     // OR operation is EQ/NE.
6853     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6854       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6855     else
6856       return 0;
6857   }
6858
6859   // The re-extended constant changed so the constant cannot be represented 
6860   // in the shorter type. Consequently, we cannot emit a simple comparison.
6861
6862   // First, handle some easy cases. We know the result cannot be equal at this
6863   // point so handle the ICI.isEquality() cases
6864   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6865     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6866   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6867     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6868
6869   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6870   // should have been folded away previously and not enter in here.
6871   Value *Result;
6872   if (isSignedCmp) {
6873     // We're performing a signed comparison.
6874     if (cast<ConstantInt>(CI)->getValue().isNegative())
6875       Result = ConstantInt::getFalse();          // X < (small) --> false
6876     else
6877       Result = ConstantInt::getTrue();           // X < (large) --> true
6878   } else {
6879     // We're performing an unsigned comparison.
6880     if (isSignedExt) {
6881       // We're performing an unsigned comp with a sign extended value.
6882       // This is true if the input is >= 0. [aka >s -1]
6883       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6884       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6885                                    NegOne, ICI.getName()), ICI);
6886     } else {
6887       // Unsigned extend & unsigned compare -> always true.
6888       Result = ConstantInt::getTrue();
6889     }
6890   }
6891
6892   // Finally, return the value computed.
6893   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6894       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6895     return ReplaceInstUsesWith(ICI, Result);
6896   } else {
6897     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6898             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6899            "ICmp should be folded!");
6900     if (Constant *CI = dyn_cast<Constant>(Result))
6901       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6902     else
6903       return BinaryOperator::CreateNot(Result);
6904   }
6905 }
6906
6907 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6908   return commonShiftTransforms(I);
6909 }
6910
6911 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6912   return commonShiftTransforms(I);
6913 }
6914
6915 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6916   if (Instruction *R = commonShiftTransforms(I))
6917     return R;
6918   
6919   Value *Op0 = I.getOperand(0);
6920   
6921   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6922   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6923     if (CSI->isAllOnesValue())
6924       return ReplaceInstUsesWith(I, CSI);
6925   
6926   // See if we can turn a signed shr into an unsigned shr.
6927   if (MaskedValueIsZero(Op0, 
6928                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6929     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6930   
6931   return 0;
6932 }
6933
6934 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6935   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6936   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6937
6938   // shl X, 0 == X and shr X, 0 == X
6939   // shl 0, X == 0 and shr 0, X == 0
6940   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6941       Op0 == Constant::getNullValue(Op0->getType()))
6942     return ReplaceInstUsesWith(I, Op0);
6943   
6944   if (isa<UndefValue>(Op0)) {            
6945     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6946       return ReplaceInstUsesWith(I, Op0);
6947     else                                    // undef << X -> 0, undef >>u X -> 0
6948       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6949   }
6950   if (isa<UndefValue>(Op1)) {
6951     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6952       return ReplaceInstUsesWith(I, Op0);          
6953     else                                     // X << undef, X >>u undef -> 0
6954       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6955   }
6956
6957   // Try to fold constant and into select arguments.
6958   if (isa<Constant>(Op0))
6959     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6960       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6961         return R;
6962
6963   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6964     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6965       return Res;
6966   return 0;
6967 }
6968
6969 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6970                                                BinaryOperator &I) {
6971   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6972
6973   // See if we can simplify any instructions used by the instruction whose sole 
6974   // purpose is to compute bits we don't care about.
6975   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6976   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6977   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6978                            KnownZero, KnownOne))
6979     return &I;
6980   
6981   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6982   // of a signed value.
6983   //
6984   if (Op1->uge(TypeBits)) {
6985     if (I.getOpcode() != Instruction::AShr)
6986       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6987     else {
6988       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6989       return &I;
6990     }
6991   }
6992   
6993   // ((X*C1) << C2) == (X * (C1 << C2))
6994   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6995     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6996       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6997         return BinaryOperator::CreateMul(BO->getOperand(0),
6998                                          ConstantExpr::getShl(BOOp, Op1));
6999   
7000   // Try to fold constant and into select arguments.
7001   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7002     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7003       return R;
7004   if (isa<PHINode>(Op0))
7005     if (Instruction *NV = FoldOpIntoPhi(I))
7006       return NV;
7007   
7008   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7009   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7010     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7011     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7012     // place.  Don't try to do this transformation in this case.  Also, we
7013     // require that the input operand is a shift-by-constant so that we have
7014     // confidence that the shifts will get folded together.  We could do this
7015     // xform in more cases, but it is unlikely to be profitable.
7016     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7017         isa<ConstantInt>(TrOp->getOperand(1))) {
7018       // Okay, we'll do this xform.  Make the shift of shift.
7019       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7020       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7021                                                 I.getName());
7022       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7023
7024       // For logical shifts, the truncation has the effect of making the high
7025       // part of the register be zeros.  Emulate this by inserting an AND to
7026       // clear the top bits as needed.  This 'and' will usually be zapped by
7027       // other xforms later if dead.
7028       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7029       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7030       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7031       
7032       // The mask we constructed says what the trunc would do if occurring
7033       // between the shifts.  We want to know the effect *after* the second
7034       // shift.  We know that it is a logical shift by a constant, so adjust the
7035       // mask as appropriate.
7036       if (I.getOpcode() == Instruction::Shl)
7037         MaskV <<= Op1->getZExtValue();
7038       else {
7039         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7040         MaskV = MaskV.lshr(Op1->getZExtValue());
7041       }
7042
7043       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7044                                                    TI->getName());
7045       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7046
7047       // Return the value truncated to the interesting size.
7048       return new TruncInst(And, I.getType());
7049     }
7050   }
7051   
7052   if (Op0->hasOneUse()) {
7053     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7054       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7055       Value *V1, *V2;
7056       ConstantInt *CC;
7057       switch (Op0BO->getOpcode()) {
7058         default: break;
7059         case Instruction::Add:
7060         case Instruction::And:
7061         case Instruction::Or:
7062         case Instruction::Xor: {
7063           // These operators commute.
7064           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7065           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7066               match(Op0BO->getOperand(1),
7067                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7068             Instruction *YS = BinaryOperator::CreateShl(
7069                                             Op0BO->getOperand(0), Op1,
7070                                             Op0BO->getName());
7071             InsertNewInstBefore(YS, I); // (Y << C)
7072             Instruction *X = 
7073               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7074                                      Op0BO->getOperand(1)->getName());
7075             InsertNewInstBefore(X, I);  // (X + (Y << C))
7076             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7077             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7078                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7079           }
7080           
7081           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7082           Value *Op0BOOp1 = Op0BO->getOperand(1);
7083           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7084               match(Op0BOOp1, 
7085                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
7086               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7087               V2 == Op1) {
7088             Instruction *YS = BinaryOperator::CreateShl(
7089                                                      Op0BO->getOperand(0), Op1,
7090                                                      Op0BO->getName());
7091             InsertNewInstBefore(YS, I); // (Y << C)
7092             Instruction *XM =
7093               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7094                                         V1->getName()+".mask");
7095             InsertNewInstBefore(XM, I); // X & (CC << C)
7096             
7097             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7098           }
7099         }
7100           
7101         // FALL THROUGH.
7102         case Instruction::Sub: {
7103           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7104           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7105               match(Op0BO->getOperand(0),
7106                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7107             Instruction *YS = BinaryOperator::CreateShl(
7108                                                      Op0BO->getOperand(1), Op1,
7109                                                      Op0BO->getName());
7110             InsertNewInstBefore(YS, I); // (Y << C)
7111             Instruction *X =
7112               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7113                                      Op0BO->getOperand(0)->getName());
7114             InsertNewInstBefore(X, I);  // (X + (Y << C))
7115             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7116             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7117                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7118           }
7119           
7120           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7121           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7122               match(Op0BO->getOperand(0),
7123                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7124                           m_ConstantInt(CC))) && V2 == Op1 &&
7125               cast<BinaryOperator>(Op0BO->getOperand(0))
7126                   ->getOperand(0)->hasOneUse()) {
7127             Instruction *YS = BinaryOperator::CreateShl(
7128                                                      Op0BO->getOperand(1), Op1,
7129                                                      Op0BO->getName());
7130             InsertNewInstBefore(YS, I); // (Y << C)
7131             Instruction *XM =
7132               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7133                                         V1->getName()+".mask");
7134             InsertNewInstBefore(XM, I); // X & (CC << C)
7135             
7136             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7137           }
7138           
7139           break;
7140         }
7141       }
7142       
7143       
7144       // If the operand is an bitwise operator with a constant RHS, and the
7145       // shift is the only use, we can pull it out of the shift.
7146       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7147         bool isValid = true;     // Valid only for And, Or, Xor
7148         bool highBitSet = false; // Transform if high bit of constant set?
7149         
7150         switch (Op0BO->getOpcode()) {
7151           default: isValid = false; break;   // Do not perform transform!
7152           case Instruction::Add:
7153             isValid = isLeftShift;
7154             break;
7155           case Instruction::Or:
7156           case Instruction::Xor:
7157             highBitSet = false;
7158             break;
7159           case Instruction::And:
7160             highBitSet = true;
7161             break;
7162         }
7163         
7164         // If this is a signed shift right, and the high bit is modified
7165         // by the logical operation, do not perform the transformation.
7166         // The highBitSet boolean indicates the value of the high bit of
7167         // the constant which would cause it to be modified for this
7168         // operation.
7169         //
7170         if (isValid && I.getOpcode() == Instruction::AShr)
7171           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7172         
7173         if (isValid) {
7174           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7175           
7176           Instruction *NewShift =
7177             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7178           InsertNewInstBefore(NewShift, I);
7179           NewShift->takeName(Op0BO);
7180           
7181           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7182                                         NewRHS);
7183         }
7184       }
7185     }
7186   }
7187   
7188   // Find out if this is a shift of a shift by a constant.
7189   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7190   if (ShiftOp && !ShiftOp->isShift())
7191     ShiftOp = 0;
7192   
7193   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7194     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7195     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7196     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7197     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7198     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7199     Value *X = ShiftOp->getOperand(0);
7200     
7201     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7202     if (AmtSum > TypeBits)
7203       AmtSum = TypeBits;
7204     
7205     const IntegerType *Ty = cast<IntegerType>(I.getType());
7206     
7207     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7208     if (I.getOpcode() == ShiftOp->getOpcode()) {
7209       return BinaryOperator::Create(I.getOpcode(), X,
7210                                     ConstantInt::get(Ty, AmtSum));
7211     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7212                I.getOpcode() == Instruction::AShr) {
7213       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7214       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7215     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7216                I.getOpcode() == Instruction::LShr) {
7217       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7218       Instruction *Shift =
7219         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7220       InsertNewInstBefore(Shift, I);
7221
7222       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7223       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7224     }
7225     
7226     // Okay, if we get here, one shift must be left, and the other shift must be
7227     // right.  See if the amounts are equal.
7228     if (ShiftAmt1 == ShiftAmt2) {
7229       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7230       if (I.getOpcode() == Instruction::Shl) {
7231         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7232         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7233       }
7234       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7235       if (I.getOpcode() == Instruction::LShr) {
7236         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7237         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7238       }
7239       // We can simplify ((X << C) >>s C) into a trunc + sext.
7240       // NOTE: we could do this for any C, but that would make 'unusual' integer
7241       // types.  For now, just stick to ones well-supported by the code
7242       // generators.
7243       const Type *SExtType = 0;
7244       switch (Ty->getBitWidth() - ShiftAmt1) {
7245       case 1  :
7246       case 8  :
7247       case 16 :
7248       case 32 :
7249       case 64 :
7250       case 128:
7251         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7252         break;
7253       default: break;
7254       }
7255       if (SExtType) {
7256         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7257         InsertNewInstBefore(NewTrunc, I);
7258         return new SExtInst(NewTrunc, Ty);
7259       }
7260       // Otherwise, we can't handle it yet.
7261     } else if (ShiftAmt1 < ShiftAmt2) {
7262       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7263       
7264       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7265       if (I.getOpcode() == Instruction::Shl) {
7266         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7267                ShiftOp->getOpcode() == Instruction::AShr);
7268         Instruction *Shift =
7269           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7270         InsertNewInstBefore(Shift, I);
7271         
7272         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7273         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7274       }
7275       
7276       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7277       if (I.getOpcode() == Instruction::LShr) {
7278         assert(ShiftOp->getOpcode() == Instruction::Shl);
7279         Instruction *Shift =
7280           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7281         InsertNewInstBefore(Shift, I);
7282         
7283         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7284         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7285       }
7286       
7287       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7288     } else {
7289       assert(ShiftAmt2 < ShiftAmt1);
7290       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7291
7292       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7293       if (I.getOpcode() == Instruction::Shl) {
7294         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7295                ShiftOp->getOpcode() == Instruction::AShr);
7296         Instruction *Shift =
7297           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7298                                  ConstantInt::get(Ty, ShiftDiff));
7299         InsertNewInstBefore(Shift, I);
7300         
7301         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7302         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7303       }
7304       
7305       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7306       if (I.getOpcode() == Instruction::LShr) {
7307         assert(ShiftOp->getOpcode() == Instruction::Shl);
7308         Instruction *Shift =
7309           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7310         InsertNewInstBefore(Shift, I);
7311         
7312         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7313         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7314       }
7315       
7316       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7317     }
7318   }
7319   return 0;
7320 }
7321
7322
7323 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7324 /// expression.  If so, decompose it, returning some value X, such that Val is
7325 /// X*Scale+Offset.
7326 ///
7327 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7328                                         int &Offset) {
7329   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7330   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7331     Offset = CI->getZExtValue();
7332     Scale  = 0;
7333     return ConstantInt::get(Type::Int32Ty, 0);
7334   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7335     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7336       if (I->getOpcode() == Instruction::Shl) {
7337         // This is a value scaled by '1 << the shift amt'.
7338         Scale = 1U << RHS->getZExtValue();
7339         Offset = 0;
7340         return I->getOperand(0);
7341       } else if (I->getOpcode() == Instruction::Mul) {
7342         // This value is scaled by 'RHS'.
7343         Scale = RHS->getZExtValue();
7344         Offset = 0;
7345         return I->getOperand(0);
7346       } else if (I->getOpcode() == Instruction::Add) {
7347         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7348         // where C1 is divisible by C2.
7349         unsigned SubScale;
7350         Value *SubVal = 
7351           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7352         Offset += RHS->getZExtValue();
7353         Scale = SubScale;
7354         return SubVal;
7355       }
7356     }
7357   }
7358
7359   // Otherwise, we can't look past this.
7360   Scale = 1;
7361   Offset = 0;
7362   return Val;
7363 }
7364
7365
7366 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7367 /// try to eliminate the cast by moving the type information into the alloc.
7368 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7369                                                    AllocationInst &AI) {
7370   const PointerType *PTy = cast<PointerType>(CI.getType());
7371   
7372   // Remove any uses of AI that are dead.
7373   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7374   
7375   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7376     Instruction *User = cast<Instruction>(*UI++);
7377     if (isInstructionTriviallyDead(User)) {
7378       while (UI != E && *UI == User)
7379         ++UI; // If this instruction uses AI more than once, don't break UI.
7380       
7381       ++NumDeadInst;
7382       DOUT << "IC: DCE: " << *User;
7383       EraseInstFromFunction(*User);
7384     }
7385   }
7386   
7387   // Get the type really allocated and the type casted to.
7388   const Type *AllocElTy = AI.getAllocatedType();
7389   const Type *CastElTy = PTy->getElementType();
7390   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7391
7392   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7393   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7394   if (CastElTyAlign < AllocElTyAlign) return 0;
7395
7396   // If the allocation has multiple uses, only promote it if we are strictly
7397   // increasing the alignment of the resultant allocation.  If we keep it the
7398   // same, we open the door to infinite loops of various kinds.
7399   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7400
7401   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7402   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7403   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7404
7405   // See if we can satisfy the modulus by pulling a scale out of the array
7406   // size argument.
7407   unsigned ArraySizeScale;
7408   int ArrayOffset;
7409   Value *NumElements = // See if the array size is a decomposable linear expr.
7410     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7411  
7412   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7413   // do the xform.
7414   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7415       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7416
7417   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7418   Value *Amt = 0;
7419   if (Scale == 1) {
7420     Amt = NumElements;
7421   } else {
7422     // If the allocation size is constant, form a constant mul expression
7423     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7424     if (isa<ConstantInt>(NumElements))
7425       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7426     // otherwise multiply the amount and the number of elements
7427     else if (Scale != 1) {
7428       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7429       Amt = InsertNewInstBefore(Tmp, AI);
7430     }
7431   }
7432   
7433   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7434     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7435     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7436     Amt = InsertNewInstBefore(Tmp, AI);
7437   }
7438   
7439   AllocationInst *New;
7440   if (isa<MallocInst>(AI))
7441     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7442   else
7443     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7444   InsertNewInstBefore(New, AI);
7445   New->takeName(&AI);
7446   
7447   // If the allocation has multiple uses, insert a cast and change all things
7448   // that used it to use the new cast.  This will also hack on CI, but it will
7449   // die soon.
7450   if (!AI.hasOneUse()) {
7451     AddUsesToWorkList(AI);
7452     // New is the allocation instruction, pointer typed. AI is the original
7453     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7454     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7455     InsertNewInstBefore(NewCast, AI);
7456     AI.replaceAllUsesWith(NewCast);
7457   }
7458   return ReplaceInstUsesWith(CI, New);
7459 }
7460
7461 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7462 /// and return it as type Ty without inserting any new casts and without
7463 /// changing the computed value.  This is used by code that tries to decide
7464 /// whether promoting or shrinking integer operations to wider or smaller types
7465 /// will allow us to eliminate a truncate or extend.
7466 ///
7467 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7468 /// extension operation if Ty is larger.
7469 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7470                                               unsigned CastOpc,
7471                                               int &NumCastsRemoved) {
7472   // We can always evaluate constants in another type.
7473   if (isa<ConstantInt>(V))
7474     return true;
7475   
7476   Instruction *I = dyn_cast<Instruction>(V);
7477   if (!I) return false;
7478   
7479   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7480   
7481   // If this is an extension or truncate, we can often eliminate it.
7482   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7483     // If this is a cast from the destination type, we can trivially eliminate
7484     // it, and this will remove a cast overall.
7485     if (I->getOperand(0)->getType() == Ty) {
7486       // If the first operand is itself a cast, and is eliminable, do not count
7487       // this as an eliminable cast.  We would prefer to eliminate those two
7488       // casts first.
7489       if (!isa<CastInst>(I->getOperand(0)))
7490         ++NumCastsRemoved;
7491       return true;
7492     }
7493   }
7494
7495   // We can't extend or shrink something that has multiple uses: doing so would
7496   // require duplicating the instruction in general, which isn't profitable.
7497   if (!I->hasOneUse()) return false;
7498
7499   switch (I->getOpcode()) {
7500   case Instruction::Add:
7501   case Instruction::Sub:
7502   case Instruction::And:
7503   case Instruction::Or:
7504   case Instruction::Xor:
7505     // These operators can all arbitrarily be extended or truncated.
7506     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7507                                       NumCastsRemoved) &&
7508            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7509                                       NumCastsRemoved);
7510
7511   case Instruction::Mul:
7512     // A multiply can be truncated by truncating its operands.
7513     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
7514            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7515                                       NumCastsRemoved) &&
7516            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7517                                       NumCastsRemoved);
7518
7519   case Instruction::Shl:
7520     // If we are truncating the result of this SHL, and if it's a shift of a
7521     // constant amount, we can always perform a SHL in a smaller type.
7522     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7523       uint32_t BitWidth = Ty->getBitWidth();
7524       if (BitWidth < OrigTy->getBitWidth() && 
7525           CI->getLimitedValue(BitWidth) < BitWidth)
7526         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7527                                           NumCastsRemoved);
7528     }
7529     break;
7530   case Instruction::LShr:
7531     // If this is a truncate of a logical shr, we can truncate it to a smaller
7532     // lshr iff we know that the bits we would otherwise be shifting in are
7533     // already zeros.
7534     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7535       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7536       uint32_t BitWidth = Ty->getBitWidth();
7537       if (BitWidth < OrigBitWidth &&
7538           MaskedValueIsZero(I->getOperand(0),
7539             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7540           CI->getLimitedValue(BitWidth) < BitWidth) {
7541         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7542                                           NumCastsRemoved);
7543       }
7544     }
7545     break;
7546   case Instruction::ZExt:
7547   case Instruction::SExt:
7548   case Instruction::Trunc:
7549     // If this is the same kind of case as our original (e.g. zext+zext), we
7550     // can safely replace it.  Note that replacing it does not reduce the number
7551     // of casts in the input.
7552     if (I->getOpcode() == CastOpc)
7553       return true;
7554     
7555     break;
7556   default:
7557     // TODO: Can handle more cases here.
7558     break;
7559   }
7560   
7561   return false;
7562 }
7563
7564 /// EvaluateInDifferentType - Given an expression that 
7565 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7566 /// evaluate the expression.
7567 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7568                                              bool isSigned) {
7569   if (Constant *C = dyn_cast<Constant>(V))
7570     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7571
7572   // Otherwise, it must be an instruction.
7573   Instruction *I = cast<Instruction>(V);
7574   Instruction *Res = 0;
7575   switch (I->getOpcode()) {
7576   case Instruction::Add:
7577   case Instruction::Sub:
7578   case Instruction::Mul:
7579   case Instruction::And:
7580   case Instruction::Or:
7581   case Instruction::Xor:
7582   case Instruction::AShr:
7583   case Instruction::LShr:
7584   case Instruction::Shl: {
7585     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7586     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7587     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7588                                  LHS, RHS, I->getName());
7589     break;
7590   }    
7591   case Instruction::Trunc:
7592   case Instruction::ZExt:
7593   case Instruction::SExt:
7594     // If the source type of the cast is the type we're trying for then we can
7595     // just return the source.  There's no need to insert it because it is not
7596     // new.
7597     if (I->getOperand(0)->getType() == Ty)
7598       return I->getOperand(0);
7599     
7600     // Otherwise, must be the same type of case, so just reinsert a new one.
7601     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7602                            Ty, I->getName());
7603     break;
7604   default: 
7605     // TODO: Can handle more cases here.
7606     assert(0 && "Unreachable!");
7607     break;
7608   }
7609   
7610   return InsertNewInstBefore(Res, *I);
7611 }
7612
7613 /// @brief Implement the transforms common to all CastInst visitors.
7614 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7615   Value *Src = CI.getOperand(0);
7616
7617   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7618   // eliminate it now.
7619   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7620     if (Instruction::CastOps opc = 
7621         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7622       // The first cast (CSrc) is eliminable so we need to fix up or replace
7623       // the second cast (CI). CSrc will then have a good chance of being dead.
7624       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7625     }
7626   }
7627
7628   // If we are casting a select then fold the cast into the select
7629   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7630     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7631       return NV;
7632
7633   // If we are casting a PHI then fold the cast into the PHI
7634   if (isa<PHINode>(Src))
7635     if (Instruction *NV = FoldOpIntoPhi(CI))
7636       return NV;
7637   
7638   return 0;
7639 }
7640
7641 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7642 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7643   Value *Src = CI.getOperand(0);
7644   
7645   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7646     // If casting the result of a getelementptr instruction with no offset, turn
7647     // this into a cast of the original pointer!
7648     if (GEP->hasAllZeroIndices()) {
7649       // Changing the cast operand is usually not a good idea but it is safe
7650       // here because the pointer operand is being replaced with another 
7651       // pointer operand so the opcode doesn't need to change.
7652       AddToWorkList(GEP);
7653       CI.setOperand(0, GEP->getOperand(0));
7654       return &CI;
7655     }
7656     
7657     // If the GEP has a single use, and the base pointer is a bitcast, and the
7658     // GEP computes a constant offset, see if we can convert these three
7659     // instructions into fewer.  This typically happens with unions and other
7660     // non-type-safe code.
7661     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7662       if (GEP->hasAllConstantIndices()) {
7663         // We are guaranteed to get a constant from EmitGEPOffset.
7664         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7665         int64_t Offset = OffsetV->getSExtValue();
7666         
7667         // Get the base pointer input of the bitcast, and the type it points to.
7668         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7669         const Type *GEPIdxTy =
7670           cast<PointerType>(OrigBase->getType())->getElementType();
7671         if (GEPIdxTy->isSized()) {
7672           SmallVector<Value*, 8> NewIndices;
7673           
7674           // Start with the index over the outer type.  Note that the type size
7675           // might be zero (even if the offset isn't zero) if the indexed type
7676           // is something like [0 x {int, int}]
7677           const Type *IntPtrTy = TD->getIntPtrType();
7678           int64_t FirstIdx = 0;
7679           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7680             FirstIdx = Offset/TySize;
7681             Offset %= TySize;
7682           
7683             // Handle silly modulus not returning values values [0..TySize).
7684             if (Offset < 0) {
7685               --FirstIdx;
7686               Offset += TySize;
7687               assert(Offset >= 0);
7688             }
7689             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7690           }
7691           
7692           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7693
7694           // Index into the types.  If we fail, set OrigBase to null.
7695           while (Offset) {
7696             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7697               const StructLayout *SL = TD->getStructLayout(STy);
7698               if (Offset < (int64_t)SL->getSizeInBytes()) {
7699                 unsigned Elt = SL->getElementContainingOffset(Offset);
7700                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7701               
7702                 Offset -= SL->getElementOffset(Elt);
7703                 GEPIdxTy = STy->getElementType(Elt);
7704               } else {
7705                 // Otherwise, we can't index into this, bail out.
7706                 Offset = 0;
7707                 OrigBase = 0;
7708               }
7709             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7710               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7711               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7712                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7713                 Offset %= EltSize;
7714               } else {
7715                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7716               }
7717               GEPIdxTy = STy->getElementType();
7718             } else {
7719               // Otherwise, we can't index into this, bail out.
7720               Offset = 0;
7721               OrigBase = 0;
7722             }
7723           }
7724           if (OrigBase) {
7725             // If we were able to index down into an element, create the GEP
7726             // and bitcast the result.  This eliminates one bitcast, potentially
7727             // two.
7728             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7729                                                           NewIndices.begin(),
7730                                                           NewIndices.end(), "");
7731             InsertNewInstBefore(NGEP, CI);
7732             NGEP->takeName(GEP);
7733             
7734             if (isa<BitCastInst>(CI))
7735               return new BitCastInst(NGEP, CI.getType());
7736             assert(isa<PtrToIntInst>(CI));
7737             return new PtrToIntInst(NGEP, CI.getType());
7738           }
7739         }
7740       }      
7741     }
7742   }
7743     
7744   return commonCastTransforms(CI);
7745 }
7746
7747
7748
7749 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7750 /// integer types. This function implements the common transforms for all those
7751 /// cases.
7752 /// @brief Implement the transforms common to CastInst with integer operands
7753 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7754   if (Instruction *Result = commonCastTransforms(CI))
7755     return Result;
7756
7757   Value *Src = CI.getOperand(0);
7758   const Type *SrcTy = Src->getType();
7759   const Type *DestTy = CI.getType();
7760   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7761   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7762
7763   // See if we can simplify any instructions used by the LHS whose sole 
7764   // purpose is to compute bits we don't care about.
7765   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7766   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7767                            KnownZero, KnownOne))
7768     return &CI;
7769
7770   // If the source isn't an instruction or has more than one use then we
7771   // can't do anything more. 
7772   Instruction *SrcI = dyn_cast<Instruction>(Src);
7773   if (!SrcI || !Src->hasOneUse())
7774     return 0;
7775
7776   // Attempt to propagate the cast into the instruction for int->int casts.
7777   int NumCastsRemoved = 0;
7778   if (!isa<BitCastInst>(CI) &&
7779       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7780                                  CI.getOpcode(), NumCastsRemoved)) {
7781     // If this cast is a truncate, evaluting in a different type always
7782     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7783     // we need to do an AND to maintain the clear top-part of the computation,
7784     // so we require that the input have eliminated at least one cast.  If this
7785     // is a sign extension, we insert two new casts (to do the extension) so we
7786     // require that two casts have been eliminated.
7787     bool DoXForm;
7788     switch (CI.getOpcode()) {
7789     default:
7790       // All the others use floating point so we shouldn't actually 
7791       // get here because of the check above.
7792       assert(0 && "Unknown cast type");
7793     case Instruction::Trunc:
7794       DoXForm = true;
7795       break;
7796     case Instruction::ZExt:
7797       DoXForm = NumCastsRemoved >= 1;
7798       break;
7799     case Instruction::SExt:
7800       DoXForm = NumCastsRemoved >= 2;
7801       break;
7802     }
7803     
7804     if (DoXForm) {
7805       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7806                                            CI.getOpcode() == Instruction::SExt);
7807       assert(Res->getType() == DestTy);
7808       switch (CI.getOpcode()) {
7809       default: assert(0 && "Unknown cast type!");
7810       case Instruction::Trunc:
7811       case Instruction::BitCast:
7812         // Just replace this cast with the result.
7813         return ReplaceInstUsesWith(CI, Res);
7814       case Instruction::ZExt: {
7815         // We need to emit an AND to clear the high bits.
7816         assert(SrcBitSize < DestBitSize && "Not a zext?");
7817         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7818                                                             SrcBitSize));
7819         return BinaryOperator::CreateAnd(Res, C);
7820       }
7821       case Instruction::SExt:
7822         // We need to emit a cast to truncate, then a cast to sext.
7823         return CastInst::Create(Instruction::SExt,
7824             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7825                              CI), DestTy);
7826       }
7827     }
7828   }
7829   
7830   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7831   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7832
7833   switch (SrcI->getOpcode()) {
7834   case Instruction::Add:
7835   case Instruction::Mul:
7836   case Instruction::And:
7837   case Instruction::Or:
7838   case Instruction::Xor:
7839     // If we are discarding information, rewrite.
7840     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7841       // Don't insert two casts if they cannot be eliminated.  We allow 
7842       // two casts to be inserted if the sizes are the same.  This could 
7843       // only be converting signedness, which is a noop.
7844       if (DestBitSize == SrcBitSize || 
7845           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7846           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7847         Instruction::CastOps opcode = CI.getOpcode();
7848         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7849         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7850         return BinaryOperator::Create(
7851             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7852       }
7853     }
7854
7855     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7856     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7857         SrcI->getOpcode() == Instruction::Xor &&
7858         Op1 == ConstantInt::getTrue() &&
7859         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7860       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7861       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7862     }
7863     break;
7864   case Instruction::SDiv:
7865   case Instruction::UDiv:
7866   case Instruction::SRem:
7867   case Instruction::URem:
7868     // If we are just changing the sign, rewrite.
7869     if (DestBitSize == SrcBitSize) {
7870       // Don't insert two casts if they cannot be eliminated.  We allow 
7871       // two casts to be inserted if the sizes are the same.  This could 
7872       // only be converting signedness, which is a noop.
7873       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7874           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7875         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7876                                               Op0, DestTy, SrcI);
7877         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7878                                               Op1, DestTy, SrcI);
7879         return BinaryOperator::Create(
7880           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7881       }
7882     }
7883     break;
7884
7885   case Instruction::Shl:
7886     // Allow changing the sign of the source operand.  Do not allow 
7887     // changing the size of the shift, UNLESS the shift amount is a 
7888     // constant.  We must not change variable sized shifts to a smaller 
7889     // size, because it is undefined to shift more bits out than exist 
7890     // in the value.
7891     if (DestBitSize == SrcBitSize ||
7892         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7893       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7894           Instruction::BitCast : Instruction::Trunc);
7895       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7896       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7897       return BinaryOperator::CreateShl(Op0c, Op1c);
7898     }
7899     break;
7900   case Instruction::AShr:
7901     // If this is a signed shr, and if all bits shifted in are about to be
7902     // truncated off, turn it into an unsigned shr to allow greater
7903     // simplifications.
7904     if (DestBitSize < SrcBitSize &&
7905         isa<ConstantInt>(Op1)) {
7906       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7907       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7908         // Insert the new logical shift right.
7909         return BinaryOperator::CreateLShr(Op0, Op1);
7910       }
7911     }
7912     break;
7913   }
7914   return 0;
7915 }
7916
7917 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7918   if (Instruction *Result = commonIntCastTransforms(CI))
7919     return Result;
7920   
7921   Value *Src = CI.getOperand(0);
7922   const Type *Ty = CI.getType();
7923   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7924   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7925   
7926   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7927     switch (SrcI->getOpcode()) {
7928     default: break;
7929     case Instruction::LShr:
7930       // We can shrink lshr to something smaller if we know the bits shifted in
7931       // are already zeros.
7932       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7933         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7934         
7935         // Get a mask for the bits shifting in.
7936         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7937         Value* SrcIOp0 = SrcI->getOperand(0);
7938         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7939           if (ShAmt >= DestBitWidth)        // All zeros.
7940             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7941
7942           // Okay, we can shrink this.  Truncate the input, then return a new
7943           // shift.
7944           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7945           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7946                                        Ty, CI);
7947           return BinaryOperator::CreateLShr(V1, V2);
7948         }
7949       } else {     // This is a variable shr.
7950         
7951         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7952         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7953         // loop-invariant and CSE'd.
7954         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7955           Value *One = ConstantInt::get(SrcI->getType(), 1);
7956
7957           Value *V = InsertNewInstBefore(
7958               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7959                                      "tmp"), CI);
7960           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7961                                                             SrcI->getOperand(0),
7962                                                             "tmp"), CI);
7963           Value *Zero = Constant::getNullValue(V->getType());
7964           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7965         }
7966       }
7967       break;
7968     }
7969   }
7970   
7971   return 0;
7972 }
7973
7974 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7975 /// in order to eliminate the icmp.
7976 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7977                                              bool DoXform) {
7978   // If we are just checking for a icmp eq of a single bit and zext'ing it
7979   // to an integer, then shift the bit to the appropriate place and then
7980   // cast to integer to avoid the comparison.
7981   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7982     const APInt &Op1CV = Op1C->getValue();
7983       
7984     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7985     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7986     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7987         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7988       if (!DoXform) return ICI;
7989
7990       Value *In = ICI->getOperand(0);
7991       Value *Sh = ConstantInt::get(In->getType(),
7992                                    In->getType()->getPrimitiveSizeInBits()-1);
7993       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7994                                                         In->getName()+".lobit"),
7995                                CI);
7996       if (In->getType() != CI.getType())
7997         In = CastInst::CreateIntegerCast(In, CI.getType(),
7998                                          false/*ZExt*/, "tmp", &CI);
7999
8000       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8001         Constant *One = ConstantInt::get(In->getType(), 1);
8002         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8003                                                          In->getName()+".not"),
8004                                  CI);
8005       }
8006
8007       return ReplaceInstUsesWith(CI, In);
8008     }
8009       
8010       
8011       
8012     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8013     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8014     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8015     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8016     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8017     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8018     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8019     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8020     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8021         // This only works for EQ and NE
8022         ICI->isEquality()) {
8023       // If Op1C some other power of two, convert:
8024       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8025       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8026       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8027       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8028         
8029       APInt KnownZeroMask(~KnownZero);
8030       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8031         if (!DoXform) return ICI;
8032
8033         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8034         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8035           // (X&4) == 2 --> false
8036           // (X&4) != 2 --> true
8037           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8038           Res = ConstantExpr::getZExt(Res, CI.getType());
8039           return ReplaceInstUsesWith(CI, Res);
8040         }
8041           
8042         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8043         Value *In = ICI->getOperand(0);
8044         if (ShiftAmt) {
8045           // Perform a logical shr by shiftamt.
8046           // Insert the shift to put the result in the low bit.
8047           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8048                                   ConstantInt::get(In->getType(), ShiftAmt),
8049                                                    In->getName()+".lobit"), CI);
8050         }
8051           
8052         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8053           Constant *One = ConstantInt::get(In->getType(), 1);
8054           In = BinaryOperator::CreateXor(In, One, "tmp");
8055           InsertNewInstBefore(cast<Instruction>(In), CI);
8056         }
8057           
8058         if (CI.getType() == In->getType())
8059           return ReplaceInstUsesWith(CI, In);
8060         else
8061           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8062       }
8063     }
8064   }
8065
8066   return 0;
8067 }
8068
8069 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8070   // If one of the common conversion will work ..
8071   if (Instruction *Result = commonIntCastTransforms(CI))
8072     return Result;
8073
8074   Value *Src = CI.getOperand(0);
8075
8076   // If this is a cast of a cast
8077   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8078     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8079     // types and if the sizes are just right we can convert this into a logical
8080     // 'and' which will be much cheaper than the pair of casts.
8081     if (isa<TruncInst>(CSrc)) {
8082       // Get the sizes of the types involved
8083       Value *A = CSrc->getOperand(0);
8084       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8085       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8086       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8087       // If we're actually extending zero bits and the trunc is a no-op
8088       if (MidSize < DstSize && SrcSize == DstSize) {
8089         // Replace both of the casts with an And of the type mask.
8090         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8091         Constant *AndConst = ConstantInt::get(AndValue);
8092         Instruction *And = 
8093           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8094         // Unfortunately, if the type changed, we need to cast it back.
8095         if (And->getType() != CI.getType()) {
8096           And->setName(CSrc->getName()+".mask");
8097           InsertNewInstBefore(And, CI);
8098           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8099         }
8100         return And;
8101       }
8102     }
8103   }
8104
8105   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8106     return transformZExtICmp(ICI, CI);
8107
8108   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8109   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8110     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8111     // of the (zext icmp) will be transformed.
8112     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8113     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8114     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8115         (transformZExtICmp(LHS, CI, false) ||
8116          transformZExtICmp(RHS, CI, false))) {
8117       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8118       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8119       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8120     }
8121   }
8122
8123   return 0;
8124 }
8125
8126 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8127   if (Instruction *I = commonIntCastTransforms(CI))
8128     return I;
8129   
8130   Value *Src = CI.getOperand(0);
8131   
8132   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
8133   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
8134   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8135     // If we are just checking for a icmp eq of a single bit and zext'ing it
8136     // to an integer, then shift the bit to the appropriate place and then
8137     // cast to integer to avoid the comparison.
8138     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8139       const APInt &Op1CV = Op1C->getValue();
8140       
8141       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8142       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8143       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8144           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8145         Value *In = ICI->getOperand(0);
8146         Value *Sh = ConstantInt::get(In->getType(),
8147                                      In->getType()->getPrimitiveSizeInBits()-1);
8148         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8149                                                         In->getName()+".lobit"),
8150                                  CI);
8151         if (In->getType() != CI.getType())
8152           In = CastInst::CreateIntegerCast(In, CI.getType(),
8153                                            true/*SExt*/, "tmp", &CI);
8154         
8155         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
8156           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8157                                      In->getName()+".not"), CI);
8158         
8159         return ReplaceInstUsesWith(CI, In);
8160       }
8161     }
8162   }
8163
8164   // See if the value being truncated is already sign extended.  If so, just
8165   // eliminate the trunc/sext pair.
8166   if (getOpcode(Src) == Instruction::Trunc) {
8167     Value *Op = cast<User>(Src)->getOperand(0);
8168     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8169     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8170     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8171     unsigned NumSignBits = ComputeNumSignBits(Op);
8172
8173     if (OpBits == DestBits) {
8174       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8175       // bits, it is already ready.
8176       if (NumSignBits > DestBits-MidBits)
8177         return ReplaceInstUsesWith(CI, Op);
8178     } else if (OpBits < DestBits) {
8179       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8180       // bits, just sext from i32.
8181       if (NumSignBits > OpBits-MidBits)
8182         return new SExtInst(Op, CI.getType(), "tmp");
8183     } else {
8184       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8185       // bits, just truncate to i32.
8186       if (NumSignBits > OpBits-MidBits)
8187         return new TruncInst(Op, CI.getType(), "tmp");
8188     }
8189   }
8190       
8191   return 0;
8192 }
8193
8194 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8195 /// in the specified FP type without changing its value.
8196 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8197   APFloat F = CFP->getValueAPF();
8198   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
8199     return ConstantFP::get(F);
8200   return 0;
8201 }
8202
8203 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8204 /// through it until we get the source value.
8205 static Value *LookThroughFPExtensions(Value *V) {
8206   if (Instruction *I = dyn_cast<Instruction>(V))
8207     if (I->getOpcode() == Instruction::FPExt)
8208       return LookThroughFPExtensions(I->getOperand(0));
8209   
8210   // If this value is a constant, return the constant in the smallest FP type
8211   // that can accurately represent it.  This allows us to turn
8212   // (float)((double)X+2.0) into x+2.0f.
8213   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8214     if (CFP->getType() == Type::PPC_FP128Ty)
8215       return V;  // No constant folding of this.
8216     // See if the value can be truncated to float and then reextended.
8217     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8218       return V;
8219     if (CFP->getType() == Type::DoubleTy)
8220       return V;  // Won't shrink.
8221     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8222       return V;
8223     // Don't try to shrink to various long double types.
8224   }
8225   
8226   return V;
8227 }
8228
8229 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8230   if (Instruction *I = commonCastTransforms(CI))
8231     return I;
8232   
8233   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8234   // smaller than the destination type, we can eliminate the truncate by doing
8235   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8236   // many builtins (sqrt, etc).
8237   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8238   if (OpI && OpI->hasOneUse()) {
8239     switch (OpI->getOpcode()) {
8240     default: break;
8241     case Instruction::Add:
8242     case Instruction::Sub:
8243     case Instruction::Mul:
8244     case Instruction::FDiv:
8245     case Instruction::FRem:
8246       const Type *SrcTy = OpI->getType();
8247       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8248       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8249       if (LHSTrunc->getType() != SrcTy && 
8250           RHSTrunc->getType() != SrcTy) {
8251         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8252         // If the source types were both smaller than the destination type of
8253         // the cast, do this xform.
8254         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8255             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8256           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8257                                       CI.getType(), CI);
8258           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8259                                       CI.getType(), CI);
8260           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8261         }
8262       }
8263       break;  
8264     }
8265   }
8266   return 0;
8267 }
8268
8269 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8270   return commonCastTransforms(CI);
8271 }
8272
8273 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8274   // fptoui(uitofp(X)) --> X  if the intermediate type has enough bits in its
8275   // mantissa to accurately represent all values of X.  For example, do not
8276   // do this with i64->float->i64.
8277   if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8278     if (SrcI->getOperand(0)->getType() == FI.getType() &&
8279         (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8280                     SrcI->getType()->getFPMantissaWidth())
8281       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8282
8283   return commonCastTransforms(FI);
8284 }
8285
8286 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8287   // fptosi(sitofp(X)) --> X  if the intermediate type has enough bits in its
8288   // mantissa to accurately represent all values of X.  For example, do not
8289   // do this with i64->float->i64.
8290   if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8291     if (SrcI->getOperand(0)->getType() == FI.getType() &&
8292         (int)FI.getType()->getPrimitiveSizeInBits() <= 
8293                     SrcI->getType()->getFPMantissaWidth())
8294       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8295   
8296   return commonCastTransforms(FI);
8297 }
8298
8299 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8300   return commonCastTransforms(CI);
8301 }
8302
8303 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8304   return commonCastTransforms(CI);
8305 }
8306
8307 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8308   return commonPointerCastTransforms(CI);
8309 }
8310
8311 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8312   if (Instruction *I = commonCastTransforms(CI))
8313     return I;
8314   
8315   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8316   if (!DestPointee->isSized()) return 0;
8317
8318   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8319   ConstantInt *Cst;
8320   Value *X;
8321   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8322                                     m_ConstantInt(Cst)))) {
8323     // If the source and destination operands have the same type, see if this
8324     // is a single-index GEP.
8325     if (X->getType() == CI.getType()) {
8326       // Get the size of the pointee type.
8327       uint64_t Size = TD->getABITypeSize(DestPointee);
8328
8329       // Convert the constant to intptr type.
8330       APInt Offset = Cst->getValue();
8331       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8332
8333       // If Offset is evenly divisible by Size, we can do this xform.
8334       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8335         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8336         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8337       }
8338     }
8339     // TODO: Could handle other cases, e.g. where add is indexing into field of
8340     // struct etc.
8341   } else if (CI.getOperand(0)->hasOneUse() &&
8342              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8343     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8344     // "inttoptr+GEP" instead of "add+intptr".
8345     
8346     // Get the size of the pointee type.
8347     uint64_t Size = TD->getABITypeSize(DestPointee);
8348     
8349     // Convert the constant to intptr type.
8350     APInt Offset = Cst->getValue();
8351     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8352     
8353     // If Offset is evenly divisible by Size, we can do this xform.
8354     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8355       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8356       
8357       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8358                                                             "tmp"), CI);
8359       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8360     }
8361   }
8362   return 0;
8363 }
8364
8365 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8366   // If the operands are integer typed then apply the integer transforms,
8367   // otherwise just apply the common ones.
8368   Value *Src = CI.getOperand(0);
8369   const Type *SrcTy = Src->getType();
8370   const Type *DestTy = CI.getType();
8371
8372   if (SrcTy->isInteger() && DestTy->isInteger()) {
8373     if (Instruction *Result = commonIntCastTransforms(CI))
8374       return Result;
8375   } else if (isa<PointerType>(SrcTy)) {
8376     if (Instruction *I = commonPointerCastTransforms(CI))
8377       return I;
8378   } else {
8379     if (Instruction *Result = commonCastTransforms(CI))
8380       return Result;
8381   }
8382
8383
8384   // Get rid of casts from one type to the same type. These are useless and can
8385   // be replaced by the operand.
8386   if (DestTy == Src->getType())
8387     return ReplaceInstUsesWith(CI, Src);
8388
8389   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8390     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8391     const Type *DstElTy = DstPTy->getElementType();
8392     const Type *SrcElTy = SrcPTy->getElementType();
8393     
8394     // If the address spaces don't match, don't eliminate the bitcast, which is
8395     // required for changing types.
8396     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8397       return 0;
8398     
8399     // If we are casting a malloc or alloca to a pointer to a type of the same
8400     // size, rewrite the allocation instruction to allocate the "right" type.
8401     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8402       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8403         return V;
8404     
8405     // If the source and destination are pointers, and this cast is equivalent
8406     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8407     // This can enhance SROA and other transforms that want type-safe pointers.
8408     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8409     unsigned NumZeros = 0;
8410     while (SrcElTy != DstElTy && 
8411            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8412            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8413       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8414       ++NumZeros;
8415     }
8416
8417     // If we found a path from the src to dest, create the getelementptr now.
8418     if (SrcElTy == DstElTy) {
8419       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8420       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8421                                        ((Instruction*) NULL));
8422     }
8423   }
8424
8425   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8426     if (SVI->hasOneUse()) {
8427       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8428       // a bitconvert to a vector with the same # elts.
8429       if (isa<VectorType>(DestTy) && 
8430           cast<VectorType>(DestTy)->getNumElements() == 
8431                 SVI->getType()->getNumElements()) {
8432         CastInst *Tmp;
8433         // If either of the operands is a cast from CI.getType(), then
8434         // evaluating the shuffle in the casted destination's type will allow
8435         // us to eliminate at least one cast.
8436         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8437              Tmp->getOperand(0)->getType() == DestTy) ||
8438             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8439              Tmp->getOperand(0)->getType() == DestTy)) {
8440           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8441                                                SVI->getOperand(0), DestTy, &CI);
8442           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8443                                                SVI->getOperand(1), DestTy, &CI);
8444           // Return a new shuffle vector.  Use the same element ID's, as we
8445           // know the vector types match #elts.
8446           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8447         }
8448       }
8449     }
8450   }
8451   return 0;
8452 }
8453
8454 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8455 ///   %C = or %A, %B
8456 ///   %D = select %cond, %C, %A
8457 /// into:
8458 ///   %C = select %cond, %B, 0
8459 ///   %D = or %A, %C
8460 ///
8461 /// Assuming that the specified instruction is an operand to the select, return
8462 /// a bitmask indicating which operands of this instruction are foldable if they
8463 /// equal the other incoming value of the select.
8464 ///
8465 static unsigned GetSelectFoldableOperands(Instruction *I) {
8466   switch (I->getOpcode()) {
8467   case Instruction::Add:
8468   case Instruction::Mul:
8469   case Instruction::And:
8470   case Instruction::Or:
8471   case Instruction::Xor:
8472     return 3;              // Can fold through either operand.
8473   case Instruction::Sub:   // Can only fold on the amount subtracted.
8474   case Instruction::Shl:   // Can only fold on the shift amount.
8475   case Instruction::LShr:
8476   case Instruction::AShr:
8477     return 1;
8478   default:
8479     return 0;              // Cannot fold
8480   }
8481 }
8482
8483 /// GetSelectFoldableConstant - For the same transformation as the previous
8484 /// function, return the identity constant that goes into the select.
8485 static Constant *GetSelectFoldableConstant(Instruction *I) {
8486   switch (I->getOpcode()) {
8487   default: assert(0 && "This cannot happen!"); abort();
8488   case Instruction::Add:
8489   case Instruction::Sub:
8490   case Instruction::Or:
8491   case Instruction::Xor:
8492   case Instruction::Shl:
8493   case Instruction::LShr:
8494   case Instruction::AShr:
8495     return Constant::getNullValue(I->getType());
8496   case Instruction::And:
8497     return Constant::getAllOnesValue(I->getType());
8498   case Instruction::Mul:
8499     return ConstantInt::get(I->getType(), 1);
8500   }
8501 }
8502
8503 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8504 /// have the same opcode and only one use each.  Try to simplify this.
8505 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8506                                           Instruction *FI) {
8507   if (TI->getNumOperands() == 1) {
8508     // If this is a non-volatile load or a cast from the same type,
8509     // merge.
8510     if (TI->isCast()) {
8511       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8512         return 0;
8513     } else {
8514       return 0;  // unknown unary op.
8515     }
8516
8517     // Fold this by inserting a select from the input values.
8518     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8519                                            FI->getOperand(0), SI.getName()+".v");
8520     InsertNewInstBefore(NewSI, SI);
8521     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8522                             TI->getType());
8523   }
8524
8525   // Only handle binary operators here.
8526   if (!isa<BinaryOperator>(TI))
8527     return 0;
8528
8529   // Figure out if the operations have any operands in common.
8530   Value *MatchOp, *OtherOpT, *OtherOpF;
8531   bool MatchIsOpZero;
8532   if (TI->getOperand(0) == FI->getOperand(0)) {
8533     MatchOp  = TI->getOperand(0);
8534     OtherOpT = TI->getOperand(1);
8535     OtherOpF = FI->getOperand(1);
8536     MatchIsOpZero = true;
8537   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8538     MatchOp  = TI->getOperand(1);
8539     OtherOpT = TI->getOperand(0);
8540     OtherOpF = FI->getOperand(0);
8541     MatchIsOpZero = false;
8542   } else if (!TI->isCommutative()) {
8543     return 0;
8544   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8545     MatchOp  = TI->getOperand(0);
8546     OtherOpT = TI->getOperand(1);
8547     OtherOpF = FI->getOperand(0);
8548     MatchIsOpZero = true;
8549   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8550     MatchOp  = TI->getOperand(1);
8551     OtherOpT = TI->getOperand(0);
8552     OtherOpF = FI->getOperand(1);
8553     MatchIsOpZero = true;
8554   } else {
8555     return 0;
8556   }
8557
8558   // If we reach here, they do have operations in common.
8559   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8560                                          OtherOpF, SI.getName()+".v");
8561   InsertNewInstBefore(NewSI, SI);
8562
8563   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8564     if (MatchIsOpZero)
8565       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8566     else
8567       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8568   }
8569   assert(0 && "Shouldn't get here");
8570   return 0;
8571 }
8572
8573 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8574   Value *CondVal = SI.getCondition();
8575   Value *TrueVal = SI.getTrueValue();
8576   Value *FalseVal = SI.getFalseValue();
8577
8578   // select true, X, Y  -> X
8579   // select false, X, Y -> Y
8580   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8581     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8582
8583   // select C, X, X -> X
8584   if (TrueVal == FalseVal)
8585     return ReplaceInstUsesWith(SI, TrueVal);
8586
8587   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8588     return ReplaceInstUsesWith(SI, FalseVal);
8589   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8590     return ReplaceInstUsesWith(SI, TrueVal);
8591   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8592     if (isa<Constant>(TrueVal))
8593       return ReplaceInstUsesWith(SI, TrueVal);
8594     else
8595       return ReplaceInstUsesWith(SI, FalseVal);
8596   }
8597
8598   if (SI.getType() == Type::Int1Ty) {
8599     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8600       if (C->getZExtValue()) {
8601         // Change: A = select B, true, C --> A = or B, C
8602         return BinaryOperator::CreateOr(CondVal, FalseVal);
8603       } else {
8604         // Change: A = select B, false, C --> A = and !B, C
8605         Value *NotCond =
8606           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8607                                              "not."+CondVal->getName()), SI);
8608         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8609       }
8610     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8611       if (C->getZExtValue() == false) {
8612         // Change: A = select B, C, false --> A = and B, C
8613         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8614       } else {
8615         // Change: A = select B, C, true --> A = or !B, C
8616         Value *NotCond =
8617           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8618                                              "not."+CondVal->getName()), SI);
8619         return BinaryOperator::CreateOr(NotCond, TrueVal);
8620       }
8621     }
8622     
8623     // select a, b, a  -> a&b
8624     // select a, a, b  -> a|b
8625     if (CondVal == TrueVal)
8626       return BinaryOperator::CreateOr(CondVal, FalseVal);
8627     else if (CondVal == FalseVal)
8628       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8629   }
8630
8631   // Selecting between two integer constants?
8632   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8633     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8634       // select C, 1, 0 -> zext C to int
8635       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8636         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8637       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8638         // select C, 0, 1 -> zext !C to int
8639         Value *NotCond =
8640           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8641                                                "not."+CondVal->getName()), SI);
8642         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8643       }
8644       
8645       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8646
8647       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8648
8649         // (x <s 0) ? -1 : 0 -> ashr x, 31
8650         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8651           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8652             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8653               // The comparison constant and the result are not neccessarily the
8654               // same width. Make an all-ones value by inserting a AShr.
8655               Value *X = IC->getOperand(0);
8656               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8657               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8658               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8659                                                         ShAmt, "ones");
8660               InsertNewInstBefore(SRA, SI);
8661               
8662               // Finally, convert to the type of the select RHS.  We figure out
8663               // if this requires a SExt, Trunc or BitCast based on the sizes.
8664               Instruction::CastOps opc = Instruction::BitCast;
8665               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8666               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8667               if (SRASize < SISize)
8668                 opc = Instruction::SExt;
8669               else if (SRASize > SISize)
8670                 opc = Instruction::Trunc;
8671               return CastInst::Create(opc, SRA, SI.getType());
8672             }
8673           }
8674
8675
8676         // If one of the constants is zero (we know they can't both be) and we
8677         // have an icmp instruction with zero, and we have an 'and' with the
8678         // non-constant value, eliminate this whole mess.  This corresponds to
8679         // cases like this: ((X & 27) ? 27 : 0)
8680         if (TrueValC->isZero() || FalseValC->isZero())
8681           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8682               cast<Constant>(IC->getOperand(1))->isNullValue())
8683             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8684               if (ICA->getOpcode() == Instruction::And &&
8685                   isa<ConstantInt>(ICA->getOperand(1)) &&
8686                   (ICA->getOperand(1) == TrueValC ||
8687                    ICA->getOperand(1) == FalseValC) &&
8688                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8689                 // Okay, now we know that everything is set up, we just don't
8690                 // know whether we have a icmp_ne or icmp_eq and whether the 
8691                 // true or false val is the zero.
8692                 bool ShouldNotVal = !TrueValC->isZero();
8693                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8694                 Value *V = ICA;
8695                 if (ShouldNotVal)
8696                   V = InsertNewInstBefore(BinaryOperator::Create(
8697                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8698                 return ReplaceInstUsesWith(SI, V);
8699               }
8700       }
8701     }
8702
8703   // See if we are selecting two values based on a comparison of the two values.
8704   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8705     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8706       // Transform (X == Y) ? X : Y  -> Y
8707       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8708         // This is not safe in general for floating point:  
8709         // consider X== -0, Y== +0.
8710         // It becomes safe if either operand is a nonzero constant.
8711         ConstantFP *CFPt, *CFPf;
8712         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8713               !CFPt->getValueAPF().isZero()) ||
8714             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8715              !CFPf->getValueAPF().isZero()))
8716         return ReplaceInstUsesWith(SI, FalseVal);
8717       }
8718       // Transform (X != Y) ? X : Y  -> X
8719       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8720         return ReplaceInstUsesWith(SI, TrueVal);
8721       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8722
8723     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8724       // Transform (X == Y) ? Y : X  -> X
8725       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8726         // This is not safe in general for floating point:  
8727         // consider X== -0, Y== +0.
8728         // It becomes safe if either operand is a nonzero constant.
8729         ConstantFP *CFPt, *CFPf;
8730         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8731               !CFPt->getValueAPF().isZero()) ||
8732             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8733              !CFPf->getValueAPF().isZero()))
8734           return ReplaceInstUsesWith(SI, FalseVal);
8735       }
8736       // Transform (X != Y) ? Y : X  -> Y
8737       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8738         return ReplaceInstUsesWith(SI, TrueVal);
8739       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8740     }
8741   }
8742
8743   // See if we are selecting two values based on a comparison of the two values.
8744   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8745     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8746       // Transform (X == Y) ? X : Y  -> Y
8747       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8748         return ReplaceInstUsesWith(SI, FalseVal);
8749       // Transform (X != Y) ? X : Y  -> X
8750       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8751         return ReplaceInstUsesWith(SI, TrueVal);
8752       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8753
8754     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8755       // Transform (X == Y) ? Y : X  -> X
8756       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8757         return ReplaceInstUsesWith(SI, FalseVal);
8758       // Transform (X != Y) ? Y : X  -> Y
8759       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8760         return ReplaceInstUsesWith(SI, TrueVal);
8761       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8762     }
8763   }
8764
8765   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8766     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8767       if (TI->hasOneUse() && FI->hasOneUse()) {
8768         Instruction *AddOp = 0, *SubOp = 0;
8769
8770         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8771         if (TI->getOpcode() == FI->getOpcode())
8772           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8773             return IV;
8774
8775         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8776         // even legal for FP.
8777         if (TI->getOpcode() == Instruction::Sub &&
8778             FI->getOpcode() == Instruction::Add) {
8779           AddOp = FI; SubOp = TI;
8780         } else if (FI->getOpcode() == Instruction::Sub &&
8781                    TI->getOpcode() == Instruction::Add) {
8782           AddOp = TI; SubOp = FI;
8783         }
8784
8785         if (AddOp) {
8786           Value *OtherAddOp = 0;
8787           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8788             OtherAddOp = AddOp->getOperand(1);
8789           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8790             OtherAddOp = AddOp->getOperand(0);
8791           }
8792
8793           if (OtherAddOp) {
8794             // So at this point we know we have (Y -> OtherAddOp):
8795             //        select C, (add X, Y), (sub X, Z)
8796             Value *NegVal;  // Compute -Z
8797             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8798               NegVal = ConstantExpr::getNeg(C);
8799             } else {
8800               NegVal = InsertNewInstBefore(
8801                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8802             }
8803
8804             Value *NewTrueOp = OtherAddOp;
8805             Value *NewFalseOp = NegVal;
8806             if (AddOp != TI)
8807               std::swap(NewTrueOp, NewFalseOp);
8808             Instruction *NewSel =
8809               SelectInst::Create(CondVal, NewTrueOp,
8810                                  NewFalseOp, SI.getName() + ".p");
8811
8812             NewSel = InsertNewInstBefore(NewSel, SI);
8813             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8814           }
8815         }
8816       }
8817
8818   // See if we can fold the select into one of our operands.
8819   if (SI.getType()->isInteger()) {
8820     // See the comment above GetSelectFoldableOperands for a description of the
8821     // transformation we are doing here.
8822     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8823       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8824           !isa<Constant>(FalseVal))
8825         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8826           unsigned OpToFold = 0;
8827           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8828             OpToFold = 1;
8829           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8830             OpToFold = 2;
8831           }
8832
8833           if (OpToFold) {
8834             Constant *C = GetSelectFoldableConstant(TVI);
8835             Instruction *NewSel =
8836               SelectInst::Create(SI.getCondition(),
8837                                  TVI->getOperand(2-OpToFold), C);
8838             InsertNewInstBefore(NewSel, SI);
8839             NewSel->takeName(TVI);
8840             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8841               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8842             else {
8843               assert(0 && "Unknown instruction!!");
8844             }
8845           }
8846         }
8847
8848     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8849       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8850           !isa<Constant>(TrueVal))
8851         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8852           unsigned OpToFold = 0;
8853           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8854             OpToFold = 1;
8855           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8856             OpToFold = 2;
8857           }
8858
8859           if (OpToFold) {
8860             Constant *C = GetSelectFoldableConstant(FVI);
8861             Instruction *NewSel =
8862               SelectInst::Create(SI.getCondition(), C,
8863                                  FVI->getOperand(2-OpToFold));
8864             InsertNewInstBefore(NewSel, SI);
8865             NewSel->takeName(FVI);
8866             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8867               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8868             else
8869               assert(0 && "Unknown instruction!!");
8870           }
8871         }
8872   }
8873
8874   if (BinaryOperator::isNot(CondVal)) {
8875     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8876     SI.setOperand(1, FalseVal);
8877     SI.setOperand(2, TrueVal);
8878     return &SI;
8879   }
8880
8881   return 0;
8882 }
8883
8884 /// EnforceKnownAlignment - If the specified pointer points to an object that
8885 /// we control, modify the object's alignment to PrefAlign. This isn't
8886 /// often possible though. If alignment is important, a more reliable approach
8887 /// is to simply align all global variables and allocation instructions to
8888 /// their preferred alignment from the beginning.
8889 ///
8890 static unsigned EnforceKnownAlignment(Value *V,
8891                                       unsigned Align, unsigned PrefAlign) {
8892
8893   User *U = dyn_cast<User>(V);
8894   if (!U) return Align;
8895
8896   switch (getOpcode(U)) {
8897   default: break;
8898   case Instruction::BitCast:
8899     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8900   case Instruction::GetElementPtr: {
8901     // If all indexes are zero, it is just the alignment of the base pointer.
8902     bool AllZeroOperands = true;
8903     for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8904       if (!isa<Constant>(U->getOperand(i)) ||
8905           !cast<Constant>(U->getOperand(i))->isNullValue()) {
8906         AllZeroOperands = false;
8907         break;
8908       }
8909
8910     if (AllZeroOperands) {
8911       // Treat this like a bitcast.
8912       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8913     }
8914     break;
8915   }
8916   }
8917
8918   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8919     // If there is a large requested alignment and we can, bump up the alignment
8920     // of the global.
8921     if (!GV->isDeclaration()) {
8922       GV->setAlignment(PrefAlign);
8923       Align = PrefAlign;
8924     }
8925   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8926     // If there is a requested alignment and if this is an alloca, round up.  We
8927     // don't do this for malloc, because some systems can't respect the request.
8928     if (isa<AllocaInst>(AI)) {
8929       AI->setAlignment(PrefAlign);
8930       Align = PrefAlign;
8931     }
8932   }
8933
8934   return Align;
8935 }
8936
8937 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8938 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8939 /// and it is more than the alignment of the ultimate object, see if we can
8940 /// increase the alignment of the ultimate object, making this check succeed.
8941 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8942                                                   unsigned PrefAlign) {
8943   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8944                       sizeof(PrefAlign) * CHAR_BIT;
8945   APInt Mask = APInt::getAllOnesValue(BitWidth);
8946   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8947   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8948   unsigned TrailZ = KnownZero.countTrailingOnes();
8949   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8950
8951   if (PrefAlign > Align)
8952     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8953   
8954     // We don't need to make any adjustment.
8955   return Align;
8956 }
8957
8958 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8959   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8960   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8961   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8962   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8963
8964   if (CopyAlign < MinAlign) {
8965     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8966     return MI;
8967   }
8968   
8969   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8970   // load/store.
8971   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8972   if (MemOpLength == 0) return 0;
8973   
8974   // Source and destination pointer types are always "i8*" for intrinsic.  See
8975   // if the size is something we can handle with a single primitive load/store.
8976   // A single load+store correctly handles overlapping memory in the memmove
8977   // case.
8978   unsigned Size = MemOpLength->getZExtValue();
8979   if (Size == 0) return MI;  // Delete this mem transfer.
8980   
8981   if (Size > 8 || (Size&(Size-1)))
8982     return 0;  // If not 1/2/4/8 bytes, exit.
8983   
8984   // Use an integer load+store unless we can find something better.
8985   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8986   
8987   // Memcpy forces the use of i8* for the source and destination.  That means
8988   // that if you're using memcpy to move one double around, you'll get a cast
8989   // from double* to i8*.  We'd much rather use a double load+store rather than
8990   // an i64 load+store, here because this improves the odds that the source or
8991   // dest address will be promotable.  See if we can find a better type than the
8992   // integer datatype.
8993   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8994     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8995     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8996       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8997       // down through these levels if so.
8998       while (!SrcETy->isSingleValueType()) {
8999         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9000           if (STy->getNumElements() == 1)
9001             SrcETy = STy->getElementType(0);
9002           else
9003             break;
9004         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9005           if (ATy->getNumElements() == 1)
9006             SrcETy = ATy->getElementType();
9007           else
9008             break;
9009         } else
9010           break;
9011       }
9012       
9013       if (SrcETy->isSingleValueType())
9014         NewPtrTy = PointerType::getUnqual(SrcETy);
9015     }
9016   }
9017   
9018   
9019   // If the memcpy/memmove provides better alignment info than we can
9020   // infer, use it.
9021   SrcAlign = std::max(SrcAlign, CopyAlign);
9022   DstAlign = std::max(DstAlign, CopyAlign);
9023   
9024   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9025   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9026   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9027   InsertNewInstBefore(L, *MI);
9028   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9029
9030   // Set the size of the copy to 0, it will be deleted on the next iteration.
9031   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9032   return MI;
9033 }
9034
9035 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9036   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9037   if (MI->getAlignment()->getZExtValue() < Alignment) {
9038     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9039     return MI;
9040   }
9041   
9042   // Extract the length and alignment and fill if they are constant.
9043   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9044   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9045   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9046     return 0;
9047   uint64_t Len = LenC->getZExtValue();
9048   Alignment = MI->getAlignment()->getZExtValue();
9049   
9050   // If the length is zero, this is a no-op
9051   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9052   
9053   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9054   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9055     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9056     
9057     Value *Dest = MI->getDest();
9058     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9059
9060     // Alignment 0 is identity for alignment 1 for memset, but not store.
9061     if (Alignment == 0) Alignment = 1;
9062     
9063     // Extract the fill value and store.
9064     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9065     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9066                                       Alignment), *MI);
9067     
9068     // Set the size of the copy to 0, it will be deleted on the next iteration.
9069     MI->setLength(Constant::getNullValue(LenC->getType()));
9070     return MI;
9071   }
9072
9073   return 0;
9074 }
9075
9076
9077 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9078 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9079 /// the heavy lifting.
9080 ///
9081 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9082   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9083   if (!II) return visitCallSite(&CI);
9084   
9085   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9086   // visitCallSite.
9087   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9088     bool Changed = false;
9089
9090     // memmove/cpy/set of zero bytes is a noop.
9091     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9092       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9093
9094       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9095         if (CI->getZExtValue() == 1) {
9096           // Replace the instruction with just byte operations.  We would
9097           // transform other cases to loads/stores, but we don't know if
9098           // alignment is sufficient.
9099         }
9100     }
9101
9102     // If we have a memmove and the source operation is a constant global,
9103     // then the source and dest pointers can't alias, so we can change this
9104     // into a call to memcpy.
9105     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9106       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9107         if (GVSrc->isConstant()) {
9108           Module *M = CI.getParent()->getParent()->getParent();
9109           Intrinsic::ID MemCpyID;
9110           if (CI.getOperand(3)->getType() == Type::Int32Ty)
9111             MemCpyID = Intrinsic::memcpy_i32;
9112           else
9113             MemCpyID = Intrinsic::memcpy_i64;
9114           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
9115           Changed = true;
9116         }
9117     }
9118
9119     // If we can determine a pointer alignment that is bigger than currently
9120     // set, update the alignment.
9121     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9122       if (Instruction *I = SimplifyMemTransfer(MI))
9123         return I;
9124     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9125       if (Instruction *I = SimplifyMemSet(MSI))
9126         return I;
9127     }
9128           
9129     if (Changed) return II;
9130   } else {
9131     switch (II->getIntrinsicID()) {
9132     default: break;
9133     case Intrinsic::ppc_altivec_lvx:
9134     case Intrinsic::ppc_altivec_lvxl:
9135     case Intrinsic::x86_sse_loadu_ps:
9136     case Intrinsic::x86_sse2_loadu_pd:
9137     case Intrinsic::x86_sse2_loadu_dq:
9138       // Turn PPC lvx     -> load if the pointer is known aligned.
9139       // Turn X86 loadups -> load if the pointer is known aligned.
9140       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9141         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9142                                          PointerType::getUnqual(II->getType()),
9143                                          CI);
9144         return new LoadInst(Ptr);
9145       }
9146       break;
9147     case Intrinsic::ppc_altivec_stvx:
9148     case Intrinsic::ppc_altivec_stvxl:
9149       // Turn stvx -> store if the pointer is known aligned.
9150       if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9151         const Type *OpPtrTy = 
9152           PointerType::getUnqual(II->getOperand(1)->getType());
9153         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9154         return new StoreInst(II->getOperand(1), Ptr);
9155       }
9156       break;
9157     case Intrinsic::x86_sse_storeu_ps:
9158     case Intrinsic::x86_sse2_storeu_pd:
9159     case Intrinsic::x86_sse2_storeu_dq:
9160     case Intrinsic::x86_sse2_storel_dq:
9161       // Turn X86 storeu -> store if the pointer is known aligned.
9162       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9163         const Type *OpPtrTy = 
9164           PointerType::getUnqual(II->getOperand(2)->getType());
9165         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9166         return new StoreInst(II->getOperand(2), Ptr);
9167       }
9168       break;
9169       
9170     case Intrinsic::x86_sse_cvttss2si: {
9171       // These intrinsics only demands the 0th element of its input vector.  If
9172       // we can simplify the input based on that, do so now.
9173       uint64_t UndefElts;
9174       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9175                                                 UndefElts)) {
9176         II->setOperand(1, V);
9177         return II;
9178       }
9179       break;
9180     }
9181       
9182     case Intrinsic::ppc_altivec_vperm:
9183       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9184       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9185         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9186         
9187         // Check that all of the elements are integer constants or undefs.
9188         bool AllEltsOk = true;
9189         for (unsigned i = 0; i != 16; ++i) {
9190           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9191               !isa<UndefValue>(Mask->getOperand(i))) {
9192             AllEltsOk = false;
9193             break;
9194           }
9195         }
9196         
9197         if (AllEltsOk) {
9198           // Cast the input vectors to byte vectors.
9199           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9200           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9201           Value *Result = UndefValue::get(Op0->getType());
9202           
9203           // Only extract each element once.
9204           Value *ExtractedElts[32];
9205           memset(ExtractedElts, 0, sizeof(ExtractedElts));
9206           
9207           for (unsigned i = 0; i != 16; ++i) {
9208             if (isa<UndefValue>(Mask->getOperand(i)))
9209               continue;
9210             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9211             Idx &= 31;  // Match the hardware behavior.
9212             
9213             if (ExtractedElts[Idx] == 0) {
9214               Instruction *Elt = 
9215                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9216               InsertNewInstBefore(Elt, CI);
9217               ExtractedElts[Idx] = Elt;
9218             }
9219           
9220             // Insert this value into the result vector.
9221             Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9222                                                i, "tmp");
9223             InsertNewInstBefore(cast<Instruction>(Result), CI);
9224           }
9225           return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9226         }
9227       }
9228       break;
9229
9230     case Intrinsic::stackrestore: {
9231       // If the save is right next to the restore, remove the restore.  This can
9232       // happen when variable allocas are DCE'd.
9233       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9234         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9235           BasicBlock::iterator BI = SS;
9236           if (&*++BI == II)
9237             return EraseInstFromFunction(CI);
9238         }
9239       }
9240       
9241       // Scan down this block to see if there is another stack restore in the
9242       // same block without an intervening call/alloca.
9243       BasicBlock::iterator BI = II;
9244       TerminatorInst *TI = II->getParent()->getTerminator();
9245       bool CannotRemove = false;
9246       for (++BI; &*BI != TI; ++BI) {
9247         if (isa<AllocaInst>(BI)) {
9248           CannotRemove = true;
9249           break;
9250         }
9251         if (isa<CallInst>(BI)) {
9252           if (!isa<IntrinsicInst>(BI)) {
9253             CannotRemove = true;
9254             break;
9255           }
9256           // If there is a stackrestore below this one, remove this one.
9257           return EraseInstFromFunction(CI);
9258         }
9259       }
9260       
9261       // If the stack restore is in a return/unwind block and if there are no
9262       // allocas or calls between the restore and the return, nuke the restore.
9263       if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9264         return EraseInstFromFunction(CI);
9265       break;
9266     }
9267     }
9268   }
9269
9270   return visitCallSite(II);
9271 }
9272
9273 // InvokeInst simplification
9274 //
9275 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9276   return visitCallSite(&II);
9277 }
9278
9279 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9280 /// passed through the varargs area, we can eliminate the use of the cast.
9281 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9282                                          const CastInst * const CI,
9283                                          const TargetData * const TD,
9284                                          const int ix) {
9285   if (!CI->isLosslessCast())
9286     return false;
9287
9288   // The size of ByVal arguments is derived from the type, so we
9289   // can't change to a type with a different size.  If the size were
9290   // passed explicitly we could avoid this check.
9291   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9292     return true;
9293
9294   const Type* SrcTy = 
9295             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9296   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9297   if (!SrcTy->isSized() || !DstTy->isSized())
9298     return false;
9299   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9300     return false;
9301   return true;
9302 }
9303
9304 // visitCallSite - Improvements for call and invoke instructions.
9305 //
9306 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9307   bool Changed = false;
9308
9309   // If the callee is a constexpr cast of a function, attempt to move the cast
9310   // to the arguments of the call/invoke.
9311   if (transformConstExprCastCall(CS)) return 0;
9312
9313   Value *Callee = CS.getCalledValue();
9314
9315   if (Function *CalleeF = dyn_cast<Function>(Callee))
9316     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9317       Instruction *OldCall = CS.getInstruction();
9318       // If the call and callee calling conventions don't match, this call must
9319       // be unreachable, as the call is undefined.
9320       new StoreInst(ConstantInt::getTrue(),
9321                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9322                                     OldCall);
9323       if (!OldCall->use_empty())
9324         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9325       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9326         return EraseInstFromFunction(*OldCall);
9327       return 0;
9328     }
9329
9330   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9331     // This instruction is not reachable, just remove it.  We insert a store to
9332     // undef so that we know that this code is not reachable, despite the fact
9333     // that we can't modify the CFG here.
9334     new StoreInst(ConstantInt::getTrue(),
9335                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9336                   CS.getInstruction());
9337
9338     if (!CS.getInstruction()->use_empty())
9339       CS.getInstruction()->
9340         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9341
9342     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9343       // Don't break the CFG, insert a dummy cond branch.
9344       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9345                          ConstantInt::getTrue(), II);
9346     }
9347     return EraseInstFromFunction(*CS.getInstruction());
9348   }
9349
9350   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9351     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9352       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9353         return transformCallThroughTrampoline(CS);
9354
9355   const PointerType *PTy = cast<PointerType>(Callee->getType());
9356   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9357   if (FTy->isVarArg()) {
9358     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9359     // See if we can optimize any arguments passed through the varargs area of
9360     // the call.
9361     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9362            E = CS.arg_end(); I != E; ++I, ++ix) {
9363       CastInst *CI = dyn_cast<CastInst>(*I);
9364       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9365         *I = CI->getOperand(0);
9366         Changed = true;
9367       }
9368     }
9369   }
9370
9371   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9372     // Inline asm calls cannot throw - mark them 'nounwind'.
9373     CS.setDoesNotThrow();
9374     Changed = true;
9375   }
9376
9377   return Changed ? CS.getInstruction() : 0;
9378 }
9379
9380 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9381 // attempt to move the cast to the arguments of the call/invoke.
9382 //
9383 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9384   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9385   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9386   if (CE->getOpcode() != Instruction::BitCast || 
9387       !isa<Function>(CE->getOperand(0)))
9388     return false;
9389   Function *Callee = cast<Function>(CE->getOperand(0));
9390   Instruction *Caller = CS.getInstruction();
9391   const PAListPtr &CallerPAL = CS.getParamAttrs();
9392
9393   // Okay, this is a cast from a function to a different type.  Unless doing so
9394   // would cause a type conversion of one of our arguments, change this call to
9395   // be a direct call with arguments casted to the appropriate types.
9396   //
9397   const FunctionType *FT = Callee->getFunctionType();
9398   const Type *OldRetTy = Caller->getType();
9399
9400   if (isa<StructType>(FT->getReturnType()))
9401     return false; // TODO: Handle multiple return values.
9402
9403   // Check to see if we are changing the return type...
9404   if (OldRetTy != FT->getReturnType()) {
9405     if (Callee->isDeclaration() &&
9406         // Conversion is ok if changing from pointer to int of same size.
9407         !(isa<PointerType>(FT->getReturnType()) &&
9408           TD->getIntPtrType() == OldRetTy))
9409       return false;   // Cannot transform this return value.
9410
9411     if (!Caller->use_empty() &&
9412         // void -> non-void is handled specially
9413         FT->getReturnType() != Type::VoidTy &&
9414         !CastInst::isCastable(FT->getReturnType(), OldRetTy))
9415       return false;   // Cannot transform this return value.
9416
9417     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9418       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9419       if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9420         return false;   // Attribute not compatible with transformed value.
9421     }
9422
9423     // If the callsite is an invoke instruction, and the return value is used by
9424     // a PHI node in a successor, we cannot change the return type of the call
9425     // because there is no place to put the cast instruction (without breaking
9426     // the critical edge).  Bail out in this case.
9427     if (!Caller->use_empty())
9428       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9429         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9430              UI != E; ++UI)
9431           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9432             if (PN->getParent() == II->getNormalDest() ||
9433                 PN->getParent() == II->getUnwindDest())
9434               return false;
9435   }
9436
9437   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9438   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9439
9440   CallSite::arg_iterator AI = CS.arg_begin();
9441   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9442     const Type *ParamTy = FT->getParamType(i);
9443     const Type *ActTy = (*AI)->getType();
9444
9445     if (!CastInst::isCastable(ActTy, ParamTy))
9446       return false;   // Cannot transform this parameter value.
9447
9448     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9449       return false;   // Attribute not compatible with transformed value.
9450
9451     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
9452     // Some conversions are safe even if we do not have a body.
9453     // Either we can cast directly, or we can upconvert the argument
9454     bool isConvertible = ActTy == ParamTy ||
9455       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
9456       (ParamTy->isInteger() && ActTy->isInteger() &&
9457        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9458       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
9459        && c->getValue().isStrictlyPositive());
9460     if (Callee->isDeclaration() && !isConvertible) return false;
9461   }
9462
9463   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9464       Callee->isDeclaration())
9465     return false;   // Do not delete arguments unless we have a function body.
9466
9467   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9468       !CallerPAL.isEmpty())
9469     // In this case we have more arguments than the new function type, but we
9470     // won't be dropping them.  Check that these extra arguments have attributes
9471     // that are compatible with being a vararg call argument.
9472     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9473       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9474         break;
9475       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9476       if (PAttrs & ParamAttr::VarArgsIncompatible)
9477         return false;
9478     }
9479
9480   // Okay, we decided that this is a safe thing to do: go ahead and start
9481   // inserting cast instructions as necessary...
9482   std::vector<Value*> Args;
9483   Args.reserve(NumActualArgs);
9484   SmallVector<ParamAttrsWithIndex, 8> attrVec;
9485   attrVec.reserve(NumCommonArgs);
9486
9487   // Get any return attributes.
9488   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9489
9490   // If the return value is not being used, the type may not be compatible
9491   // with the existing attributes.  Wipe out any problematic attributes.
9492   RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
9493
9494   // Add the new return attributes.
9495   if (RAttrs)
9496     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
9497
9498   AI = CS.arg_begin();
9499   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9500     const Type *ParamTy = FT->getParamType(i);
9501     if ((*AI)->getType() == ParamTy) {
9502       Args.push_back(*AI);
9503     } else {
9504       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9505           false, ParamTy, false);
9506       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9507       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9508     }
9509
9510     // Add any parameter attributes.
9511     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9512       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9513   }
9514
9515   // If the function takes more arguments than the call was taking, add them
9516   // now...
9517   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9518     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9519
9520   // If we are removing arguments to the function, emit an obnoxious warning...
9521   if (FT->getNumParams() < NumActualArgs) {
9522     if (!FT->isVarArg()) {
9523       cerr << "WARNING: While resolving call to function '"
9524            << Callee->getName() << "' arguments were dropped!\n";
9525     } else {
9526       // Add all of the arguments in their promoted form to the arg list...
9527       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9528         const Type *PTy = getPromotedType((*AI)->getType());
9529         if (PTy != (*AI)->getType()) {
9530           // Must promote to pass through va_arg area!
9531           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9532                                                                 PTy, false);
9533           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9534           InsertNewInstBefore(Cast, *Caller);
9535           Args.push_back(Cast);
9536         } else {
9537           Args.push_back(*AI);
9538         }
9539
9540         // Add any parameter attributes.
9541         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9542           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9543       }
9544     }
9545   }
9546
9547   if (FT->getReturnType() == Type::VoidTy)
9548     Caller->setName("");   // Void type should not have a name.
9549
9550   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9551
9552   Instruction *NC;
9553   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9554     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9555                             Args.begin(), Args.end(),
9556                             Caller->getName(), Caller);
9557     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9558     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9559   } else {
9560     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9561                           Caller->getName(), Caller);
9562     CallInst *CI = cast<CallInst>(Caller);
9563     if (CI->isTailCall())
9564       cast<CallInst>(NC)->setTailCall();
9565     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9566     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9567   }
9568
9569   // Insert a cast of the return type as necessary.
9570   Value *NV = NC;
9571   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9572     if (NV->getType() != Type::VoidTy) {
9573       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9574                                                             OldRetTy, false);
9575       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9576
9577       // If this is an invoke instruction, we should insert it after the first
9578       // non-phi, instruction in the normal successor block.
9579       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9580         BasicBlock::iterator I = II->getNormalDest()->begin();
9581         while (isa<PHINode>(I)) ++I;
9582         InsertNewInstBefore(NC, *I);
9583       } else {
9584         // Otherwise, it's a call, just insert cast right after the call instr
9585         InsertNewInstBefore(NC, *Caller);
9586       }
9587       AddUsersToWorkList(*Caller);
9588     } else {
9589       NV = UndefValue::get(Caller->getType());
9590     }
9591   }
9592
9593   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9594     Caller->replaceAllUsesWith(NV);
9595   Caller->eraseFromParent();
9596   RemoveFromWorkList(Caller);
9597   return true;
9598 }
9599
9600 // transformCallThroughTrampoline - Turn a call to a function created by the
9601 // init_trampoline intrinsic into a direct call to the underlying function.
9602 //
9603 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9604   Value *Callee = CS.getCalledValue();
9605   const PointerType *PTy = cast<PointerType>(Callee->getType());
9606   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9607   const PAListPtr &Attrs = CS.getParamAttrs();
9608
9609   // If the call already has the 'nest' attribute somewhere then give up -
9610   // otherwise 'nest' would occur twice after splicing in the chain.
9611   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9612     return 0;
9613
9614   IntrinsicInst *Tramp =
9615     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9616
9617   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9618   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9619   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9620
9621   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9622   if (!NestAttrs.isEmpty()) {
9623     unsigned NestIdx = 1;
9624     const Type *NestTy = 0;
9625     ParameterAttributes NestAttr = ParamAttr::None;
9626
9627     // Look for a parameter marked with the 'nest' attribute.
9628     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9629          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9630       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9631         // Record the parameter type and any other attributes.
9632         NestTy = *I;
9633         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9634         break;
9635       }
9636
9637     if (NestTy) {
9638       Instruction *Caller = CS.getInstruction();
9639       std::vector<Value*> NewArgs;
9640       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9641
9642       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9643       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9644
9645       // Insert the nest argument into the call argument list, which may
9646       // mean appending it.  Likewise for attributes.
9647
9648       // Add any function result attributes.
9649       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9650         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9651
9652       {
9653         unsigned Idx = 1;
9654         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9655         do {
9656           if (Idx == NestIdx) {
9657             // Add the chain argument and attributes.
9658             Value *NestVal = Tramp->getOperand(3);
9659             if (NestVal->getType() != NestTy)
9660               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9661             NewArgs.push_back(NestVal);
9662             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9663           }
9664
9665           if (I == E)
9666             break;
9667
9668           // Add the original argument and attributes.
9669           NewArgs.push_back(*I);
9670           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9671             NewAttrs.push_back
9672               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9673
9674           ++Idx, ++I;
9675         } while (1);
9676       }
9677
9678       // The trampoline may have been bitcast to a bogus type (FTy).
9679       // Handle this by synthesizing a new function type, equal to FTy
9680       // with the chain parameter inserted.
9681
9682       std::vector<const Type*> NewTypes;
9683       NewTypes.reserve(FTy->getNumParams()+1);
9684
9685       // Insert the chain's type into the list of parameter types, which may
9686       // mean appending it.
9687       {
9688         unsigned Idx = 1;
9689         FunctionType::param_iterator I = FTy->param_begin(),
9690           E = FTy->param_end();
9691
9692         do {
9693           if (Idx == NestIdx)
9694             // Add the chain's type.
9695             NewTypes.push_back(NestTy);
9696
9697           if (I == E)
9698             break;
9699
9700           // Add the original type.
9701           NewTypes.push_back(*I);
9702
9703           ++Idx, ++I;
9704         } while (1);
9705       }
9706
9707       // Replace the trampoline call with a direct call.  Let the generic
9708       // code sort out any function type mismatches.
9709       FunctionType *NewFTy =
9710         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9711       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9712         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9713       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9714
9715       Instruction *NewCaller;
9716       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9717         NewCaller = InvokeInst::Create(NewCallee,
9718                                        II->getNormalDest(), II->getUnwindDest(),
9719                                        NewArgs.begin(), NewArgs.end(),
9720                                        Caller->getName(), Caller);
9721         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9722         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9723       } else {
9724         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9725                                      Caller->getName(), Caller);
9726         if (cast<CallInst>(Caller)->isTailCall())
9727           cast<CallInst>(NewCaller)->setTailCall();
9728         cast<CallInst>(NewCaller)->
9729           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9730         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9731       }
9732       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9733         Caller->replaceAllUsesWith(NewCaller);
9734       Caller->eraseFromParent();
9735       RemoveFromWorkList(Caller);
9736       return 0;
9737     }
9738   }
9739
9740   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9741   // parameter, there is no need to adjust the argument list.  Let the generic
9742   // code sort out any function type mismatches.
9743   Constant *NewCallee =
9744     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9745   CS.setCalledFunction(NewCallee);
9746   return CS.getInstruction();
9747 }
9748
9749 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9750 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9751 /// and a single binop.
9752 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9753   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9754   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9755          isa<CmpInst>(FirstInst));
9756   unsigned Opc = FirstInst->getOpcode();
9757   Value *LHSVal = FirstInst->getOperand(0);
9758   Value *RHSVal = FirstInst->getOperand(1);
9759     
9760   const Type *LHSType = LHSVal->getType();
9761   const Type *RHSType = RHSVal->getType();
9762   
9763   // Scan to see if all operands are the same opcode, all have one use, and all
9764   // kill their operands (i.e. the operands have one use).
9765   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9766     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9767     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9768         // Verify type of the LHS matches so we don't fold cmp's of different
9769         // types or GEP's with different index types.
9770         I->getOperand(0)->getType() != LHSType ||
9771         I->getOperand(1)->getType() != RHSType)
9772       return 0;
9773
9774     // If they are CmpInst instructions, check their predicates
9775     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9776       if (cast<CmpInst>(I)->getPredicate() !=
9777           cast<CmpInst>(FirstInst)->getPredicate())
9778         return 0;
9779     
9780     // Keep track of which operand needs a phi node.
9781     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9782     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9783   }
9784   
9785   // Otherwise, this is safe to transform, determine if it is profitable.
9786
9787   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9788   // Indexes are often folded into load/store instructions, so we don't want to
9789   // hide them behind a phi.
9790   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9791     return 0;
9792   
9793   Value *InLHS = FirstInst->getOperand(0);
9794   Value *InRHS = FirstInst->getOperand(1);
9795   PHINode *NewLHS = 0, *NewRHS = 0;
9796   if (LHSVal == 0) {
9797     NewLHS = PHINode::Create(LHSType,
9798                              FirstInst->getOperand(0)->getName() + ".pn");
9799     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9800     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9801     InsertNewInstBefore(NewLHS, PN);
9802     LHSVal = NewLHS;
9803   }
9804   
9805   if (RHSVal == 0) {
9806     NewRHS = PHINode::Create(RHSType,
9807                              FirstInst->getOperand(1)->getName() + ".pn");
9808     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9809     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9810     InsertNewInstBefore(NewRHS, PN);
9811     RHSVal = NewRHS;
9812   }
9813   
9814   // Add all operands to the new PHIs.
9815   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9816     if (NewLHS) {
9817       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9818       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9819     }
9820     if (NewRHS) {
9821       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9822       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9823     }
9824   }
9825     
9826   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9827     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9828   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9829     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9830                            RHSVal);
9831   else {
9832     assert(isa<GetElementPtrInst>(FirstInst));
9833     return GetElementPtrInst::Create(LHSVal, RHSVal);
9834   }
9835 }
9836
9837 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9838 /// of the block that defines it.  This means that it must be obvious the value
9839 /// of the load is not changed from the point of the load to the end of the
9840 /// block it is in.
9841 ///
9842 /// Finally, it is safe, but not profitable, to sink a load targetting a
9843 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9844 /// to a register.
9845 static bool isSafeToSinkLoad(LoadInst *L) {
9846   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9847   
9848   for (++BBI; BBI != E; ++BBI)
9849     if (BBI->mayWriteToMemory())
9850       return false;
9851   
9852   // Check for non-address taken alloca.  If not address-taken already, it isn't
9853   // profitable to do this xform.
9854   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9855     bool isAddressTaken = false;
9856     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9857          UI != E; ++UI) {
9858       if (isa<LoadInst>(UI)) continue;
9859       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9860         // If storing TO the alloca, then the address isn't taken.
9861         if (SI->getOperand(1) == AI) continue;
9862       }
9863       isAddressTaken = true;
9864       break;
9865     }
9866     
9867     if (!isAddressTaken)
9868       return false;
9869   }
9870   
9871   return true;
9872 }
9873
9874
9875 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9876 // operator and they all are only used by the PHI, PHI together their
9877 // inputs, and do the operation once, to the result of the PHI.
9878 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9879   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9880
9881   // Scan the instruction, looking for input operations that can be folded away.
9882   // If all input operands to the phi are the same instruction (e.g. a cast from
9883   // the same type or "+42") we can pull the operation through the PHI, reducing
9884   // code size and simplifying code.
9885   Constant *ConstantOp = 0;
9886   const Type *CastSrcTy = 0;
9887   bool isVolatile = false;
9888   if (isa<CastInst>(FirstInst)) {
9889     CastSrcTy = FirstInst->getOperand(0)->getType();
9890   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9891     // Can fold binop, compare or shift here if the RHS is a constant, 
9892     // otherwise call FoldPHIArgBinOpIntoPHI.
9893     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9894     if (ConstantOp == 0)
9895       return FoldPHIArgBinOpIntoPHI(PN);
9896   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9897     isVolatile = LI->isVolatile();
9898     // We can't sink the load if the loaded value could be modified between the
9899     // load and the PHI.
9900     if (LI->getParent() != PN.getIncomingBlock(0) ||
9901         !isSafeToSinkLoad(LI))
9902       return 0;
9903   } else if (isa<GetElementPtrInst>(FirstInst)) {
9904     if (FirstInst->getNumOperands() == 2)
9905       return FoldPHIArgBinOpIntoPHI(PN);
9906     // Can't handle general GEPs yet.
9907     return 0;
9908   } else {
9909     return 0;  // Cannot fold this operation.
9910   }
9911
9912   // Check to see if all arguments are the same operation.
9913   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9914     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9915     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9916     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9917       return 0;
9918     if (CastSrcTy) {
9919       if (I->getOperand(0)->getType() != CastSrcTy)
9920         return 0;  // Cast operation must match.
9921     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9922       // We can't sink the load if the loaded value could be modified between 
9923       // the load and the PHI.
9924       if (LI->isVolatile() != isVolatile ||
9925           LI->getParent() != PN.getIncomingBlock(i) ||
9926           !isSafeToSinkLoad(LI))
9927         return 0;
9928       
9929       // If the PHI is volatile and its block has multiple successors, sinking
9930       // it would remove a load of the volatile value from the path through the
9931       // other successor.
9932       if (isVolatile &&
9933           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9934         return 0;
9935
9936       
9937     } else if (I->getOperand(1) != ConstantOp) {
9938       return 0;
9939     }
9940   }
9941
9942   // Okay, they are all the same operation.  Create a new PHI node of the
9943   // correct type, and PHI together all of the LHS's of the instructions.
9944   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9945                                    PN.getName()+".in");
9946   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9947
9948   Value *InVal = FirstInst->getOperand(0);
9949   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9950
9951   // Add all operands to the new PHI.
9952   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9953     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9954     if (NewInVal != InVal)
9955       InVal = 0;
9956     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9957   }
9958
9959   Value *PhiVal;
9960   if (InVal) {
9961     // The new PHI unions all of the same values together.  This is really
9962     // common, so we handle it intelligently here for compile-time speed.
9963     PhiVal = InVal;
9964     delete NewPN;
9965   } else {
9966     InsertNewInstBefore(NewPN, PN);
9967     PhiVal = NewPN;
9968   }
9969
9970   // Insert and return the new operation.
9971   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9972     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9973   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9974     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9975   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9976     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9977                            PhiVal, ConstantOp);
9978   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9979   
9980   // If this was a volatile load that we are merging, make sure to loop through
9981   // and mark all the input loads as non-volatile.  If we don't do this, we will
9982   // insert a new volatile load and the old ones will not be deletable.
9983   if (isVolatile)
9984     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9985       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9986   
9987   return new LoadInst(PhiVal, "", isVolatile);
9988 }
9989
9990 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9991 /// that is dead.
9992 static bool DeadPHICycle(PHINode *PN,
9993                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9994   if (PN->use_empty()) return true;
9995   if (!PN->hasOneUse()) return false;
9996
9997   // Remember this node, and if we find the cycle, return.
9998   if (!PotentiallyDeadPHIs.insert(PN))
9999     return true;
10000   
10001   // Don't scan crazily complex things.
10002   if (PotentiallyDeadPHIs.size() == 16)
10003     return false;
10004
10005   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10006     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10007
10008   return false;
10009 }
10010
10011 /// PHIsEqualValue - Return true if this phi node is always equal to
10012 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10013 ///   z = some value; x = phi (y, z); y = phi (x, z)
10014 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10015                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10016   // See if we already saw this PHI node.
10017   if (!ValueEqualPHIs.insert(PN))
10018     return true;
10019   
10020   // Don't scan crazily complex things.
10021   if (ValueEqualPHIs.size() == 16)
10022     return false;
10023  
10024   // Scan the operands to see if they are either phi nodes or are equal to
10025   // the value.
10026   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10027     Value *Op = PN->getIncomingValue(i);
10028     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10029       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10030         return false;
10031     } else if (Op != NonPhiInVal)
10032       return false;
10033   }
10034   
10035   return true;
10036 }
10037
10038
10039 // PHINode simplification
10040 //
10041 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10042   // If LCSSA is around, don't mess with Phi nodes
10043   if (MustPreserveLCSSA) return 0;
10044   
10045   if (Value *V = PN.hasConstantValue())
10046     return ReplaceInstUsesWith(PN, V);
10047
10048   // If all PHI operands are the same operation, pull them through the PHI,
10049   // reducing code size.
10050   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10051       PN.getIncomingValue(0)->hasOneUse())
10052     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10053       return Result;
10054
10055   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10056   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10057   // PHI)... break the cycle.
10058   if (PN.hasOneUse()) {
10059     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10060     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10061       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10062       PotentiallyDeadPHIs.insert(&PN);
10063       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10064         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10065     }
10066    
10067     // If this phi has a single use, and if that use just computes a value for
10068     // the next iteration of a loop, delete the phi.  This occurs with unused
10069     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10070     // common case here is good because the only other things that catch this
10071     // are induction variable analysis (sometimes) and ADCE, which is only run
10072     // late.
10073     if (PHIUser->hasOneUse() &&
10074         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10075         PHIUser->use_back() == &PN) {
10076       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10077     }
10078   }
10079
10080   // We sometimes end up with phi cycles that non-obviously end up being the
10081   // same value, for example:
10082   //   z = some value; x = phi (y, z); y = phi (x, z)
10083   // where the phi nodes don't necessarily need to be in the same block.  Do a
10084   // quick check to see if the PHI node only contains a single non-phi value, if
10085   // so, scan to see if the phi cycle is actually equal to that value.
10086   {
10087     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10088     // Scan for the first non-phi operand.
10089     while (InValNo != NumOperandVals && 
10090            isa<PHINode>(PN.getIncomingValue(InValNo)))
10091       ++InValNo;
10092
10093     if (InValNo != NumOperandVals) {
10094       Value *NonPhiInVal = PN.getOperand(InValNo);
10095       
10096       // Scan the rest of the operands to see if there are any conflicts, if so
10097       // there is no need to recursively scan other phis.
10098       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10099         Value *OpVal = PN.getIncomingValue(InValNo);
10100         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10101           break;
10102       }
10103       
10104       // If we scanned over all operands, then we have one unique value plus
10105       // phi values.  Scan PHI nodes to see if they all merge in each other or
10106       // the value.
10107       if (InValNo == NumOperandVals) {
10108         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10109         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10110           return ReplaceInstUsesWith(PN, NonPhiInVal);
10111       }
10112     }
10113   }
10114   return 0;
10115 }
10116
10117 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10118                                    Instruction *InsertPoint,
10119                                    InstCombiner *IC) {
10120   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10121   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10122   // We must cast correctly to the pointer type. Ensure that we
10123   // sign extend the integer value if it is smaller as this is
10124   // used for address computation.
10125   Instruction::CastOps opcode = 
10126      (VTySize < PtrSize ? Instruction::SExt :
10127       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10128   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10129 }
10130
10131
10132 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10133   Value *PtrOp = GEP.getOperand(0);
10134   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10135   // If so, eliminate the noop.
10136   if (GEP.getNumOperands() == 1)
10137     return ReplaceInstUsesWith(GEP, PtrOp);
10138
10139   if (isa<UndefValue>(GEP.getOperand(0)))
10140     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10141
10142   bool HasZeroPointerIndex = false;
10143   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10144     HasZeroPointerIndex = C->isNullValue();
10145
10146   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10147     return ReplaceInstUsesWith(GEP, PtrOp);
10148
10149   // Eliminate unneeded casts for indices.
10150   bool MadeChange = false;
10151   
10152   gep_type_iterator GTI = gep_type_begin(GEP);
10153   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
10154     if (isa<SequentialType>(*GTI)) {
10155       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
10156         if (CI->getOpcode() == Instruction::ZExt ||
10157             CI->getOpcode() == Instruction::SExt) {
10158           const Type *SrcTy = CI->getOperand(0)->getType();
10159           // We can eliminate a cast from i32 to i64 iff the target 
10160           // is a 32-bit pointer target.
10161           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10162             MadeChange = true;
10163             GEP.setOperand(i, CI->getOperand(0));
10164           }
10165         }
10166       }
10167       // If we are using a wider index than needed for this platform, shrink it
10168       // to what we need.  If the incoming value needs a cast instruction,
10169       // insert it.  This explicit cast can make subsequent optimizations more
10170       // obvious.
10171       Value *Op = GEP.getOperand(i);
10172       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10173         if (Constant *C = dyn_cast<Constant>(Op)) {
10174           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
10175           MadeChange = true;
10176         } else {
10177           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10178                                 GEP);
10179           GEP.setOperand(i, Op);
10180           MadeChange = true;
10181         }
10182       }
10183     }
10184   }
10185   if (MadeChange) return &GEP;
10186
10187   // If this GEP instruction doesn't move the pointer, and if the input operand
10188   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10189   // real input to the dest type.
10190   if (GEP.hasAllZeroIndices()) {
10191     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10192       // If the bitcast is of an allocation, and the allocation will be
10193       // converted to match the type of the cast, don't touch this.
10194       if (isa<AllocationInst>(BCI->getOperand(0))) {
10195         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10196         if (Instruction *I = visitBitCast(*BCI)) {
10197           if (I != BCI) {
10198             I->takeName(BCI);
10199             BCI->getParent()->getInstList().insert(BCI, I);
10200             ReplaceInstUsesWith(*BCI, I);
10201           }
10202           return &GEP;
10203         }
10204       }
10205       return new BitCastInst(BCI->getOperand(0), GEP.getType());
10206     }
10207   }
10208   
10209   // Combine Indices - If the source pointer to this getelementptr instruction
10210   // is a getelementptr instruction, combine the indices of the two
10211   // getelementptr instructions into a single instruction.
10212   //
10213   SmallVector<Value*, 8> SrcGEPOperands;
10214   if (User *Src = dyn_castGetElementPtr(PtrOp))
10215     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10216
10217   if (!SrcGEPOperands.empty()) {
10218     // Note that if our source is a gep chain itself that we wait for that
10219     // chain to be resolved before we perform this transformation.  This
10220     // avoids us creating a TON of code in some cases.
10221     //
10222     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10223         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10224       return 0;   // Wait until our source is folded to completion.
10225
10226     SmallVector<Value*, 8> Indices;
10227
10228     // Find out whether the last index in the source GEP is a sequential idx.
10229     bool EndsWithSequential = false;
10230     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10231            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10232       EndsWithSequential = !isa<StructType>(*I);
10233
10234     // Can we combine the two pointer arithmetics offsets?
10235     if (EndsWithSequential) {
10236       // Replace: gep (gep %P, long B), long A, ...
10237       // With:    T = long A+B; gep %P, T, ...
10238       //
10239       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10240       if (SO1 == Constant::getNullValue(SO1->getType())) {
10241         Sum = GO1;
10242       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10243         Sum = SO1;
10244       } else {
10245         // If they aren't the same type, convert both to an integer of the
10246         // target's pointer size.
10247         if (SO1->getType() != GO1->getType()) {
10248           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10249             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10250           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10251             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10252           } else {
10253             unsigned PS = TD->getPointerSizeInBits();
10254             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10255               // Convert GO1 to SO1's type.
10256               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10257
10258             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10259               // Convert SO1 to GO1's type.
10260               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10261             } else {
10262               const Type *PT = TD->getIntPtrType();
10263               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10264               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10265             }
10266           }
10267         }
10268         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10269           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10270         else {
10271           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10272           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10273         }
10274       }
10275
10276       // Recycle the GEP we already have if possible.
10277       if (SrcGEPOperands.size() == 2) {
10278         GEP.setOperand(0, SrcGEPOperands[0]);
10279         GEP.setOperand(1, Sum);
10280         return &GEP;
10281       } else {
10282         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10283                        SrcGEPOperands.end()-1);
10284         Indices.push_back(Sum);
10285         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10286       }
10287     } else if (isa<Constant>(*GEP.idx_begin()) &&
10288                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10289                SrcGEPOperands.size() != 1) {
10290       // Otherwise we can do the fold if the first index of the GEP is a zero
10291       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10292                      SrcGEPOperands.end());
10293       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10294     }
10295
10296     if (!Indices.empty())
10297       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10298                                        Indices.end(), GEP.getName());
10299
10300   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10301     // GEP of global variable.  If all of the indices for this GEP are
10302     // constants, we can promote this to a constexpr instead of an instruction.
10303
10304     // Scan for nonconstants...
10305     SmallVector<Constant*, 8> Indices;
10306     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10307     for (; I != E && isa<Constant>(*I); ++I)
10308       Indices.push_back(cast<Constant>(*I));
10309
10310     if (I == E) {  // If they are all constants...
10311       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10312                                                     &Indices[0],Indices.size());
10313
10314       // Replace all uses of the GEP with the new constexpr...
10315       return ReplaceInstUsesWith(GEP, CE);
10316     }
10317   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10318     if (!isa<PointerType>(X->getType())) {
10319       // Not interesting.  Source pointer must be a cast from pointer.
10320     } else if (HasZeroPointerIndex) {
10321       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10322       // into     : GEP [10 x i8]* X, i32 0, ...
10323       //
10324       // This occurs when the program declares an array extern like "int X[];"
10325       //
10326       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10327       const PointerType *XTy = cast<PointerType>(X->getType());
10328       if (const ArrayType *XATy =
10329           dyn_cast<ArrayType>(XTy->getElementType()))
10330         if (const ArrayType *CATy =
10331             dyn_cast<ArrayType>(CPTy->getElementType()))
10332           if (CATy->getElementType() == XATy->getElementType()) {
10333             // At this point, we know that the cast source type is a pointer
10334             // to an array of the same type as the destination pointer
10335             // array.  Because the array type is never stepped over (there
10336             // is a leading zero) we can fold the cast into this GEP.
10337             GEP.setOperand(0, X);
10338             return &GEP;
10339           }
10340     } else if (GEP.getNumOperands() == 2) {
10341       // Transform things like:
10342       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10343       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10344       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10345       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10346       if (isa<ArrayType>(SrcElTy) &&
10347           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10348           TD->getABITypeSize(ResElTy)) {
10349         Value *Idx[2];
10350         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10351         Idx[1] = GEP.getOperand(1);
10352         Value *V = InsertNewInstBefore(
10353                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10354         // V and GEP are both pointer types --> BitCast
10355         return new BitCastInst(V, GEP.getType());
10356       }
10357       
10358       // Transform things like:
10359       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10360       //   (where tmp = 8*tmp2) into:
10361       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10362       
10363       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10364         uint64_t ArrayEltSize =
10365             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10366         
10367         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10368         // allow either a mul, shift, or constant here.
10369         Value *NewIdx = 0;
10370         ConstantInt *Scale = 0;
10371         if (ArrayEltSize == 1) {
10372           NewIdx = GEP.getOperand(1);
10373           Scale = ConstantInt::get(NewIdx->getType(), 1);
10374         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10375           NewIdx = ConstantInt::get(CI->getType(), 1);
10376           Scale = CI;
10377         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10378           if (Inst->getOpcode() == Instruction::Shl &&
10379               isa<ConstantInt>(Inst->getOperand(1))) {
10380             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10381             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10382             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10383             NewIdx = Inst->getOperand(0);
10384           } else if (Inst->getOpcode() == Instruction::Mul &&
10385                      isa<ConstantInt>(Inst->getOperand(1))) {
10386             Scale = cast<ConstantInt>(Inst->getOperand(1));
10387             NewIdx = Inst->getOperand(0);
10388           }
10389         }
10390         
10391         // If the index will be to exactly the right offset with the scale taken
10392         // out, perform the transformation. Note, we don't know whether Scale is
10393         // signed or not. We'll use unsigned version of division/modulo
10394         // operation after making sure Scale doesn't have the sign bit set.
10395         if (Scale && Scale->getSExtValue() >= 0LL &&
10396             Scale->getZExtValue() % ArrayEltSize == 0) {
10397           Scale = ConstantInt::get(Scale->getType(),
10398                                    Scale->getZExtValue() / ArrayEltSize);
10399           if (Scale->getZExtValue() != 1) {
10400             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10401                                                        false /*ZExt*/);
10402             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10403             NewIdx = InsertNewInstBefore(Sc, GEP);
10404           }
10405
10406           // Insert the new GEP instruction.
10407           Value *Idx[2];
10408           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10409           Idx[1] = NewIdx;
10410           Instruction *NewGEP =
10411             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10412           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10413           // The NewGEP must be pointer typed, so must the old one -> BitCast
10414           return new BitCastInst(NewGEP, GEP.getType());
10415         }
10416       }
10417     }
10418   }
10419
10420   return 0;
10421 }
10422
10423 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10424   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10425   if (AI.isArrayAllocation()) {  // Check C != 1
10426     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10427       const Type *NewTy = 
10428         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10429       AllocationInst *New = 0;
10430
10431       // Create and insert the replacement instruction...
10432       if (isa<MallocInst>(AI))
10433         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10434       else {
10435         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10436         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10437       }
10438
10439       InsertNewInstBefore(New, AI);
10440
10441       // Scan to the end of the allocation instructions, to skip over a block of
10442       // allocas if possible...
10443       //
10444       BasicBlock::iterator It = New;
10445       while (isa<AllocationInst>(*It)) ++It;
10446
10447       // Now that I is pointing to the first non-allocation-inst in the block,
10448       // insert our getelementptr instruction...
10449       //
10450       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10451       Value *Idx[2];
10452       Idx[0] = NullIdx;
10453       Idx[1] = NullIdx;
10454       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10455                                            New->getName()+".sub", It);
10456
10457       // Now make everything use the getelementptr instead of the original
10458       // allocation.
10459       return ReplaceInstUsesWith(AI, V);
10460     } else if (isa<UndefValue>(AI.getArraySize())) {
10461       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10462     }
10463   }
10464
10465   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10466   // Note that we only do this for alloca's, because malloc should allocate and
10467   // return a unique pointer, even for a zero byte allocation.
10468   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10469       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10470     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10471
10472   return 0;
10473 }
10474
10475 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10476   Value *Op = FI.getOperand(0);
10477
10478   // free undef -> unreachable.
10479   if (isa<UndefValue>(Op)) {
10480     // Insert a new store to null because we cannot modify the CFG here.
10481     new StoreInst(ConstantInt::getTrue(),
10482                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10483     return EraseInstFromFunction(FI);
10484   }
10485   
10486   // If we have 'free null' delete the instruction.  This can happen in stl code
10487   // when lots of inlining happens.
10488   if (isa<ConstantPointerNull>(Op))
10489     return EraseInstFromFunction(FI);
10490   
10491   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10492   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10493     FI.setOperand(0, CI->getOperand(0));
10494     return &FI;
10495   }
10496   
10497   // Change free (gep X, 0,0,0,0) into free(X)
10498   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10499     if (GEPI->hasAllZeroIndices()) {
10500       AddToWorkList(GEPI);
10501       FI.setOperand(0, GEPI->getOperand(0));
10502       return &FI;
10503     }
10504   }
10505   
10506   // Change free(malloc) into nothing, if the malloc has a single use.
10507   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10508     if (MI->hasOneUse()) {
10509       EraseInstFromFunction(FI);
10510       return EraseInstFromFunction(*MI);
10511     }
10512
10513   return 0;
10514 }
10515
10516
10517 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10518 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10519                                         const TargetData *TD) {
10520   User *CI = cast<User>(LI.getOperand(0));
10521   Value *CastOp = CI->getOperand(0);
10522
10523   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10524     // Instead of loading constant c string, use corresponding integer value
10525     // directly if string length is small enough.
10526     const std::string &Str = CE->getOperand(0)->getStringValue();
10527     if (!Str.empty()) {
10528       unsigned len = Str.length();
10529       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10530       unsigned numBits = Ty->getPrimitiveSizeInBits();
10531       // Replace LI with immediate integer store.
10532       if ((numBits >> 3) == len + 1) {
10533         APInt StrVal(numBits, 0);
10534         APInt SingleChar(numBits, 0);
10535         if (TD->isLittleEndian()) {
10536           for (signed i = len-1; i >= 0; i--) {
10537             SingleChar = (uint64_t) Str[i];
10538             StrVal = (StrVal << 8) | SingleChar;
10539           }
10540         } else {
10541           for (unsigned i = 0; i < len; i++) {
10542             SingleChar = (uint64_t) Str[i];
10543             StrVal = (StrVal << 8) | SingleChar;
10544           }
10545           // Append NULL at the end.
10546           SingleChar = 0;
10547           StrVal = (StrVal << 8) | SingleChar;
10548         }
10549         Value *NL = ConstantInt::get(StrVal);
10550         return IC.ReplaceInstUsesWith(LI, NL);
10551       }
10552     }
10553   }
10554
10555   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10556   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10557     const Type *SrcPTy = SrcTy->getElementType();
10558
10559     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10560          isa<VectorType>(DestPTy)) {
10561       // If the source is an array, the code below will not succeed.  Check to
10562       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10563       // constants.
10564       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10565         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10566           if (ASrcTy->getNumElements() != 0) {
10567             Value *Idxs[2];
10568             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10569             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10570             SrcTy = cast<PointerType>(CastOp->getType());
10571             SrcPTy = SrcTy->getElementType();
10572           }
10573
10574       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10575             isa<VectorType>(SrcPTy)) &&
10576           // Do not allow turning this into a load of an integer, which is then
10577           // casted to a pointer, this pessimizes pointer analysis a lot.
10578           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10579           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10580                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10581
10582         // Okay, we are casting from one integer or pointer type to another of
10583         // the same size.  Instead of casting the pointer before the load, cast
10584         // the result of the loaded value.
10585         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10586                                                              CI->getName(),
10587                                                          LI.isVolatile()),LI);
10588         // Now cast the result of the load.
10589         return new BitCastInst(NewLoad, LI.getType());
10590       }
10591     }
10592   }
10593   return 0;
10594 }
10595
10596 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10597 /// from this value cannot trap.  If it is not obviously safe to load from the
10598 /// specified pointer, we do a quick local scan of the basic block containing
10599 /// ScanFrom, to determine if the address is already accessed.
10600 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10601   // If it is an alloca it is always safe to load from.
10602   if (isa<AllocaInst>(V)) return true;
10603
10604   // If it is a global variable it is mostly safe to load from.
10605   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10606     // Don't try to evaluate aliases.  External weak GV can be null.
10607     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10608
10609   // Otherwise, be a little bit agressive by scanning the local block where we
10610   // want to check to see if the pointer is already being loaded or stored
10611   // from/to.  If so, the previous load or store would have already trapped,
10612   // so there is no harm doing an extra load (also, CSE will later eliminate
10613   // the load entirely).
10614   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10615
10616   while (BBI != E) {
10617     --BBI;
10618
10619     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10620       if (LI->getOperand(0) == V) return true;
10621     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10622       if (SI->getOperand(1) == V) return true;
10623
10624   }
10625   return false;
10626 }
10627
10628 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10629 /// until we find the underlying object a pointer is referring to or something
10630 /// we don't understand.  Note that the returned pointer may be offset from the
10631 /// input, because we ignore GEP indices.
10632 static Value *GetUnderlyingObject(Value *Ptr) {
10633   while (1) {
10634     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10635       if (CE->getOpcode() == Instruction::BitCast ||
10636           CE->getOpcode() == Instruction::GetElementPtr)
10637         Ptr = CE->getOperand(0);
10638       else
10639         return Ptr;
10640     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10641       Ptr = BCI->getOperand(0);
10642     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10643       Ptr = GEP->getOperand(0);
10644     } else {
10645       return Ptr;
10646     }
10647   }
10648 }
10649
10650 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10651   Value *Op = LI.getOperand(0);
10652
10653   // Attempt to improve the alignment.
10654   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10655   if (KnownAlign >
10656       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10657                                 LI.getAlignment()))
10658     LI.setAlignment(KnownAlign);
10659
10660   // load (cast X) --> cast (load X) iff safe
10661   if (isa<CastInst>(Op))
10662     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10663       return Res;
10664
10665   // None of the following transforms are legal for volatile loads.
10666   if (LI.isVolatile()) return 0;
10667   
10668   if (&LI.getParent()->front() != &LI) {
10669     BasicBlock::iterator BBI = &LI; --BBI;
10670     // If the instruction immediately before this is a store to the same
10671     // address, do a simple form of store->load forwarding.
10672     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10673       if (SI->getOperand(1) == LI.getOperand(0))
10674         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10675     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10676       if (LIB->getOperand(0) == LI.getOperand(0))
10677         return ReplaceInstUsesWith(LI, LIB);
10678   }
10679
10680   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10681     const Value *GEPI0 = GEPI->getOperand(0);
10682     // TODO: Consider a target hook for valid address spaces for this xform.
10683     if (isa<ConstantPointerNull>(GEPI0) &&
10684         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10685       // Insert a new store to null instruction before the load to indicate
10686       // that this code is not reachable.  We do this instead of inserting
10687       // an unreachable instruction directly because we cannot modify the
10688       // CFG.
10689       new StoreInst(UndefValue::get(LI.getType()),
10690                     Constant::getNullValue(Op->getType()), &LI);
10691       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10692     }
10693   } 
10694
10695   if (Constant *C = dyn_cast<Constant>(Op)) {
10696     // load null/undef -> undef
10697     // TODO: Consider a target hook for valid address spaces for this xform.
10698     if (isa<UndefValue>(C) || (C->isNullValue() && 
10699         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10700       // Insert a new store to null instruction before the load to indicate that
10701       // this code is not reachable.  We do this instead of inserting an
10702       // unreachable instruction directly because we cannot modify the 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     // Instcombine load (constant global) into the value loaded.
10709     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10710       if (GV->isConstant() && !GV->isDeclaration())
10711         return ReplaceInstUsesWith(LI, GV->getInitializer());
10712
10713     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10714     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10715       if (CE->getOpcode() == Instruction::GetElementPtr) {
10716         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10717           if (GV->isConstant() && !GV->isDeclaration())
10718             if (Constant *V = 
10719                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10720               return ReplaceInstUsesWith(LI, V);
10721         if (CE->getOperand(0)->isNullValue()) {
10722           // Insert a new store to null instruction before the load to indicate
10723           // that this code is not reachable.  We do this instead of inserting
10724           // an unreachable instruction directly because we cannot modify the
10725           // CFG.
10726           new StoreInst(UndefValue::get(LI.getType()),
10727                         Constant::getNullValue(Op->getType()), &LI);
10728           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10729         }
10730
10731       } else if (CE->isCast()) {
10732         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10733           return Res;
10734       }
10735     }
10736   }
10737     
10738   // If this load comes from anywhere in a constant global, and if the global
10739   // is all undef or zero, we know what it loads.
10740   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10741     if (GV->isConstant() && GV->hasInitializer()) {
10742       if (GV->getInitializer()->isNullValue())
10743         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10744       else if (isa<UndefValue>(GV->getInitializer()))
10745         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10746     }
10747   }
10748
10749   if (Op->hasOneUse()) {
10750     // Change select and PHI nodes to select values instead of addresses: this
10751     // helps alias analysis out a lot, allows many others simplifications, and
10752     // exposes redundancy in the code.
10753     //
10754     // Note that we cannot do the transformation unless we know that the
10755     // introduced loads cannot trap!  Something like this is valid as long as
10756     // the condition is always false: load (select bool %C, int* null, int* %G),
10757     // but it would not be valid if we transformed it to load from null
10758     // unconditionally.
10759     //
10760     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10761       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10762       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10763           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10764         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10765                                      SI->getOperand(1)->getName()+".val"), LI);
10766         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10767                                      SI->getOperand(2)->getName()+".val"), LI);
10768         return SelectInst::Create(SI->getCondition(), V1, V2);
10769       }
10770
10771       // load (select (cond, null, P)) -> load P
10772       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10773         if (C->isNullValue()) {
10774           LI.setOperand(0, SI->getOperand(2));
10775           return &LI;
10776         }
10777
10778       // load (select (cond, P, null)) -> load P
10779       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10780         if (C->isNullValue()) {
10781           LI.setOperand(0, SI->getOperand(1));
10782           return &LI;
10783         }
10784     }
10785   }
10786   return 0;
10787 }
10788
10789 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10790 /// when possible.
10791 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10792   User *CI = cast<User>(SI.getOperand(1));
10793   Value *CastOp = CI->getOperand(0);
10794
10795   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10796   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10797     const Type *SrcPTy = SrcTy->getElementType();
10798
10799     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10800       // If the source is an array, the code below will not succeed.  Check to
10801       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10802       // constants.
10803       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10804         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10805           if (ASrcTy->getNumElements() != 0) {
10806             Value* Idxs[2];
10807             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10808             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10809             SrcTy = cast<PointerType>(CastOp->getType());
10810             SrcPTy = SrcTy->getElementType();
10811           }
10812
10813       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10814           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10815                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10816
10817         // Okay, we are casting from one integer or pointer type to another of
10818         // the same size.  Instead of casting the pointer before 
10819         // the store, cast the value to be stored.
10820         Value *NewCast;
10821         Value *SIOp0 = SI.getOperand(0);
10822         Instruction::CastOps opcode = Instruction::BitCast;
10823         const Type* CastSrcTy = SIOp0->getType();
10824         const Type* CastDstTy = SrcPTy;
10825         if (isa<PointerType>(CastDstTy)) {
10826           if (CastSrcTy->isInteger())
10827             opcode = Instruction::IntToPtr;
10828         } else if (isa<IntegerType>(CastDstTy)) {
10829           if (isa<PointerType>(SIOp0->getType()))
10830             opcode = Instruction::PtrToInt;
10831         }
10832         if (Constant *C = dyn_cast<Constant>(SIOp0))
10833           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10834         else
10835           NewCast = IC.InsertNewInstBefore(
10836             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10837             SI);
10838         return new StoreInst(NewCast, CastOp);
10839       }
10840     }
10841   }
10842   return 0;
10843 }
10844
10845 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10846   Value *Val = SI.getOperand(0);
10847   Value *Ptr = SI.getOperand(1);
10848
10849   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10850     EraseInstFromFunction(SI);
10851     ++NumCombined;
10852     return 0;
10853   }
10854   
10855   // If the RHS is an alloca with a single use, zapify the store, making the
10856   // alloca dead.
10857   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10858     if (isa<AllocaInst>(Ptr)) {
10859       EraseInstFromFunction(SI);
10860       ++NumCombined;
10861       return 0;
10862     }
10863     
10864     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10865       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10866           GEP->getOperand(0)->hasOneUse()) {
10867         EraseInstFromFunction(SI);
10868         ++NumCombined;
10869         return 0;
10870       }
10871   }
10872
10873   // Attempt to improve the alignment.
10874   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10875   if (KnownAlign >
10876       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10877                                 SI.getAlignment()))
10878     SI.setAlignment(KnownAlign);
10879
10880   // Do really simple DSE, to catch cases where there are several consequtive
10881   // stores to the same location, separated by a few arithmetic operations. This
10882   // situation often occurs with bitfield accesses.
10883   BasicBlock::iterator BBI = &SI;
10884   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10885        --ScanInsts) {
10886     --BBI;
10887     
10888     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10889       // Prev store isn't volatile, and stores to the same location?
10890       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10891         ++NumDeadStore;
10892         ++BBI;
10893         EraseInstFromFunction(*PrevSI);
10894         continue;
10895       }
10896       break;
10897     }
10898     
10899     // If this is a load, we have to stop.  However, if the loaded value is from
10900     // the pointer we're loading and is producing the pointer we're storing,
10901     // then *this* store is dead (X = load P; store X -> P).
10902     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10903       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10904         EraseInstFromFunction(SI);
10905         ++NumCombined;
10906         return 0;
10907       }
10908       // Otherwise, this is a load from some other location.  Stores before it
10909       // may not be dead.
10910       break;
10911     }
10912     
10913     // Don't skip over loads or things that can modify memory.
10914     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10915       break;
10916   }
10917   
10918   
10919   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10920
10921   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10922   if (isa<ConstantPointerNull>(Ptr)) {
10923     if (!isa<UndefValue>(Val)) {
10924       SI.setOperand(0, UndefValue::get(Val->getType()));
10925       if (Instruction *U = dyn_cast<Instruction>(Val))
10926         AddToWorkList(U);  // Dropped a use.
10927       ++NumCombined;
10928     }
10929     return 0;  // Do not modify these!
10930   }
10931
10932   // store undef, Ptr -> noop
10933   if (isa<UndefValue>(Val)) {
10934     EraseInstFromFunction(SI);
10935     ++NumCombined;
10936     return 0;
10937   }
10938
10939   // If the pointer destination is a cast, see if we can fold the cast into the
10940   // source instead.
10941   if (isa<CastInst>(Ptr))
10942     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10943       return Res;
10944   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10945     if (CE->isCast())
10946       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10947         return Res;
10948
10949   
10950   // If this store is the last instruction in the basic block, and if the block
10951   // ends with an unconditional branch, try to move it to the successor block.
10952   BBI = &SI; ++BBI;
10953   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10954     if (BI->isUnconditional())
10955       if (SimplifyStoreAtEndOfBlock(SI))
10956         return 0;  // xform done!
10957   
10958   return 0;
10959 }
10960
10961 /// SimplifyStoreAtEndOfBlock - Turn things like:
10962 ///   if () { *P = v1; } else { *P = v2 }
10963 /// into a phi node with a store in the successor.
10964 ///
10965 /// Simplify things like:
10966 ///   *P = v1; if () { *P = v2; }
10967 /// into a phi node with a store in the successor.
10968 ///
10969 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10970   BasicBlock *StoreBB = SI.getParent();
10971   
10972   // Check to see if the successor block has exactly two incoming edges.  If
10973   // so, see if the other predecessor contains a store to the same location.
10974   // if so, insert a PHI node (if needed) and move the stores down.
10975   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10976   
10977   // Determine whether Dest has exactly two predecessors and, if so, compute
10978   // the other predecessor.
10979   pred_iterator PI = pred_begin(DestBB);
10980   BasicBlock *OtherBB = 0;
10981   if (*PI != StoreBB)
10982     OtherBB = *PI;
10983   ++PI;
10984   if (PI == pred_end(DestBB))
10985     return false;
10986   
10987   if (*PI != StoreBB) {
10988     if (OtherBB)
10989       return false;
10990     OtherBB = *PI;
10991   }
10992   if (++PI != pred_end(DestBB))
10993     return false;
10994   
10995   
10996   // Verify that the other block ends in a branch and is not otherwise empty.
10997   BasicBlock::iterator BBI = OtherBB->getTerminator();
10998   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10999   if (!OtherBr || BBI == OtherBB->begin())
11000     return false;
11001   
11002   // If the other block ends in an unconditional branch, check for the 'if then
11003   // else' case.  there is an instruction before the branch.
11004   StoreInst *OtherStore = 0;
11005   if (OtherBr->isUnconditional()) {
11006     // If this isn't a store, or isn't a store to the same location, bail out.
11007     --BBI;
11008     OtherStore = dyn_cast<StoreInst>(BBI);
11009     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11010       return false;
11011   } else {
11012     // Otherwise, the other block ended with a conditional branch. If one of the
11013     // destinations is StoreBB, then we have the if/then case.
11014     if (OtherBr->getSuccessor(0) != StoreBB && 
11015         OtherBr->getSuccessor(1) != StoreBB)
11016       return false;
11017     
11018     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11019     // if/then triangle.  See if there is a store to the same ptr as SI that
11020     // lives in OtherBB.
11021     for (;; --BBI) {
11022       // Check to see if we find the matching store.
11023       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11024         if (OtherStore->getOperand(1) != SI.getOperand(1))
11025           return false;
11026         break;
11027       }
11028       // If we find something that may be using the stored value, or if we run
11029       // out of instructions, we can't do the xform.
11030       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11031           BBI == OtherBB->begin())
11032         return false;
11033     }
11034     
11035     // In order to eliminate the store in OtherBr, we have to
11036     // make sure nothing reads the stored value in StoreBB.
11037     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11038       // FIXME: This should really be AA driven.
11039       if (isa<LoadInst>(I) || I->mayWriteToMemory())
11040         return false;
11041     }
11042   }
11043   
11044   // Insert a PHI node now if we need it.
11045   Value *MergedVal = OtherStore->getOperand(0);
11046   if (MergedVal != SI.getOperand(0)) {
11047     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11048     PN->reserveOperandSpace(2);
11049     PN->addIncoming(SI.getOperand(0), SI.getParent());
11050     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11051     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11052   }
11053   
11054   // Advance to a place where it is safe to insert the new store and
11055   // insert it.
11056   BBI = DestBB->begin();
11057   while (isa<PHINode>(BBI)) ++BBI;
11058   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11059                                     OtherStore->isVolatile()), *BBI);
11060   
11061   // Nuke the old stores.
11062   EraseInstFromFunction(SI);
11063   EraseInstFromFunction(*OtherStore);
11064   ++NumCombined;
11065   return true;
11066 }
11067
11068
11069 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11070   // Change br (not X), label True, label False to: br X, label False, True
11071   Value *X = 0;
11072   BasicBlock *TrueDest;
11073   BasicBlock *FalseDest;
11074   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11075       !isa<Constant>(X)) {
11076     // Swap Destinations and condition...
11077     BI.setCondition(X);
11078     BI.setSuccessor(0, FalseDest);
11079     BI.setSuccessor(1, TrueDest);
11080     return &BI;
11081   }
11082
11083   // Cannonicalize fcmp_one -> fcmp_oeq
11084   FCmpInst::Predicate FPred; Value *Y;
11085   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11086                              TrueDest, FalseDest)))
11087     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11088          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11089       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11090       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11091       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11092       NewSCC->takeName(I);
11093       // Swap Destinations and condition...
11094       BI.setCondition(NewSCC);
11095       BI.setSuccessor(0, FalseDest);
11096       BI.setSuccessor(1, TrueDest);
11097       RemoveFromWorkList(I);
11098       I->eraseFromParent();
11099       AddToWorkList(NewSCC);
11100       return &BI;
11101     }
11102
11103   // Cannonicalize icmp_ne -> icmp_eq
11104   ICmpInst::Predicate IPred;
11105   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11106                       TrueDest, FalseDest)))
11107     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11108          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11109          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11110       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11111       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11112       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11113       NewSCC->takeName(I);
11114       // Swap Destinations and condition...
11115       BI.setCondition(NewSCC);
11116       BI.setSuccessor(0, FalseDest);
11117       BI.setSuccessor(1, TrueDest);
11118       RemoveFromWorkList(I);
11119       I->eraseFromParent();;
11120       AddToWorkList(NewSCC);
11121       return &BI;
11122     }
11123
11124   return 0;
11125 }
11126
11127 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11128   Value *Cond = SI.getCondition();
11129   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11130     if (I->getOpcode() == Instruction::Add)
11131       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11132         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11133         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11134           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11135                                                 AddRHS));
11136         SI.setOperand(0, I->getOperand(0));
11137         AddToWorkList(I);
11138         return &SI;
11139       }
11140   }
11141   return 0;
11142 }
11143
11144 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11145 /// is to leave as a vector operation.
11146 static bool CheapToScalarize(Value *V, bool isConstant) {
11147   if (isa<ConstantAggregateZero>(V)) 
11148     return true;
11149   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11150     if (isConstant) return true;
11151     // If all elts are the same, we can extract.
11152     Constant *Op0 = C->getOperand(0);
11153     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11154       if (C->getOperand(i) != Op0)
11155         return false;
11156     return true;
11157   }
11158   Instruction *I = dyn_cast<Instruction>(V);
11159   if (!I) return false;
11160   
11161   // Insert element gets simplified to the inserted element or is deleted if
11162   // this is constant idx extract element and its a constant idx insertelt.
11163   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11164       isa<ConstantInt>(I->getOperand(2)))
11165     return true;
11166   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11167     return true;
11168   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11169     if (BO->hasOneUse() &&
11170         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11171          CheapToScalarize(BO->getOperand(1), isConstant)))
11172       return true;
11173   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11174     if (CI->hasOneUse() &&
11175         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11176          CheapToScalarize(CI->getOperand(1), isConstant)))
11177       return true;
11178   
11179   return false;
11180 }
11181
11182 /// Read and decode a shufflevector mask.
11183 ///
11184 /// It turns undef elements into values that are larger than the number of
11185 /// elements in the input.
11186 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11187   unsigned NElts = SVI->getType()->getNumElements();
11188   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11189     return std::vector<unsigned>(NElts, 0);
11190   if (isa<UndefValue>(SVI->getOperand(2)))
11191     return std::vector<unsigned>(NElts, 2*NElts);
11192
11193   std::vector<unsigned> Result;
11194   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11195   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11196     if (isa<UndefValue>(CP->getOperand(i)))
11197       Result.push_back(NElts*2);  // undef -> 8
11198     else
11199       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
11200   return Result;
11201 }
11202
11203 /// FindScalarElement - Given a vector and an element number, see if the scalar
11204 /// value is already around as a register, for example if it were inserted then
11205 /// extracted from the vector.
11206 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11207   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11208   const VectorType *PTy = cast<VectorType>(V->getType());
11209   unsigned Width = PTy->getNumElements();
11210   if (EltNo >= Width)  // Out of range access.
11211     return UndefValue::get(PTy->getElementType());
11212   
11213   if (isa<UndefValue>(V))
11214     return UndefValue::get(PTy->getElementType());
11215   else if (isa<ConstantAggregateZero>(V))
11216     return Constant::getNullValue(PTy->getElementType());
11217   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11218     return CP->getOperand(EltNo);
11219   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11220     // If this is an insert to a variable element, we don't know what it is.
11221     if (!isa<ConstantInt>(III->getOperand(2))) 
11222       return 0;
11223     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11224     
11225     // If this is an insert to the element we are looking for, return the
11226     // inserted value.
11227     if (EltNo == IIElt) 
11228       return III->getOperand(1);
11229     
11230     // Otherwise, the insertelement doesn't modify the value, recurse on its
11231     // vector input.
11232     return FindScalarElement(III->getOperand(0), EltNo);
11233   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11234     unsigned InEl = getShuffleMask(SVI)[EltNo];
11235     if (InEl < Width)
11236       return FindScalarElement(SVI->getOperand(0), InEl);
11237     else if (InEl < Width*2)
11238       return FindScalarElement(SVI->getOperand(1), InEl - Width);
11239     else
11240       return UndefValue::get(PTy->getElementType());
11241   }
11242   
11243   // Otherwise, we don't know.
11244   return 0;
11245 }
11246
11247 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11248
11249   // If vector val is undef, replace extract with scalar undef.
11250   if (isa<UndefValue>(EI.getOperand(0)))
11251     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11252
11253   // If vector val is constant 0, replace extract with scalar 0.
11254   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11255     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11256   
11257   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11258     // If vector val is constant with uniform operands, replace EI
11259     // with that operand
11260     Constant *op0 = C->getOperand(0);
11261     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11262       if (C->getOperand(i) != op0) {
11263         op0 = 0; 
11264         break;
11265       }
11266     if (op0)
11267       return ReplaceInstUsesWith(EI, op0);
11268   }
11269   
11270   // If extracting a specified index from the vector, see if we can recursively
11271   // find a previously computed scalar that was inserted into the vector.
11272   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11273     unsigned IndexVal = IdxC->getZExtValue();
11274     unsigned VectorWidth = 
11275       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11276       
11277     // If this is extracting an invalid index, turn this into undef, to avoid
11278     // crashing the code below.
11279     if (IndexVal >= VectorWidth)
11280       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11281     
11282     // This instruction only demands the single element from the input vector.
11283     // If the input vector has a single use, simplify it based on this use
11284     // property.
11285     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11286       uint64_t UndefElts;
11287       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11288                                                 1 << IndexVal,
11289                                                 UndefElts)) {
11290         EI.setOperand(0, V);
11291         return &EI;
11292       }
11293     }
11294     
11295     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11296       return ReplaceInstUsesWith(EI, Elt);
11297     
11298     // If the this extractelement is directly using a bitcast from a vector of
11299     // the same number of elements, see if we can find the source element from
11300     // it.  In this case, we will end up needing to bitcast the scalars.
11301     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11302       if (const VectorType *VT = 
11303               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11304         if (VT->getNumElements() == VectorWidth)
11305           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11306             return new BitCastInst(Elt, EI.getType());
11307     }
11308   }
11309   
11310   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11311     if (I->hasOneUse()) {
11312       // Push extractelement into predecessor operation if legal and
11313       // profitable to do so
11314       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11315         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11316         if (CheapToScalarize(BO, isConstantElt)) {
11317           ExtractElementInst *newEI0 = 
11318             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11319                                    EI.getName()+".lhs");
11320           ExtractElementInst *newEI1 =
11321             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11322                                    EI.getName()+".rhs");
11323           InsertNewInstBefore(newEI0, EI);
11324           InsertNewInstBefore(newEI1, EI);
11325           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11326         }
11327       } else if (isa<LoadInst>(I)) {
11328         unsigned AS = 
11329           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11330         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11331                                          PointerType::get(EI.getType(), AS),EI);
11332         GetElementPtrInst *GEP =
11333           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11334         InsertNewInstBefore(GEP, EI);
11335         return new LoadInst(GEP);
11336       }
11337     }
11338     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11339       // Extracting the inserted element?
11340       if (IE->getOperand(2) == EI.getOperand(1))
11341         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11342       // If the inserted and extracted elements are constants, they must not
11343       // be the same value, extract from the pre-inserted value instead.
11344       if (isa<Constant>(IE->getOperand(2)) &&
11345           isa<Constant>(EI.getOperand(1))) {
11346         AddUsesToWorkList(EI);
11347         EI.setOperand(0, IE->getOperand(0));
11348         return &EI;
11349       }
11350     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11351       // If this is extracting an element from a shufflevector, figure out where
11352       // it came from and extract from the appropriate input element instead.
11353       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11354         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11355         Value *Src;
11356         if (SrcIdx < SVI->getType()->getNumElements())
11357           Src = SVI->getOperand(0);
11358         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11359           SrcIdx -= SVI->getType()->getNumElements();
11360           Src = SVI->getOperand(1);
11361         } else {
11362           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11363         }
11364         return new ExtractElementInst(Src, SrcIdx);
11365       }
11366     }
11367   }
11368   return 0;
11369 }
11370
11371 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11372 /// elements from either LHS or RHS, return the shuffle mask and true. 
11373 /// Otherwise, return false.
11374 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11375                                          std::vector<Constant*> &Mask) {
11376   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11377          "Invalid CollectSingleShuffleElements");
11378   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11379
11380   if (isa<UndefValue>(V)) {
11381     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11382     return true;
11383   } else if (V == LHS) {
11384     for (unsigned i = 0; i != NumElts; ++i)
11385       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11386     return true;
11387   } else if (V == RHS) {
11388     for (unsigned i = 0; i != NumElts; ++i)
11389       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11390     return true;
11391   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11392     // If this is an insert of an extract from some other vector, include it.
11393     Value *VecOp    = IEI->getOperand(0);
11394     Value *ScalarOp = IEI->getOperand(1);
11395     Value *IdxOp    = IEI->getOperand(2);
11396     
11397     if (!isa<ConstantInt>(IdxOp))
11398       return false;
11399     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11400     
11401     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11402       // Okay, we can handle this if the vector we are insertinting into is
11403       // transitively ok.
11404       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11405         // If so, update the mask to reflect the inserted undef.
11406         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11407         return true;
11408       }      
11409     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11410       if (isa<ConstantInt>(EI->getOperand(1)) &&
11411           EI->getOperand(0)->getType() == V->getType()) {
11412         unsigned ExtractedIdx =
11413           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11414         
11415         // This must be extracting from either LHS or RHS.
11416         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11417           // Okay, we can handle this if the vector we are insertinting into is
11418           // transitively ok.
11419           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11420             // If so, update the mask to reflect the inserted value.
11421             if (EI->getOperand(0) == LHS) {
11422               Mask[InsertedIdx & (NumElts-1)] = 
11423                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11424             } else {
11425               assert(EI->getOperand(0) == RHS);
11426               Mask[InsertedIdx & (NumElts-1)] = 
11427                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11428               
11429             }
11430             return true;
11431           }
11432         }
11433       }
11434     }
11435   }
11436   // TODO: Handle shufflevector here!
11437   
11438   return false;
11439 }
11440
11441 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11442 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11443 /// that computes V and the LHS value of the shuffle.
11444 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11445                                      Value *&RHS) {
11446   assert(isa<VectorType>(V->getType()) && 
11447          (RHS == 0 || V->getType() == RHS->getType()) &&
11448          "Invalid shuffle!");
11449   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11450
11451   if (isa<UndefValue>(V)) {
11452     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11453     return V;
11454   } else if (isa<ConstantAggregateZero>(V)) {
11455     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11456     return V;
11457   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11458     // If this is an insert of an extract from some other vector, include it.
11459     Value *VecOp    = IEI->getOperand(0);
11460     Value *ScalarOp = IEI->getOperand(1);
11461     Value *IdxOp    = IEI->getOperand(2);
11462     
11463     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11464       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11465           EI->getOperand(0)->getType() == V->getType()) {
11466         unsigned ExtractedIdx =
11467           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11468         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11469         
11470         // Either the extracted from or inserted into vector must be RHSVec,
11471         // otherwise we'd end up with a shuffle of three inputs.
11472         if (EI->getOperand(0) == RHS || RHS == 0) {
11473           RHS = EI->getOperand(0);
11474           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11475           Mask[InsertedIdx & (NumElts-1)] = 
11476             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11477           return V;
11478         }
11479         
11480         if (VecOp == RHS) {
11481           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11482           // Everything but the extracted element is replaced with the RHS.
11483           for (unsigned i = 0; i != NumElts; ++i) {
11484             if (i != InsertedIdx)
11485               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11486           }
11487           return V;
11488         }
11489         
11490         // If this insertelement is a chain that comes from exactly these two
11491         // vectors, return the vector and the effective shuffle.
11492         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11493           return EI->getOperand(0);
11494         
11495       }
11496     }
11497   }
11498   // TODO: Handle shufflevector here!
11499   
11500   // Otherwise, can't do anything fancy.  Return an identity vector.
11501   for (unsigned i = 0; i != NumElts; ++i)
11502     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11503   return V;
11504 }
11505
11506 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11507   Value *VecOp    = IE.getOperand(0);
11508   Value *ScalarOp = IE.getOperand(1);
11509   Value *IdxOp    = IE.getOperand(2);
11510   
11511   // Inserting an undef or into an undefined place, remove this.
11512   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11513     ReplaceInstUsesWith(IE, VecOp);
11514   
11515   // If the inserted element was extracted from some other vector, and if the 
11516   // indexes are constant, try to turn this into a shufflevector operation.
11517   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11518     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11519         EI->getOperand(0)->getType() == IE.getType()) {
11520       unsigned NumVectorElts = IE.getType()->getNumElements();
11521       unsigned ExtractedIdx =
11522         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11523       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11524       
11525       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11526         return ReplaceInstUsesWith(IE, VecOp);
11527       
11528       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11529         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11530       
11531       // If we are extracting a value from a vector, then inserting it right
11532       // back into the same place, just use the input vector.
11533       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11534         return ReplaceInstUsesWith(IE, VecOp);      
11535       
11536       // We could theoretically do this for ANY input.  However, doing so could
11537       // turn chains of insertelement instructions into a chain of shufflevector
11538       // instructions, and right now we do not merge shufflevectors.  As such,
11539       // only do this in a situation where it is clear that there is benefit.
11540       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11541         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11542         // the values of VecOp, except then one read from EIOp0.
11543         // Build a new shuffle mask.
11544         std::vector<Constant*> Mask;
11545         if (isa<UndefValue>(VecOp))
11546           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11547         else {
11548           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11549           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11550                                                        NumVectorElts));
11551         } 
11552         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11553         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11554                                      ConstantVector::get(Mask));
11555       }
11556       
11557       // If this insertelement isn't used by some other insertelement, turn it
11558       // (and any insertelements it points to), into one big shuffle.
11559       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11560         std::vector<Constant*> Mask;
11561         Value *RHS = 0;
11562         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11563         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11564         // We now have a shuffle of LHS, RHS, Mask.
11565         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11566       }
11567     }
11568   }
11569
11570   return 0;
11571 }
11572
11573
11574 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11575   Value *LHS = SVI.getOperand(0);
11576   Value *RHS = SVI.getOperand(1);
11577   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11578
11579   bool MadeChange = false;
11580   
11581   // Undefined shuffle mask -> undefined value.
11582   if (isa<UndefValue>(SVI.getOperand(2)))
11583     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11584   
11585   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11586   // the undef, change them to undefs.
11587   if (isa<UndefValue>(SVI.getOperand(1))) {
11588     // Scan to see if there are any references to the RHS.  If so, replace them
11589     // with undef element refs and set MadeChange to true.
11590     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11591       if (Mask[i] >= e && Mask[i] != 2*e) {
11592         Mask[i] = 2*e;
11593         MadeChange = true;
11594       }
11595     }
11596     
11597     if (MadeChange) {
11598       // Remap any references to RHS to use LHS.
11599       std::vector<Constant*> Elts;
11600       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11601         if (Mask[i] == 2*e)
11602           Elts.push_back(UndefValue::get(Type::Int32Ty));
11603         else
11604           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11605       }
11606       SVI.setOperand(2, ConstantVector::get(Elts));
11607     }
11608   }
11609   
11610   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11611   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11612   if (LHS == RHS || isa<UndefValue>(LHS)) {
11613     if (isa<UndefValue>(LHS) && LHS == RHS) {
11614       // shuffle(undef,undef,mask) -> undef.
11615       return ReplaceInstUsesWith(SVI, LHS);
11616     }
11617     
11618     // Remap any references to RHS to use LHS.
11619     std::vector<Constant*> Elts;
11620     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11621       if (Mask[i] >= 2*e)
11622         Elts.push_back(UndefValue::get(Type::Int32Ty));
11623       else {
11624         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11625             (Mask[i] <  e && isa<UndefValue>(LHS)))
11626           Mask[i] = 2*e;     // Turn into undef.
11627         else
11628           Mask[i] &= (e-1);  // Force to LHS.
11629         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11630       }
11631     }
11632     SVI.setOperand(0, SVI.getOperand(1));
11633     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11634     SVI.setOperand(2, ConstantVector::get(Elts));
11635     LHS = SVI.getOperand(0);
11636     RHS = SVI.getOperand(1);
11637     MadeChange = true;
11638   }
11639   
11640   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11641   bool isLHSID = true, isRHSID = true;
11642     
11643   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11644     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11645     // Is this an identity shuffle of the LHS value?
11646     isLHSID &= (Mask[i] == i);
11647       
11648     // Is this an identity shuffle of the RHS value?
11649     isRHSID &= (Mask[i]-e == i);
11650   }
11651
11652   // Eliminate identity shuffles.
11653   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11654   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11655   
11656   // If the LHS is a shufflevector itself, see if we can combine it with this
11657   // one without producing an unusual shuffle.  Here we are really conservative:
11658   // we are absolutely afraid of producing a shuffle mask not in the input
11659   // program, because the code gen may not be smart enough to turn a merged
11660   // shuffle into two specific shuffles: it may produce worse code.  As such,
11661   // we only merge two shuffles if the result is one of the two input shuffle
11662   // masks.  In this case, merging the shuffles just removes one instruction,
11663   // which we know is safe.  This is good for things like turning:
11664   // (splat(splat)) -> splat.
11665   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11666     if (isa<UndefValue>(RHS)) {
11667       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11668
11669       std::vector<unsigned> NewMask;
11670       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11671         if (Mask[i] >= 2*e)
11672           NewMask.push_back(2*e);
11673         else
11674           NewMask.push_back(LHSMask[Mask[i]]);
11675       
11676       // If the result mask is equal to the src shuffle or this shuffle mask, do
11677       // the replacement.
11678       if (NewMask == LHSMask || NewMask == Mask) {
11679         std::vector<Constant*> Elts;
11680         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11681           if (NewMask[i] >= e*2) {
11682             Elts.push_back(UndefValue::get(Type::Int32Ty));
11683           } else {
11684             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11685           }
11686         }
11687         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11688                                      LHSSVI->getOperand(1),
11689                                      ConstantVector::get(Elts));
11690       }
11691     }
11692   }
11693
11694   return MadeChange ? &SVI : 0;
11695 }
11696
11697
11698
11699
11700 /// TryToSinkInstruction - Try to move the specified instruction from its
11701 /// current block into the beginning of DestBlock, which can only happen if it's
11702 /// safe to move the instruction past all of the instructions between it and the
11703 /// end of its block.
11704 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11705   assert(I->hasOneUse() && "Invariants didn't hold!");
11706
11707   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11708   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11709     return false;
11710
11711   // Do not sink alloca instructions out of the entry block.
11712   if (isa<AllocaInst>(I) && I->getParent() ==
11713         &DestBlock->getParent()->getEntryBlock())
11714     return false;
11715
11716   // We can only sink load instructions if there is nothing between the load and
11717   // the end of block that could change the value.
11718   if (I->mayReadFromMemory()) {
11719     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11720          Scan != E; ++Scan)
11721       if (Scan->mayWriteToMemory())
11722         return false;
11723   }
11724
11725   BasicBlock::iterator InsertPos = DestBlock->begin();
11726   while (isa<PHINode>(InsertPos)) ++InsertPos;
11727
11728   I->moveBefore(InsertPos);
11729   ++NumSunkInst;
11730   return true;
11731 }
11732
11733
11734 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11735 /// all reachable code to the worklist.
11736 ///
11737 /// This has a couple of tricks to make the code faster and more powerful.  In
11738 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11739 /// them to the worklist (this significantly speeds up instcombine on code where
11740 /// many instructions are dead or constant).  Additionally, if we find a branch
11741 /// whose condition is a known constant, we only visit the reachable successors.
11742 ///
11743 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11744                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11745                                        InstCombiner &IC,
11746                                        const TargetData *TD) {
11747   std::vector<BasicBlock*> Worklist;
11748   Worklist.push_back(BB);
11749
11750   while (!Worklist.empty()) {
11751     BB = Worklist.back();
11752     Worklist.pop_back();
11753     
11754     // We have now visited this block!  If we've already been here, ignore it.
11755     if (!Visited.insert(BB)) continue;
11756     
11757     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11758       Instruction *Inst = BBI++;
11759       
11760       // DCE instruction if trivially dead.
11761       if (isInstructionTriviallyDead(Inst)) {
11762         ++NumDeadInst;
11763         DOUT << "IC: DCE: " << *Inst;
11764         Inst->eraseFromParent();
11765         continue;
11766       }
11767       
11768       // ConstantProp instruction if trivially constant.
11769       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11770         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11771         Inst->replaceAllUsesWith(C);
11772         ++NumConstProp;
11773         Inst->eraseFromParent();
11774         continue;
11775       }
11776      
11777       IC.AddToWorkList(Inst);
11778     }
11779
11780     // Recursively visit successors.  If this is a branch or switch on a
11781     // constant, only visit the reachable successor.
11782     TerminatorInst *TI = BB->getTerminator();
11783     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11784       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11785         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11786         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11787         Worklist.push_back(ReachableBB);
11788         continue;
11789       }
11790     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11791       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11792         // See if this is an explicit destination.
11793         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11794           if (SI->getCaseValue(i) == Cond) {
11795             BasicBlock *ReachableBB = SI->getSuccessor(i);
11796             Worklist.push_back(ReachableBB);
11797             continue;
11798           }
11799         
11800         // Otherwise it is the default destination.
11801         Worklist.push_back(SI->getSuccessor(0));
11802         continue;
11803       }
11804     }
11805     
11806     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11807       Worklist.push_back(TI->getSuccessor(i));
11808   }
11809 }
11810
11811 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11812   bool Changed = false;
11813   TD = &getAnalysis<TargetData>();
11814   
11815   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11816              << F.getNameStr() << "\n");
11817
11818   {
11819     // Do a depth-first traversal of the function, populate the worklist with
11820     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11821     // track of which blocks we visit.
11822     SmallPtrSet<BasicBlock*, 64> Visited;
11823     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11824
11825     // Do a quick scan over the function.  If we find any blocks that are
11826     // unreachable, remove any instructions inside of them.  This prevents
11827     // the instcombine code from having to deal with some bad special cases.
11828     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11829       if (!Visited.count(BB)) {
11830         Instruction *Term = BB->getTerminator();
11831         while (Term != BB->begin()) {   // Remove instrs bottom-up
11832           BasicBlock::iterator I = Term; --I;
11833
11834           DOUT << "IC: DCE: " << *I;
11835           ++NumDeadInst;
11836
11837           if (!I->use_empty())
11838             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11839           I->eraseFromParent();
11840         }
11841       }
11842   }
11843
11844   while (!Worklist.empty()) {
11845     Instruction *I = RemoveOneFromWorkList();
11846     if (I == 0) continue;  // skip null values.
11847
11848     // Check to see if we can DCE the instruction.
11849     if (isInstructionTriviallyDead(I)) {
11850       // Add operands to the worklist.
11851       if (I->getNumOperands() < 4)
11852         AddUsesToWorkList(*I);
11853       ++NumDeadInst;
11854
11855       DOUT << "IC: DCE: " << *I;
11856
11857       I->eraseFromParent();
11858       RemoveFromWorkList(I);
11859       continue;
11860     }
11861
11862     // Instruction isn't dead, see if we can constant propagate it.
11863     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11864       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11865
11866       // Add operands to the worklist.
11867       AddUsesToWorkList(*I);
11868       ReplaceInstUsesWith(*I, C);
11869
11870       ++NumConstProp;
11871       I->eraseFromParent();
11872       RemoveFromWorkList(I);
11873       continue;
11874     }
11875
11876     // See if we can trivially sink this instruction to a successor basic block.
11877     // FIXME: Remove GetResultInst test when first class support for aggregates
11878     // is implemented.
11879     if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11880       BasicBlock *BB = I->getParent();
11881       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11882       if (UserParent != BB) {
11883         bool UserIsSuccessor = false;
11884         // See if the user is one of our successors.
11885         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11886           if (*SI == UserParent) {
11887             UserIsSuccessor = true;
11888             break;
11889           }
11890
11891         // If the user is one of our immediate successors, and if that successor
11892         // only has us as a predecessors (we'd have to split the critical edge
11893         // otherwise), we can keep going.
11894         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11895             next(pred_begin(UserParent)) == pred_end(UserParent))
11896           // Okay, the CFG is simple enough, try to sink this instruction.
11897           Changed |= TryToSinkInstruction(I, UserParent);
11898       }
11899     }
11900
11901     // Now that we have an instruction, try combining it to simplify it...
11902 #ifndef NDEBUG
11903     std::string OrigI;
11904 #endif
11905     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11906     if (Instruction *Result = visit(*I)) {
11907       ++NumCombined;
11908       // Should we replace the old instruction with a new one?
11909       if (Result != I) {
11910         DOUT << "IC: Old = " << *I
11911              << "    New = " << *Result;
11912
11913         // Everything uses the new instruction now.
11914         I->replaceAllUsesWith(Result);
11915
11916         // Push the new instruction and any users onto the worklist.
11917         AddToWorkList(Result);
11918         AddUsersToWorkList(*Result);
11919
11920         // Move the name to the new instruction first.
11921         Result->takeName(I);
11922
11923         // Insert the new instruction into the basic block...
11924         BasicBlock *InstParent = I->getParent();
11925         BasicBlock::iterator InsertPos = I;
11926
11927         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11928           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11929             ++InsertPos;
11930
11931         InstParent->getInstList().insert(InsertPos, Result);
11932
11933         // Make sure that we reprocess all operands now that we reduced their
11934         // use counts.
11935         AddUsesToWorkList(*I);
11936
11937         // Instructions can end up on the worklist more than once.  Make sure
11938         // we do not process an instruction that has been deleted.
11939         RemoveFromWorkList(I);
11940
11941         // Erase the old instruction.
11942         InstParent->getInstList().erase(I);
11943       } else {
11944 #ifndef NDEBUG
11945         DOUT << "IC: Mod = " << OrigI
11946              << "    New = " << *I;
11947 #endif
11948
11949         // If the instruction was modified, it's possible that it is now dead.
11950         // if so, remove it.
11951         if (isInstructionTriviallyDead(I)) {
11952           // Make sure we process all operands now that we are reducing their
11953           // use counts.
11954           AddUsesToWorkList(*I);
11955
11956           // Instructions may end up in the worklist more than once.  Erase all
11957           // occurrences of this instruction.
11958           RemoveFromWorkList(I);
11959           I->eraseFromParent();
11960         } else {
11961           AddToWorkList(I);
11962           AddUsersToWorkList(*I);
11963         }
11964       }
11965       Changed = true;
11966     }
11967   }
11968
11969   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11970     
11971   // Do an explicit clear, this shrinks the map if needed.
11972   WorklistMap.clear();
11973   return Changed;
11974 }
11975
11976
11977 bool InstCombiner::runOnFunction(Function &F) {
11978   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11979   
11980   bool EverMadeChange = false;
11981
11982   // Iterate while there is work to do.
11983   unsigned Iteration = 0;
11984   while (DoOneIteration(F, Iteration++))
11985     EverMadeChange = true;
11986   return EverMadeChange;
11987 }
11988
11989 FunctionPass *llvm::createInstructionCombiningPass() {
11990   return new InstCombiner();
11991 }
11992