Fix the regressions on sext-misc.ll my patch yesterday caused.
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     std::vector<Instruction*> Worklist;
78     DenseMap<Instruction*, unsigned> WorklistMap;
79     TargetData *TD;
80     bool MustPreserveLCSSA;
81   public:
82     static char ID; // Pass identification, replacement for typeid
83     InstCombiner() : FunctionPass((intptr_t)&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(*i))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           *i = UndefValue::get(Op->getType());
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitSub(BinaryOperator &I);
171     Instruction *visitMul(BinaryOperator &I);
172     Instruction *visitURem(BinaryOperator &I);
173     Instruction *visitSRem(BinaryOperator &I);
174     Instruction *visitFRem(BinaryOperator &I);
175     Instruction *commonRemTransforms(BinaryOperator &I);
176     Instruction *commonIRemTransforms(BinaryOperator &I);
177     Instruction *commonDivTransforms(BinaryOperator &I);
178     Instruction *commonIDivTransforms(BinaryOperator &I);
179     Instruction *visitUDiv(BinaryOperator &I);
180     Instruction *visitSDiv(BinaryOperator &I);
181     Instruction *visitFDiv(BinaryOperator &I);
182     Instruction *visitAnd(BinaryOperator &I);
183     Instruction *visitOr (BinaryOperator &I);
184     Instruction *visitXor(BinaryOperator &I);
185     Instruction *visitShl(BinaryOperator &I);
186     Instruction *visitAShr(BinaryOperator &I);
187     Instruction *visitLShr(BinaryOperator &I);
188     Instruction *commonShiftTransforms(BinaryOperator &I);
189     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190                                       Constant *RHSC);
191     Instruction *visitFCmpInst(FCmpInst &I);
192     Instruction *visitICmpInst(ICmpInst &I);
193     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
194     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
195                                                 Instruction *LHS,
196                                                 ConstantInt *RHS);
197     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198                                 ConstantInt *DivRHS);
199
200     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201                              ICmpInst::Predicate Cond, Instruction &I);
202     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
203                                      BinaryOperator &I);
204     Instruction *commonCastTransforms(CastInst &CI);
205     Instruction *commonIntCastTransforms(CastInst &CI);
206     Instruction *commonPointerCastTransforms(CastInst &CI);
207     Instruction *visitTrunc(TruncInst &CI);
208     Instruction *visitZExt(ZExtInst &CI);
209     Instruction *visitSExt(SExtInst &CI);
210     Instruction *visitFPTrunc(FPTruncInst &CI);
211     Instruction *visitFPExt(CastInst &CI);
212     Instruction *visitFPToUI(FPToUIInst &FI);
213     Instruction *visitFPToSI(FPToSIInst &FI);
214     Instruction *visitUIToFP(CastInst &CI);
215     Instruction *visitSIToFP(CastInst &CI);
216     Instruction *visitPtrToInt(CastInst &CI);
217     Instruction *visitIntToPtr(IntToPtrInst &CI);
218     Instruction *visitBitCast(BitCastInst &CI);
219     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220                                 Instruction *FI);
221     Instruction *visitSelectInst(SelectInst &CI);
222     Instruction *visitCallInst(CallInst &CI);
223     Instruction *visitInvokeInst(InvokeInst &II);
224     Instruction *visitPHINode(PHINode &PN);
225     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
226     Instruction *visitAllocationInst(AllocationInst &AI);
227     Instruction *visitFreeInst(FreeInst &FI);
228     Instruction *visitLoadInst(LoadInst &LI);
229     Instruction *visitStoreInst(StoreInst &SI);
230     Instruction *visitBranchInst(BranchInst &BI);
231     Instruction *visitSwitchInst(SwitchInst &SI);
232     Instruction *visitInsertElementInst(InsertElementInst &IE);
233     Instruction *visitExtractElementInst(ExtractElementInst &EI);
234     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
235     Instruction *visitExtractValueInst(ExtractValueInst &EV);
236
237     // visitInstruction - Specify what to return for unhandled instructions...
238     Instruction *visitInstruction(Instruction &I) { return 0; }
239
240   private:
241     Instruction *visitCallSite(CallSite CS);
242     bool transformConstExprCastCall(CallSite CS);
243     Instruction *transformCallThroughTrampoline(CallSite CS);
244     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
245                                    bool DoXform = true);
246     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
247
248   public:
249     // InsertNewInstBefore - insert an instruction New before instruction Old
250     // in the program.  Add the new instruction to the worklist.
251     //
252     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
253       assert(New && New->getParent() == 0 &&
254              "New instruction already inserted into a basic block!");
255       BasicBlock *BB = Old.getParent();
256       BB->getInstList().insert(&Old, New);  // Insert inst
257       AddToWorkList(New);
258       return New;
259     }
260
261     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
262     /// This also adds the cast to the worklist.  Finally, this returns the
263     /// cast.
264     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
265                             Instruction &Pos) {
266       if (V->getType() == Ty) return V;
267
268       if (Constant *CV = dyn_cast<Constant>(V))
269         return ConstantExpr::getCast(opc, CV, Ty);
270       
271       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
272       AddToWorkList(C);
273       return C;
274     }
275         
276     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
277       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
278     }
279
280
281     // ReplaceInstUsesWith - This method is to be used when an instruction is
282     // found to be dead, replacable with another preexisting expression.  Here
283     // we add all uses of I to the worklist, replace all uses of I with the new
284     // value, then return I, so that the inst combiner will know that I was
285     // modified.
286     //
287     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
288       AddUsersToWorkList(I);         // Add all modified instrs to worklist
289       if (&I != V) {
290         I.replaceAllUsesWith(V);
291         return &I;
292       } else {
293         // If we are replacing the instruction with itself, this must be in a
294         // segment of unreachable code, so just clobber the instruction.
295         I.replaceAllUsesWith(UndefValue::get(I.getType()));
296         return &I;
297       }
298     }
299
300     // UpdateValueUsesWith - This method is to be used when an value is
301     // found to be replacable with another preexisting expression or was
302     // updated.  Here we add all uses of I to the worklist, replace all uses of
303     // I with the new value (unless the instruction was just updated), then
304     // return true, so that the inst combiner will know that I was modified.
305     //
306     bool UpdateValueUsesWith(Value *Old, Value *New) {
307       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
308       if (Old != New)
309         Old->replaceAllUsesWith(New);
310       if (Instruction *I = dyn_cast<Instruction>(Old))
311         AddToWorkList(I);
312       if (Instruction *I = dyn_cast<Instruction>(New))
313         AddToWorkList(I);
314       return true;
315     }
316     
317     // EraseInstFromFunction - When dealing with an instruction that has side
318     // effects or produces a void value, we can't rely on DCE to delete the
319     // instruction.  Instead, visit methods should return the value returned by
320     // this function.
321     Instruction *EraseInstFromFunction(Instruction &I) {
322       assert(I.use_empty() && "Cannot erase instruction that is used!");
323       AddUsesToWorkList(I);
324       RemoveFromWorkList(&I);
325       I.eraseFromParent();
326       return 0;  // Don't do anything with FI
327     }
328         
329     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330                            APInt &KnownOne, unsigned Depth = 0) const {
331       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332     }
333     
334     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
335                            unsigned Depth = 0) const {
336       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337     }
338     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339       return llvm::ComputeNumSignBits(Op, TD, Depth);
340     }
341
342   private:
343     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
344     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
345     /// casts that are known to not do anything...
346     ///
347     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
348                                    Value *V, const Type *DestTy,
349                                    Instruction *InsertBefore);
350
351     /// SimplifyCommutative - This performs a few simplifications for 
352     /// commutative operators.
353     bool SimplifyCommutative(BinaryOperator &I);
354
355     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
356     /// most-complex to least-complex order.
357     bool SimplifyCompare(CmpInst &I);
358
359     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
360     /// on the demanded bits.
361     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
362                               APInt& KnownZero, APInt& KnownOne,
363                               unsigned Depth = 0);
364
365     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
366                                       uint64_t &UndefElts, unsigned Depth = 0);
367       
368     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369     // PHI node as operand #0, see if we can fold the instruction into the PHI
370     // (which is only possible if all operands to the PHI are constants).
371     Instruction *FoldOpIntoPhi(Instruction &I);
372
373     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374     // operator and they all are only used by the PHI, PHI together their
375     // inputs, and do the operation once, to the result of the PHI.
376     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378     
379     
380     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
382     
383     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384                               bool isSub, Instruction &I);
385     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386                                  bool isSigned, bool Inside, Instruction &IB);
387     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388     Instruction *MatchBSwap(BinaryOperator &I);
389     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
390     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
391     Instruction *SimplifyMemSet(MemSetInst *MI);
392
393
394     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
395
396     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
397                                     unsigned CastOpc,
398                                     int &NumCastsRemoved);
399     unsigned GetOrEnforceKnownAlignment(Value *V,
400                                         unsigned PrefAlign = 0);
401
402   };
403 }
404
405 char InstCombiner::ID = 0;
406 static RegisterPass<InstCombiner>
407 X("instcombine", "Combine redundant instructions");
408
409 // getComplexity:  Assign a complexity or rank value to LLVM Values...
410 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411 static unsigned getComplexity(Value *V) {
412   if (isa<Instruction>(V)) {
413     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
414       return 3;
415     return 4;
416   }
417   if (isa<Argument>(V)) return 3;
418   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
419 }
420
421 // isOnlyUse - Return true if this instruction will be deleted if we stop using
422 // it.
423 static bool isOnlyUse(Value *V) {
424   return V->hasOneUse() || isa<Constant>(V);
425 }
426
427 // getPromotedType - Return the specified type promoted as it would be to pass
428 // though a va_arg area...
429 static const Type *getPromotedType(const Type *Ty) {
430   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431     if (ITy->getBitWidth() < 32)
432       return Type::Int32Ty;
433   }
434   return Ty;
435 }
436
437 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
438 /// expression bitcast,  return the operand value, otherwise return null.
439 static Value *getBitCastOperand(Value *V) {
440   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
441     return I->getOperand(0);
442   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
443     if (CE->getOpcode() == Instruction::BitCast)
444       return CE->getOperand(0);
445   return 0;
446 }
447
448 /// This function is a wrapper around CastInst::isEliminableCastPair. It
449 /// simply extracts arguments and returns what that function returns.
450 static Instruction::CastOps 
451 isEliminableCastPair(
452   const CastInst *CI, ///< The first cast instruction
453   unsigned opcode,       ///< The opcode of the second cast instruction
454   const Type *DstTy,     ///< The target type for the second cast instruction
455   TargetData *TD         ///< The target data for pointer size
456 ) {
457   
458   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
459   const Type *MidTy = CI->getType();                  // B from above
460
461   // Get the opcodes of the two Cast instructions
462   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
463   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
464
465   return Instruction::CastOps(
466       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
467                                      DstTy, TD->getIntPtrType()));
468 }
469
470 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
471 /// in any code being generated.  It does not require codegen if V is simple
472 /// enough or if the cast can be folded into other casts.
473 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
474                               const Type *Ty, TargetData *TD) {
475   if (V->getType() == Ty || isa<Constant>(V)) return false;
476   
477   // If this is another cast that can be eliminated, it isn't codegen either.
478   if (const CastInst *CI = dyn_cast<CastInst>(V))
479     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
480       return false;
481   return true;
482 }
483
484 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
485 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
486 /// casts that are known to not do anything...
487 ///
488 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
489                                              Value *V, const Type *DestTy,
490                                              Instruction *InsertBefore) {
491   if (V->getType() == DestTy) return V;
492   if (Constant *C = dyn_cast<Constant>(V))
493     return ConstantExpr::getCast(opcode, C, DestTy);
494   
495   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
496 }
497
498 // SimplifyCommutative - This performs a few simplifications for commutative
499 // operators:
500 //
501 //  1. Order operands such that they are listed from right (least complex) to
502 //     left (most complex).  This puts constants before unary operators before
503 //     binary operators.
504 //
505 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
506 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
507 //
508 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
509   bool Changed = false;
510   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
511     Changed = !I.swapOperands();
512
513   if (!I.isAssociative()) return Changed;
514   Instruction::BinaryOps Opcode = I.getOpcode();
515   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517       if (isa<Constant>(I.getOperand(1))) {
518         Constant *Folded = ConstantExpr::get(I.getOpcode(),
519                                              cast<Constant>(I.getOperand(1)),
520                                              cast<Constant>(Op->getOperand(1)));
521         I.setOperand(0, Op->getOperand(0));
522         I.setOperand(1, Folded);
523         return true;
524       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526             isOnlyUse(Op) && isOnlyUse(Op1)) {
527           Constant *C1 = cast<Constant>(Op->getOperand(1));
528           Constant *C2 = cast<Constant>(Op1->getOperand(1));
529
530           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
531           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
532           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
533                                                     Op1->getOperand(0),
534                                                     Op1->getName(), &I);
535           AddToWorkList(New);
536           I.setOperand(0, New);
537           I.setOperand(1, Folded);
538           return true;
539         }
540     }
541   return Changed;
542 }
543
544 /// SimplifyCompare - For a CmpInst this function just orders the operands
545 /// so that theyare listed from right (least complex) to left (most complex).
546 /// This puts constants before unary operators before binary operators.
547 bool InstCombiner::SimplifyCompare(CmpInst &I) {
548   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
549     return false;
550   I.swapOperands();
551   // Compare instructions are not associative so there's nothing else we can do.
552   return true;
553 }
554
555 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
556 // if the LHS is a constant zero (which is the 'negate' form).
557 //
558 static inline Value *dyn_castNegVal(Value *V) {
559   if (BinaryOperator::isNeg(V))
560     return BinaryOperator::getNegArgument(V);
561
562   // Constants can be considered to be negated values if they can be folded.
563   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
564     return ConstantExpr::getNeg(C);
565
566   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
567     if (C->getType()->getElementType()->isInteger())
568       return ConstantExpr::getNeg(C);
569
570   return 0;
571 }
572
573 static inline Value *dyn_castNotVal(Value *V) {
574   if (BinaryOperator::isNot(V))
575     return BinaryOperator::getNotArgument(V);
576
577   // Constants can be considered to be not'ed values...
578   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
579     return ConstantInt::get(~C->getValue());
580   return 0;
581 }
582
583 // dyn_castFoldableMul - If this value is a multiply that can be folded into
584 // other computations (because it has a constant operand), return the
585 // non-constant operand of the multiply, and set CST to point to the multiplier.
586 // Otherwise, return null.
587 //
588 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
589   if (V->hasOneUse() && V->getType()->isInteger())
590     if (Instruction *I = dyn_cast<Instruction>(V)) {
591       if (I->getOpcode() == Instruction::Mul)
592         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
593           return I->getOperand(0);
594       if (I->getOpcode() == Instruction::Shl)
595         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
596           // The multiplier is really 1 << CST.
597           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
598           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
599           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
600           return I->getOperand(0);
601         }
602     }
603   return 0;
604 }
605
606 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
607 /// expression, return it.
608 static User *dyn_castGetElementPtr(Value *V) {
609   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
610   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
611     if (CE->getOpcode() == Instruction::GetElementPtr)
612       return cast<User>(V);
613   return false;
614 }
615
616 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
617 /// opcode value. Otherwise return UserOp1.
618 static unsigned getOpcode(const Value *V) {
619   if (const Instruction *I = dyn_cast<Instruction>(V))
620     return I->getOpcode();
621   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
622     return CE->getOpcode();
623   // Use UserOp1 to mean there's no opcode.
624   return Instruction::UserOp1;
625 }
626
627 /// AddOne - Add one to a ConstantInt
628 static ConstantInt *AddOne(ConstantInt *C) {
629   APInt Val(C->getValue());
630   return ConstantInt::get(++Val);
631 }
632 /// SubOne - Subtract one from a ConstantInt
633 static ConstantInt *SubOne(ConstantInt *C) {
634   APInt Val(C->getValue());
635   return ConstantInt::get(--Val);
636 }
637 /// Add - Add two ConstantInts together
638 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
639   return ConstantInt::get(C1->getValue() + C2->getValue());
640 }
641 /// And - Bitwise AND two ConstantInts together
642 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
643   return ConstantInt::get(C1->getValue() & C2->getValue());
644 }
645 /// Subtract - Subtract one ConstantInt from another
646 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
647   return ConstantInt::get(C1->getValue() - C2->getValue());
648 }
649 /// Multiply - Multiply two ConstantInts together
650 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
651   return ConstantInt::get(C1->getValue() * C2->getValue());
652 }
653 /// MultiplyOverflows - True if the multiply can not be expressed in an int
654 /// this size.
655 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
656   uint32_t W = C1->getBitWidth();
657   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
658   if (sign) {
659     LHSExt.sext(W * 2);
660     RHSExt.sext(W * 2);
661   } else {
662     LHSExt.zext(W * 2);
663     RHSExt.zext(W * 2);
664   }
665
666   APInt MulExt = LHSExt * RHSExt;
667
668   if (sign) {
669     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
670     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
671     return MulExt.slt(Min) || MulExt.sgt(Max);
672   } else 
673     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
674 }
675
676
677 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
678 /// specified instruction is a constant integer.  If so, check to see if there
679 /// are any bits set in the constant that are not demanded.  If so, shrink the
680 /// constant and return true.
681 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
682                                    APInt Demanded) {
683   assert(I && "No instruction?");
684   assert(OpNo < I->getNumOperands() && "Operand index too large");
685
686   // If the operand is not a constant integer, nothing to do.
687   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
688   if (!OpC) return false;
689
690   // If there are no bits set that aren't demanded, nothing to do.
691   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
692   if ((~Demanded & OpC->getValue()) == 0)
693     return false;
694
695   // This instruction is producing bits that are not demanded. Shrink the RHS.
696   Demanded &= OpC->getValue();
697   I->setOperand(OpNo, ConstantInt::get(Demanded));
698   return true;
699 }
700
701 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
702 // set of known zero and one bits, compute the maximum and minimum values that
703 // could have the specified known zero and known one bits, returning them in
704 // min/max.
705 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
706                                                    const APInt& KnownZero,
707                                                    const APInt& KnownOne,
708                                                    APInt& Min, APInt& Max) {
709   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
710   assert(KnownZero.getBitWidth() == BitWidth && 
711          KnownOne.getBitWidth() == BitWidth &&
712          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
713          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
714   APInt UnknownBits = ~(KnownZero|KnownOne);
715
716   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
717   // bit if it is unknown.
718   Min = KnownOne;
719   Max = KnownOne|UnknownBits;
720   
721   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
722     Min.set(BitWidth-1);
723     Max.clear(BitWidth-1);
724   }
725 }
726
727 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
728 // a set of known zero and one bits, compute the maximum and minimum values that
729 // could have the specified known zero and known one bits, returning them in
730 // min/max.
731 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
732                                                      const APInt &KnownZero,
733                                                      const APInt &KnownOne,
734                                                      APInt &Min, APInt &Max) {
735   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
736   assert(KnownZero.getBitWidth() == BitWidth && 
737          KnownOne.getBitWidth() == BitWidth &&
738          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
739          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
740   APInt UnknownBits = ~(KnownZero|KnownOne);
741   
742   // The minimum value is when the unknown bits are all zeros.
743   Min = KnownOne;
744   // The maximum value is when the unknown bits are all ones.
745   Max = KnownOne|UnknownBits;
746 }
747
748 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
749 /// value based on the demanded bits. When this function is called, it is known
750 /// that only the bits set in DemandedMask of the result of V are ever used
751 /// downstream. Consequently, depending on the mask and V, it may be possible
752 /// to replace V with a constant or one of its operands. In such cases, this
753 /// function does the replacement and returns true. In all other cases, it
754 /// returns false after analyzing the expression and setting KnownOne and known
755 /// to be one in the expression. KnownZero contains all the bits that are known
756 /// to be zero in the expression. These are provided to potentially allow the
757 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
758 /// the expression. KnownOne and KnownZero always follow the invariant that 
759 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
760 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
761 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
762 /// and KnownOne must all be the same.
763 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
764                                         APInt& KnownZero, APInt& KnownOne,
765                                         unsigned Depth) {
766   assert(V != 0 && "Null pointer of Value???");
767   assert(Depth <= 6 && "Limit Search Depth");
768   uint32_t BitWidth = DemandedMask.getBitWidth();
769   const IntegerType *VTy = cast<IntegerType>(V->getType());
770   assert(VTy->getBitWidth() == BitWidth && 
771          KnownZero.getBitWidth() == BitWidth && 
772          KnownOne.getBitWidth() == BitWidth &&
773          "Value *V, DemandedMask, KnownZero and KnownOne \
774           must have same BitWidth");
775   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
776     // We know all of the bits for a constant!
777     KnownOne = CI->getValue() & DemandedMask;
778     KnownZero = ~KnownOne & DemandedMask;
779     return false;
780   }
781   
782   KnownZero.clear(); 
783   KnownOne.clear();
784   if (!V->hasOneUse()) {    // Other users may use these bits.
785     if (Depth != 0) {       // Not at the root.
786       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
787       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
788       return false;
789     }
790     // If this is the root being simplified, allow it to have multiple uses,
791     // just set the DemandedMask to all bits.
792     DemandedMask = APInt::getAllOnesValue(BitWidth);
793   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
794     if (V != UndefValue::get(VTy))
795       return UpdateValueUsesWith(V, UndefValue::get(VTy));
796     return false;
797   } else if (Depth == 6) {        // Limit search depth.
798     return false;
799   }
800   
801   Instruction *I = dyn_cast<Instruction>(V);
802   if (!I) return false;        // Only analyze instructions.
803
804   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
805   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
806   switch (I->getOpcode()) {
807   default:
808     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
809     break;
810   case Instruction::And:
811     // If either the LHS or the RHS are Zero, the result is zero.
812     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
813                              RHSKnownZero, RHSKnownOne, Depth+1))
814       return true;
815     assert((RHSKnownZero & RHSKnownOne) == 0 && 
816            "Bits known to be one AND zero?"); 
817
818     // If something is known zero on the RHS, the bits aren't demanded on the
819     // LHS.
820     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
821                              LHSKnownZero, LHSKnownOne, Depth+1))
822       return true;
823     assert((LHSKnownZero & LHSKnownOne) == 0 && 
824            "Bits known to be one AND zero?"); 
825
826     // If all of the demanded bits are known 1 on one side, return the other.
827     // These bits cannot contribute to the result of the 'and'.
828     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
829         (DemandedMask & ~LHSKnownZero))
830       return UpdateValueUsesWith(I, I->getOperand(0));
831     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
832         (DemandedMask & ~RHSKnownZero))
833       return UpdateValueUsesWith(I, I->getOperand(1));
834     
835     // If all of the demanded bits in the inputs are known zeros, return zero.
836     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
837       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
838       
839     // If the RHS is a constant, see if we can simplify it.
840     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
841       return UpdateValueUsesWith(I, I);
842       
843     // Output known-1 bits are only known if set in both the LHS & RHS.
844     RHSKnownOne &= LHSKnownOne;
845     // Output known-0 are known to be clear if zero in either the LHS | RHS.
846     RHSKnownZero |= LHSKnownZero;
847     break;
848   case Instruction::Or:
849     // If either the LHS or the RHS are One, the result is One.
850     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
851                              RHSKnownZero, RHSKnownOne, Depth+1))
852       return true;
853     assert((RHSKnownZero & RHSKnownOne) == 0 && 
854            "Bits known to be one AND zero?"); 
855     // If something is known one on the RHS, the bits aren't demanded on the
856     // LHS.
857     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
858                              LHSKnownZero, LHSKnownOne, Depth+1))
859       return true;
860     assert((LHSKnownZero & LHSKnownOne) == 0 && 
861            "Bits known to be one AND zero?"); 
862     
863     // If all of the demanded bits are known zero on one side, return the other.
864     // These bits cannot contribute to the result of the 'or'.
865     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
866         (DemandedMask & ~LHSKnownOne))
867       return UpdateValueUsesWith(I, I->getOperand(0));
868     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
869         (DemandedMask & ~RHSKnownOne))
870       return UpdateValueUsesWith(I, I->getOperand(1));
871
872     // If all of the potentially set bits on one side are known to be set on
873     // the other side, just use the 'other' side.
874     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
875         (DemandedMask & (~RHSKnownZero)))
876       return UpdateValueUsesWith(I, I->getOperand(0));
877     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
878         (DemandedMask & (~LHSKnownZero)))
879       return UpdateValueUsesWith(I, I->getOperand(1));
880         
881     // If the RHS is a constant, see if we can simplify it.
882     if (ShrinkDemandedConstant(I, 1, DemandedMask))
883       return UpdateValueUsesWith(I, I);
884           
885     // Output known-0 bits are only known if clear in both the LHS & RHS.
886     RHSKnownZero &= LHSKnownZero;
887     // Output known-1 are known to be set if set in either the LHS | RHS.
888     RHSKnownOne |= LHSKnownOne;
889     break;
890   case Instruction::Xor: {
891     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
892                              RHSKnownZero, RHSKnownOne, Depth+1))
893       return true;
894     assert((RHSKnownZero & RHSKnownOne) == 0 && 
895            "Bits known to be one AND zero?"); 
896     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
897                              LHSKnownZero, LHSKnownOne, Depth+1))
898       return true;
899     assert((LHSKnownZero & LHSKnownOne) == 0 && 
900            "Bits known to be one AND zero?"); 
901     
902     // If all of the demanded bits are known zero on one side, return the other.
903     // These bits cannot contribute to the result of the 'xor'.
904     if ((DemandedMask & RHSKnownZero) == DemandedMask)
905       return UpdateValueUsesWith(I, I->getOperand(0));
906     if ((DemandedMask & LHSKnownZero) == DemandedMask)
907       return UpdateValueUsesWith(I, I->getOperand(1));
908     
909     // Output known-0 bits are known if clear or set in both the LHS & RHS.
910     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
911                          (RHSKnownOne & LHSKnownOne);
912     // Output known-1 are known to be set if set in only one of the LHS, RHS.
913     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
914                         (RHSKnownOne & LHSKnownZero);
915     
916     // If all of the demanded bits are known to be zero on one side or the
917     // other, turn this into an *inclusive* or.
918     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
919     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
920       Instruction *Or =
921         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
922                                  I->getName());
923       InsertNewInstBefore(Or, *I);
924       return UpdateValueUsesWith(I, Or);
925     }
926     
927     // If all of the demanded bits on one side are known, and all of the set
928     // bits on that side are also known to be set on the other side, turn this
929     // into an AND, as we know the bits will be cleared.
930     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
931     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
932       // all known
933       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
934         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
935         Instruction *And = 
936           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
937         InsertNewInstBefore(And, *I);
938         return UpdateValueUsesWith(I, And);
939       }
940     }
941     
942     // If the RHS is a constant, see if we can simplify it.
943     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
944     if (ShrinkDemandedConstant(I, 1, DemandedMask))
945       return UpdateValueUsesWith(I, I);
946     
947     RHSKnownZero = KnownZeroOut;
948     RHSKnownOne  = KnownOneOut;
949     break;
950   }
951   case Instruction::Select:
952     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
953                              RHSKnownZero, RHSKnownOne, Depth+1))
954       return true;
955     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
956                              LHSKnownZero, LHSKnownOne, Depth+1))
957       return true;
958     assert((RHSKnownZero & RHSKnownOne) == 0 && 
959            "Bits known to be one AND zero?"); 
960     assert((LHSKnownZero & LHSKnownOne) == 0 && 
961            "Bits known to be one AND zero?"); 
962     
963     // If the operands are constants, see if we can simplify them.
964     if (ShrinkDemandedConstant(I, 1, DemandedMask))
965       return UpdateValueUsesWith(I, I);
966     if (ShrinkDemandedConstant(I, 2, DemandedMask))
967       return UpdateValueUsesWith(I, I);
968     
969     // Only known if known in both the LHS and RHS.
970     RHSKnownOne &= LHSKnownOne;
971     RHSKnownZero &= LHSKnownZero;
972     break;
973   case Instruction::Trunc: {
974     uint32_t truncBf = 
975       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
976     DemandedMask.zext(truncBf);
977     RHSKnownZero.zext(truncBf);
978     RHSKnownOne.zext(truncBf);
979     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
980                              RHSKnownZero, RHSKnownOne, Depth+1))
981       return true;
982     DemandedMask.trunc(BitWidth);
983     RHSKnownZero.trunc(BitWidth);
984     RHSKnownOne.trunc(BitWidth);
985     assert((RHSKnownZero & RHSKnownOne) == 0 && 
986            "Bits known to be one AND zero?"); 
987     break;
988   }
989   case Instruction::BitCast:
990     if (!I->getOperand(0)->getType()->isInteger())
991       return false;
992       
993     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
994                              RHSKnownZero, RHSKnownOne, Depth+1))
995       return true;
996     assert((RHSKnownZero & RHSKnownOne) == 0 && 
997            "Bits known to be one AND zero?"); 
998     break;
999   case Instruction::ZExt: {
1000     // Compute the bits in the result that are not present in the input.
1001     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1002     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1003     
1004     DemandedMask.trunc(SrcBitWidth);
1005     RHSKnownZero.trunc(SrcBitWidth);
1006     RHSKnownOne.trunc(SrcBitWidth);
1007     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008                              RHSKnownZero, RHSKnownOne, Depth+1))
1009       return true;
1010     DemandedMask.zext(BitWidth);
1011     RHSKnownZero.zext(BitWidth);
1012     RHSKnownOne.zext(BitWidth);
1013     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1014            "Bits known to be one AND zero?"); 
1015     // The top bits are known to be zero.
1016     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1017     break;
1018   }
1019   case Instruction::SExt: {
1020     // Compute the bits in the result that are not present in the input.
1021     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1022     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1023     
1024     APInt InputDemandedBits = DemandedMask & 
1025                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1026
1027     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1028     // If any of the sign extended bits are demanded, we know that the sign
1029     // bit is demanded.
1030     if ((NewBits & DemandedMask) != 0)
1031       InputDemandedBits.set(SrcBitWidth-1);
1032       
1033     InputDemandedBits.trunc(SrcBitWidth);
1034     RHSKnownZero.trunc(SrcBitWidth);
1035     RHSKnownOne.trunc(SrcBitWidth);
1036     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1037                              RHSKnownZero, RHSKnownOne, Depth+1))
1038       return true;
1039     InputDemandedBits.zext(BitWidth);
1040     RHSKnownZero.zext(BitWidth);
1041     RHSKnownOne.zext(BitWidth);
1042     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1043            "Bits known to be one AND zero?"); 
1044       
1045     // If the sign bit of the input is known set or clear, then we know the
1046     // top bits of the result.
1047
1048     // If the input sign bit is known zero, or if the NewBits are not demanded
1049     // convert this into a zero extension.
1050     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1051     {
1052       // Convert to ZExt cast
1053       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1054       return UpdateValueUsesWith(I, NewCast);
1055     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1056       RHSKnownOne |= NewBits;
1057     }
1058     break;
1059   }
1060   case Instruction::Add: {
1061     // Figure out what the input bits are.  If the top bits of the and result
1062     // are not demanded, then the add doesn't demand them from its input
1063     // either.
1064     uint32_t NLZ = DemandedMask.countLeadingZeros();
1065       
1066     // If there is a constant on the RHS, there are a variety of xformations
1067     // we can do.
1068     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1069       // If null, this should be simplified elsewhere.  Some of the xforms here
1070       // won't work if the RHS is zero.
1071       if (RHS->isZero())
1072         break;
1073       
1074       // If the top bit of the output is demanded, demand everything from the
1075       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1076       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1077
1078       // Find information about known zero/one bits in the input.
1079       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1080                                LHSKnownZero, LHSKnownOne, Depth+1))
1081         return true;
1082
1083       // If the RHS of the add has bits set that can't affect the input, reduce
1084       // the constant.
1085       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1086         return UpdateValueUsesWith(I, I);
1087       
1088       // Avoid excess work.
1089       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1090         break;
1091       
1092       // Turn it into OR if input bits are zero.
1093       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1094         Instruction *Or =
1095           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1096                                    I->getName());
1097         InsertNewInstBefore(Or, *I);
1098         return UpdateValueUsesWith(I, Or);
1099       }
1100       
1101       // We can say something about the output known-zero and known-one bits,
1102       // depending on potential carries from the input constant and the
1103       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1104       // bits set and the RHS constant is 0x01001, then we know we have a known
1105       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1106       
1107       // To compute this, we first compute the potential carry bits.  These are
1108       // the bits which may be modified.  I'm not aware of a better way to do
1109       // this scan.
1110       const APInt& RHSVal = RHS->getValue();
1111       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1112       
1113       // Now that we know which bits have carries, compute the known-1/0 sets.
1114       
1115       // Bits are known one if they are known zero in one operand and one in the
1116       // other, and there is no input carry.
1117       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1118                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1119       
1120       // Bits are known zero if they are known zero in both operands and there
1121       // is no input carry.
1122       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1123     } else {
1124       // If the high-bits of this ADD are not demanded, then it does not demand
1125       // the high bits of its LHS or RHS.
1126       if (DemandedMask[BitWidth-1] == 0) {
1127         // Right fill the mask of bits for this ADD to demand the most
1128         // significant bit and all those below it.
1129         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1130         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1131                                  LHSKnownZero, LHSKnownOne, Depth+1))
1132           return true;
1133         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1134                                  LHSKnownZero, LHSKnownOne, Depth+1))
1135           return true;
1136       }
1137     }
1138     break;
1139   }
1140   case Instruction::Sub:
1141     // If the high-bits of this SUB are not demanded, then it does not demand
1142     // the high bits of its LHS or RHS.
1143     if (DemandedMask[BitWidth-1] == 0) {
1144       // Right fill the mask of bits for this SUB to demand the most
1145       // significant bit and all those below it.
1146       uint32_t NLZ = DemandedMask.countLeadingZeros();
1147       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1148       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1149                                LHSKnownZero, LHSKnownOne, Depth+1))
1150         return true;
1151       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1152                                LHSKnownZero, LHSKnownOne, Depth+1))
1153         return true;
1154     }
1155     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1156     // the known zeros and ones.
1157     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1158     break;
1159   case Instruction::Shl:
1160     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1162       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1163       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1164                                RHSKnownZero, RHSKnownOne, Depth+1))
1165         return true;
1166       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1167              "Bits known to be one AND zero?"); 
1168       RHSKnownZero <<= ShiftAmt;
1169       RHSKnownOne  <<= ShiftAmt;
1170       // low bits known zero.
1171       if (ShiftAmt)
1172         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1173     }
1174     break;
1175   case Instruction::LShr:
1176     // For a logical shift right
1177     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1179       
1180       // Unsigned shift right.
1181       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1182       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1183                                RHSKnownZero, RHSKnownOne, Depth+1))
1184         return true;
1185       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1186              "Bits known to be one AND zero?"); 
1187       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1188       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1189       if (ShiftAmt) {
1190         // Compute the new bits that are at the top now.
1191         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1192         RHSKnownZero |= HighBits;  // high bits known zero.
1193       }
1194     }
1195     break;
1196   case Instruction::AShr:
1197     // If this is an arithmetic shift right and only the low-bit is set, we can
1198     // always convert this into a logical shr, even if the shift amount is
1199     // variable.  The low bit of the shift cannot be an input sign bit unless
1200     // the shift amount is >= the size of the datatype, which is undefined.
1201     if (DemandedMask == 1) {
1202       // Perform the logical shift right.
1203       Value *NewVal = BinaryOperator::CreateLShr(
1204                         I->getOperand(0), I->getOperand(1), I->getName());
1205       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1206       return UpdateValueUsesWith(I, NewVal);
1207     }    
1208
1209     // If the sign bit is the only bit demanded by this ashr, then there is no
1210     // need to do it, the shift doesn't change the high bit.
1211     if (DemandedMask.isSignBit())
1212       return UpdateValueUsesWith(I, I->getOperand(0));
1213     
1214     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1216       
1217       // Signed shift right.
1218       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1219       // If any of the "high bits" are demanded, we should set the sign bit as
1220       // demanded.
1221       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1222         DemandedMaskIn.set(BitWidth-1);
1223       if (SimplifyDemandedBits(I->getOperand(0),
1224                                DemandedMaskIn,
1225                                RHSKnownZero, RHSKnownOne, Depth+1))
1226         return true;
1227       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1228              "Bits known to be one AND zero?"); 
1229       // Compute the new bits that are at the top now.
1230       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1231       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1232       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1233         
1234       // Handle the sign bits.
1235       APInt SignBit(APInt::getSignBit(BitWidth));
1236       // Adjust to where it is now in the mask.
1237       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1238         
1239       // If the input sign bit is known to be zero, or if none of the top bits
1240       // are demanded, turn this into an unsigned shift right.
1241       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1242           (HighBits & ~DemandedMask) == HighBits) {
1243         // Perform the logical shift right.
1244         Value *NewVal = BinaryOperator::CreateLShr(
1245                           I->getOperand(0), SA, I->getName());
1246         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1247         return UpdateValueUsesWith(I, NewVal);
1248       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1249         RHSKnownOne |= HighBits;
1250       }
1251     }
1252     break;
1253   case Instruction::SRem:
1254     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1255       APInt RA = Rem->getValue();
1256       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1257         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1258         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1259         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1260                                  LHSKnownZero, LHSKnownOne, Depth+1))
1261           return true;
1262
1263         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1264           LHSKnownZero |= ~LowBits;
1265         else if (LHSKnownOne[BitWidth-1])
1266           LHSKnownOne |= ~LowBits;
1267
1268         KnownZero |= LHSKnownZero & DemandedMask;
1269         KnownOne |= LHSKnownOne & DemandedMask;
1270
1271         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1272       }
1273     }
1274     break;
1275   case Instruction::URem: {
1276     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1277       APInt RA = Rem->getValue();
1278       if (RA.isPowerOf2()) {
1279         APInt LowBits = (RA - 1);
1280         APInt Mask2 = LowBits & DemandedMask;
1281         KnownZero |= ~LowBits & DemandedMask;
1282         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1283                                  KnownZero, KnownOne, Depth+1))
1284           return true;
1285
1286         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1287         break;
1288       }
1289     }
1290
1291     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1292     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1293     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1294                              KnownZero2, KnownOne2, Depth+1))
1295       return true;
1296
1297     uint32_t Leaders = KnownZero2.countLeadingOnes();
1298     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1299                              KnownZero2, KnownOne2, Depth+1))
1300       return true;
1301
1302     Leaders = std::max(Leaders,
1303                        KnownZero2.countLeadingOnes());
1304     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1305     break;
1306   }
1307   case Instruction::Call:
1308     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1309       switch (II->getIntrinsicID()) {
1310       default: break;
1311       case Intrinsic::bswap: {
1312         // If the only bits demanded come from one byte of the bswap result,
1313         // just shift the input byte into position to eliminate the bswap.
1314         unsigned NLZ = DemandedMask.countLeadingZeros();
1315         unsigned NTZ = DemandedMask.countTrailingZeros();
1316           
1317         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1318         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1319         // have 14 leading zeros, round to 8.
1320         NLZ &= ~7;
1321         NTZ &= ~7;
1322         // If we need exactly one byte, we can do this transformation.
1323         if (BitWidth-NLZ-NTZ == 8) {
1324           unsigned ResultBit = NTZ;
1325           unsigned InputBit = BitWidth-NTZ-8;
1326           
1327           // Replace this with either a left or right shift to get the byte into
1328           // the right place.
1329           Instruction *NewVal;
1330           if (InputBit > ResultBit)
1331             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1332                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1333           else
1334             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1335                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1336           NewVal->takeName(I);
1337           InsertNewInstBefore(NewVal, *I);
1338           return UpdateValueUsesWith(I, NewVal);
1339         }
1340           
1341         // TODO: Could compute known zero/one bits based on the input.
1342         break;
1343       }
1344       }
1345     }
1346     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1347     break;
1348   }
1349   
1350   // If the client is only demanding bits that we know, return the known
1351   // constant.
1352   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1353     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1354   return false;
1355 }
1356
1357
1358 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1359 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1360 /// actually used by the caller.  This method analyzes which elements of the
1361 /// operand are undef and returns that information in UndefElts.
1362 ///
1363 /// If the information about demanded elements can be used to simplify the
1364 /// operation, the operation is simplified, then the resultant value is
1365 /// returned.  This returns null if no change was made.
1366 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1367                                                 uint64_t &UndefElts,
1368                                                 unsigned Depth) {
1369   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1370   assert(VWidth <= 64 && "Vector too wide to analyze!");
1371   uint64_t EltMask = ~0ULL >> (64-VWidth);
1372   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1373          "Invalid DemandedElts!");
1374
1375   if (isa<UndefValue>(V)) {
1376     // If the entire vector is undefined, just return this info.
1377     UndefElts = EltMask;
1378     return 0;
1379   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1380     UndefElts = EltMask;
1381     return UndefValue::get(V->getType());
1382   }
1383   
1384   UndefElts = 0;
1385   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1386     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1387     Constant *Undef = UndefValue::get(EltTy);
1388
1389     std::vector<Constant*> Elts;
1390     for (unsigned i = 0; i != VWidth; ++i)
1391       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1392         Elts.push_back(Undef);
1393         UndefElts |= (1ULL << i);
1394       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1395         Elts.push_back(Undef);
1396         UndefElts |= (1ULL << i);
1397       } else {                               // Otherwise, defined.
1398         Elts.push_back(CP->getOperand(i));
1399       }
1400         
1401     // If we changed the constant, return it.
1402     Constant *NewCP = ConstantVector::get(Elts);
1403     return NewCP != CP ? NewCP : 0;
1404   } else if (isa<ConstantAggregateZero>(V)) {
1405     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1406     // set to undef.
1407     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1408     Constant *Zero = Constant::getNullValue(EltTy);
1409     Constant *Undef = UndefValue::get(EltTy);
1410     std::vector<Constant*> Elts;
1411     for (unsigned i = 0; i != VWidth; ++i)
1412       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1413     UndefElts = DemandedElts ^ EltMask;
1414     return ConstantVector::get(Elts);
1415   }
1416   
1417   if (!V->hasOneUse()) {    // Other users may use these bits.
1418     if (Depth != 0) {       // Not at the root.
1419       // TODO: Just compute the UndefElts information recursively.
1420       return false;
1421     }
1422     return false;
1423   } else if (Depth == 10) {        // Limit search depth.
1424     return false;
1425   }
1426   
1427   Instruction *I = dyn_cast<Instruction>(V);
1428   if (!I) return false;        // Only analyze instructions.
1429   
1430   bool MadeChange = false;
1431   uint64_t UndefElts2;
1432   Value *TmpV;
1433   switch (I->getOpcode()) {
1434   default: break;
1435     
1436   case Instruction::InsertElement: {
1437     // If this is a variable index, we don't know which element it overwrites.
1438     // demand exactly the same input as we produce.
1439     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1440     if (Idx == 0) {
1441       // Note that we can't propagate undef elt info, because we don't know
1442       // which elt is getting updated.
1443       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1444                                         UndefElts2, Depth+1);
1445       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1446       break;
1447     }
1448     
1449     // If this is inserting an element that isn't demanded, remove this
1450     // insertelement.
1451     unsigned IdxNo = Idx->getZExtValue();
1452     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1453       return AddSoonDeadInstToWorklist(*I, 0);
1454     
1455     // Otherwise, the element inserted overwrites whatever was there, so the
1456     // input demanded set is simpler than the output set.
1457     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1458                                       DemandedElts & ~(1ULL << IdxNo),
1459                                       UndefElts, Depth+1);
1460     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1461
1462     // The inserted element is defined.
1463     UndefElts |= 1ULL << IdxNo;
1464     break;
1465   }
1466   case Instruction::BitCast: {
1467     // Vector->vector casts only.
1468     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1469     if (!VTy) break;
1470     unsigned InVWidth = VTy->getNumElements();
1471     uint64_t InputDemandedElts = 0;
1472     unsigned Ratio;
1473
1474     if (VWidth == InVWidth) {
1475       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1476       // elements as are demanded of us.
1477       Ratio = 1;
1478       InputDemandedElts = DemandedElts;
1479     } else if (VWidth > InVWidth) {
1480       // Untested so far.
1481       break;
1482       
1483       // If there are more elements in the result than there are in the source,
1484       // then an input element is live if any of the corresponding output
1485       // elements are live.
1486       Ratio = VWidth/InVWidth;
1487       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1488         if (DemandedElts & (1ULL << OutIdx))
1489           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1490       }
1491     } else {
1492       // Untested so far.
1493       break;
1494       
1495       // If there are more elements in the source than there are in the result,
1496       // then an input element is live if the corresponding output element is
1497       // live.
1498       Ratio = InVWidth/VWidth;
1499       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1500         if (DemandedElts & (1ULL << InIdx/Ratio))
1501           InputDemandedElts |= 1ULL << InIdx;
1502     }
1503     
1504     // div/rem demand all inputs, because they don't want divide by zero.
1505     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1506                                       UndefElts2, Depth+1);
1507     if (TmpV) {
1508       I->setOperand(0, TmpV);
1509       MadeChange = true;
1510     }
1511     
1512     UndefElts = UndefElts2;
1513     if (VWidth > InVWidth) {
1514       assert(0 && "Unimp");
1515       // If there are more elements in the result than there are in the source,
1516       // then an output element is undef if the corresponding input element is
1517       // undef.
1518       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1519         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1520           UndefElts |= 1ULL << OutIdx;
1521     } else if (VWidth < InVWidth) {
1522       assert(0 && "Unimp");
1523       // If there are more elements in the source than there are in the result,
1524       // then a result element is undef if all of the corresponding input
1525       // elements are undef.
1526       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1527       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1528         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1529           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1530     }
1531     break;
1532   }
1533   case Instruction::And:
1534   case Instruction::Or:
1535   case Instruction::Xor:
1536   case Instruction::Add:
1537   case Instruction::Sub:
1538   case Instruction::Mul:
1539     // div/rem demand all inputs, because they don't want divide by zero.
1540     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1541                                       UndefElts, Depth+1);
1542     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1544                                       UndefElts2, Depth+1);
1545     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1546       
1547     // Output elements are undefined if both are undefined.  Consider things
1548     // like undef&0.  The result is known zero, not undef.
1549     UndefElts &= UndefElts2;
1550     break;
1551     
1552   case Instruction::Call: {
1553     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1554     if (!II) break;
1555     switch (II->getIntrinsicID()) {
1556     default: break;
1557       
1558     // Binary vector operations that work column-wise.  A dest element is a
1559     // function of the corresponding input elements from the two inputs.
1560     case Intrinsic::x86_sse_sub_ss:
1561     case Intrinsic::x86_sse_mul_ss:
1562     case Intrinsic::x86_sse_min_ss:
1563     case Intrinsic::x86_sse_max_ss:
1564     case Intrinsic::x86_sse2_sub_sd:
1565     case Intrinsic::x86_sse2_mul_sd:
1566     case Intrinsic::x86_sse2_min_sd:
1567     case Intrinsic::x86_sse2_max_sd:
1568       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1569                                         UndefElts, Depth+1);
1570       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1571       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1572                                         UndefElts2, Depth+1);
1573       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1574
1575       // If only the low elt is demanded and this is a scalarizable intrinsic,
1576       // scalarize it now.
1577       if (DemandedElts == 1) {
1578         switch (II->getIntrinsicID()) {
1579         default: break;
1580         case Intrinsic::x86_sse_sub_ss:
1581         case Intrinsic::x86_sse_mul_ss:
1582         case Intrinsic::x86_sse2_sub_sd:
1583         case Intrinsic::x86_sse2_mul_sd:
1584           // TODO: Lower MIN/MAX/ABS/etc
1585           Value *LHS = II->getOperand(1);
1586           Value *RHS = II->getOperand(2);
1587           // Extract the element as scalars.
1588           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1589           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1590           
1591           switch (II->getIntrinsicID()) {
1592           default: assert(0 && "Case stmts out of sync!");
1593           case Intrinsic::x86_sse_sub_ss:
1594           case Intrinsic::x86_sse2_sub_sd:
1595             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1596                                                         II->getName()), *II);
1597             break;
1598           case Intrinsic::x86_sse_mul_ss:
1599           case Intrinsic::x86_sse2_mul_sd:
1600             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1601                                                          II->getName()), *II);
1602             break;
1603           }
1604           
1605           Instruction *New =
1606             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1607                                       II->getName());
1608           InsertNewInstBefore(New, *II);
1609           AddSoonDeadInstToWorklist(*II, 0);
1610           return New;
1611         }            
1612       }
1613         
1614       // Output elements are undefined if both are undefined.  Consider things
1615       // like undef&0.  The result is known zero, not undef.
1616       UndefElts &= UndefElts2;
1617       break;
1618     }
1619     break;
1620   }
1621   }
1622   return MadeChange ? I : 0;
1623 }
1624
1625
1626 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1627 /// function is designed to check a chain of associative operators for a
1628 /// potential to apply a certain optimization.  Since the optimization may be
1629 /// applicable if the expression was reassociated, this checks the chain, then
1630 /// reassociates the expression as necessary to expose the optimization
1631 /// opportunity.  This makes use of a special Functor, which must define
1632 /// 'shouldApply' and 'apply' methods.
1633 ///
1634 template<typename Functor>
1635 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1636   unsigned Opcode = Root.getOpcode();
1637   Value *LHS = Root.getOperand(0);
1638
1639   // Quick check, see if the immediate LHS matches...
1640   if (F.shouldApply(LHS))
1641     return F.apply(Root);
1642
1643   // Otherwise, if the LHS is not of the same opcode as the root, return.
1644   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1645   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1646     // Should we apply this transform to the RHS?
1647     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1648
1649     // If not to the RHS, check to see if we should apply to the LHS...
1650     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1651       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1652       ShouldApply = true;
1653     }
1654
1655     // If the functor wants to apply the optimization to the RHS of LHSI,
1656     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1657     if (ShouldApply) {
1658       BasicBlock *BB = Root.getParent();
1659
1660       // Now all of the instructions are in the current basic block, go ahead
1661       // and perform the reassociation.
1662       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1663
1664       // First move the selected RHS to the LHS of the root...
1665       Root.setOperand(0, LHSI->getOperand(1));
1666
1667       // Make what used to be the LHS of the root be the user of the root...
1668       Value *ExtraOperand = TmpLHSI->getOperand(1);
1669       if (&Root == TmpLHSI) {
1670         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1671         return 0;
1672       }
1673       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1674       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1675       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1676       BasicBlock::iterator ARI = &Root; ++ARI;
1677       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1678       ARI = Root;
1679
1680       // Now propagate the ExtraOperand down the chain of instructions until we
1681       // get to LHSI.
1682       while (TmpLHSI != LHSI) {
1683         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1684         // Move the instruction to immediately before the chain we are
1685         // constructing to avoid breaking dominance properties.
1686         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1687         BB->getInstList().insert(ARI, NextLHSI);
1688         ARI = NextLHSI;
1689
1690         Value *NextOp = NextLHSI->getOperand(1);
1691         NextLHSI->setOperand(1, ExtraOperand);
1692         TmpLHSI = NextLHSI;
1693         ExtraOperand = NextOp;
1694       }
1695
1696       // Now that the instructions are reassociated, have the functor perform
1697       // the transformation...
1698       return F.apply(Root);
1699     }
1700
1701     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1702   }
1703   return 0;
1704 }
1705
1706 namespace {
1707
1708 // AddRHS - Implements: X + X --> X << 1
1709 struct AddRHS {
1710   Value *RHS;
1711   AddRHS(Value *rhs) : RHS(rhs) {}
1712   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1713   Instruction *apply(BinaryOperator &Add) const {
1714     return BinaryOperator::CreateShl(Add.getOperand(0),
1715                                      ConstantInt::get(Add.getType(), 1));
1716   }
1717 };
1718
1719 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1720 //                 iff C1&C2 == 0
1721 struct AddMaskingAnd {
1722   Constant *C2;
1723   AddMaskingAnd(Constant *c) : C2(c) {}
1724   bool shouldApply(Value *LHS) const {
1725     ConstantInt *C1;
1726     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1727            ConstantExpr::getAnd(C1, C2)->isNullValue();
1728   }
1729   Instruction *apply(BinaryOperator &Add) const {
1730     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1731   }
1732 };
1733
1734 }
1735
1736 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1737                                              InstCombiner *IC) {
1738   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1739     if (Constant *SOC = dyn_cast<Constant>(SO))
1740       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1741
1742     return IC->InsertNewInstBefore(CastInst::Create(
1743           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1744   }
1745
1746   // Figure out if the constant is the left or the right argument.
1747   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1748   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1749
1750   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1751     if (ConstIsRHS)
1752       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1753     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1754   }
1755
1756   Value *Op0 = SO, *Op1 = ConstOperand;
1757   if (!ConstIsRHS)
1758     std::swap(Op0, Op1);
1759   Instruction *New;
1760   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1761     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1762   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1763     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1764                           SO->getName()+".cmp");
1765   else {
1766     assert(0 && "Unknown binary instruction type!");
1767     abort();
1768   }
1769   return IC->InsertNewInstBefore(New, I);
1770 }
1771
1772 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1773 // constant as the other operand, try to fold the binary operator into the
1774 // select arguments.  This also works for Cast instructions, which obviously do
1775 // not have a second operand.
1776 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1777                                      InstCombiner *IC) {
1778   // Don't modify shared select instructions
1779   if (!SI->hasOneUse()) return 0;
1780   Value *TV = SI->getOperand(1);
1781   Value *FV = SI->getOperand(2);
1782
1783   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1784     // Bool selects with constant operands can be folded to logical ops.
1785     if (SI->getType() == Type::Int1Ty) return 0;
1786
1787     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1788     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1789
1790     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1791                               SelectFalseVal);
1792   }
1793   return 0;
1794 }
1795
1796
1797 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1798 /// node as operand #0, see if we can fold the instruction into the PHI (which
1799 /// is only possible if all operands to the PHI are constants).
1800 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1801   PHINode *PN = cast<PHINode>(I.getOperand(0));
1802   unsigned NumPHIValues = PN->getNumIncomingValues();
1803   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1804
1805   // Check to see if all of the operands of the PHI are constants.  If there is
1806   // one non-constant value, remember the BB it is.  If there is more than one
1807   // or if *it* is a PHI, bail out.
1808   BasicBlock *NonConstBB = 0;
1809   for (unsigned i = 0; i != NumPHIValues; ++i)
1810     if (!isa<Constant>(PN->getIncomingValue(i))) {
1811       if (NonConstBB) return 0;  // More than one non-const value.
1812       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1813       NonConstBB = PN->getIncomingBlock(i);
1814       
1815       // If the incoming non-constant value is in I's block, we have an infinite
1816       // loop.
1817       if (NonConstBB == I.getParent())
1818         return 0;
1819     }
1820   
1821   // If there is exactly one non-constant value, we can insert a copy of the
1822   // operation in that block.  However, if this is a critical edge, we would be
1823   // inserting the computation one some other paths (e.g. inside a loop).  Only
1824   // do this if the pred block is unconditionally branching into the phi block.
1825   if (NonConstBB) {
1826     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1827     if (!BI || !BI->isUnconditional()) return 0;
1828   }
1829
1830   // Okay, we can do the transformation: create the new PHI node.
1831   PHINode *NewPN = PHINode::Create(I.getType(), "");
1832   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1833   InsertNewInstBefore(NewPN, *PN);
1834   NewPN->takeName(PN);
1835
1836   // Next, add all of the operands to the PHI.
1837   if (I.getNumOperands() == 2) {
1838     Constant *C = cast<Constant>(I.getOperand(1));
1839     for (unsigned i = 0; i != NumPHIValues; ++i) {
1840       Value *InV = 0;
1841       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1842         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1843           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1844         else
1845           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1846       } else {
1847         assert(PN->getIncomingBlock(i) == NonConstBB);
1848         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1849           InV = BinaryOperator::Create(BO->getOpcode(),
1850                                        PN->getIncomingValue(i), C, "phitmp",
1851                                        NonConstBB->getTerminator());
1852         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1853           InV = CmpInst::Create(CI->getOpcode(), 
1854                                 CI->getPredicate(),
1855                                 PN->getIncomingValue(i), C, "phitmp",
1856                                 NonConstBB->getTerminator());
1857         else
1858           assert(0 && "Unknown binop!");
1859         
1860         AddToWorkList(cast<Instruction>(InV));
1861       }
1862       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1863     }
1864   } else { 
1865     CastInst *CI = cast<CastInst>(&I);
1866     const Type *RetTy = CI->getType();
1867     for (unsigned i = 0; i != NumPHIValues; ++i) {
1868       Value *InV;
1869       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1870         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1871       } else {
1872         assert(PN->getIncomingBlock(i) == NonConstBB);
1873         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1874                                I.getType(), "phitmp", 
1875                                NonConstBB->getTerminator());
1876         AddToWorkList(cast<Instruction>(InV));
1877       }
1878       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1879     }
1880   }
1881   return ReplaceInstUsesWith(I, NewPN);
1882 }
1883
1884
1885 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1886 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1887 /// This basically requires proving that the add in the original type would not
1888 /// overflow to change the sign bit or have a carry out.
1889 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1890   // There are different heuristics we can use for this.  Here are some simple
1891   // ones.
1892   
1893   // Add has the property that adding any two 2's complement numbers can only 
1894   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1895   // have at least two sign bits, we know that the addition of the two values will
1896   // sign extend fine.
1897   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1898     return true;
1899   
1900   
1901   // If one of the operands only has one non-zero bit, and if the other operand
1902   // has a known-zero bit in a more significant place than it (not including the
1903   // sign bit) the ripple may go up to and fill the zero, but won't change the
1904   // sign.  For example, (X & ~4) + 1.
1905   
1906   // TODO: Implement.
1907   
1908   return false;
1909 }
1910
1911
1912 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1913   bool Changed = SimplifyCommutative(I);
1914   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1915
1916   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1917     // X + undef -> undef
1918     if (isa<UndefValue>(RHS))
1919       return ReplaceInstUsesWith(I, RHS);
1920
1921     // X + 0 --> X
1922     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1923       if (RHSC->isNullValue())
1924         return ReplaceInstUsesWith(I, LHS);
1925     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1926       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1927                               (I.getType())->getValueAPF()))
1928         return ReplaceInstUsesWith(I, LHS);
1929     }
1930
1931     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1932       // X + (signbit) --> X ^ signbit
1933       const APInt& Val = CI->getValue();
1934       uint32_t BitWidth = Val.getBitWidth();
1935       if (Val == APInt::getSignBit(BitWidth))
1936         return BinaryOperator::CreateXor(LHS, RHS);
1937       
1938       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1939       // (X & 254)+1 -> (X&254)|1
1940       if (!isa<VectorType>(I.getType())) {
1941         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1942         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1943                                  KnownZero, KnownOne))
1944           return &I;
1945       }
1946     }
1947
1948     if (isa<PHINode>(LHS))
1949       if (Instruction *NV = FoldOpIntoPhi(I))
1950         return NV;
1951     
1952     ConstantInt *XorRHS = 0;
1953     Value *XorLHS = 0;
1954     if (isa<ConstantInt>(RHSC) &&
1955         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1956       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1957       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1958       
1959       uint32_t Size = TySizeBits / 2;
1960       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1961       APInt CFF80Val(-C0080Val);
1962       do {
1963         if (TySizeBits > Size) {
1964           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1965           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1966           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1967               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1968             // This is a sign extend if the top bits are known zero.
1969             if (!MaskedValueIsZero(XorLHS, 
1970                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1971               Size = 0;  // Not a sign ext, but can't be any others either.
1972             break;
1973           }
1974         }
1975         Size >>= 1;
1976         C0080Val = APIntOps::lshr(C0080Val, Size);
1977         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1978       } while (Size >= 1);
1979       
1980       // FIXME: This shouldn't be necessary. When the backends can handle types
1981       // with funny bit widths then this switch statement should be removed. It
1982       // is just here to get the size of the "middle" type back up to something
1983       // that the back ends can handle.
1984       const Type *MiddleType = 0;
1985       switch (Size) {
1986         default: break;
1987         case 32: MiddleType = Type::Int32Ty; break;
1988         case 16: MiddleType = Type::Int16Ty; break;
1989         case  8: MiddleType = Type::Int8Ty; break;
1990       }
1991       if (MiddleType) {
1992         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1993         InsertNewInstBefore(NewTrunc, I);
1994         return new SExtInst(NewTrunc, I.getType(), I.getName());
1995       }
1996     }
1997   }
1998
1999   if (I.getType() == Type::Int1Ty)
2000     return BinaryOperator::CreateXor(LHS, RHS);
2001
2002   // X + X --> X << 1
2003   if (I.getType()->isInteger()) {
2004     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2005
2006     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2007       if (RHSI->getOpcode() == Instruction::Sub)
2008         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2009           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2010     }
2011     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2012       if (LHSI->getOpcode() == Instruction::Sub)
2013         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2014           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2015     }
2016   }
2017
2018   // -A + B  -->  B - A
2019   // -A + -B  -->  -(A + B)
2020   if (Value *LHSV = dyn_castNegVal(LHS)) {
2021     if (LHS->getType()->isIntOrIntVector()) {
2022       if (Value *RHSV = dyn_castNegVal(RHS)) {
2023         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2024         InsertNewInstBefore(NewAdd, I);
2025         return BinaryOperator::CreateNeg(NewAdd);
2026       }
2027     }
2028     
2029     return BinaryOperator::CreateSub(RHS, LHSV);
2030   }
2031
2032   // A + -B  -->  A - B
2033   if (!isa<Constant>(RHS))
2034     if (Value *V = dyn_castNegVal(RHS))
2035       return BinaryOperator::CreateSub(LHS, V);
2036
2037
2038   ConstantInt *C2;
2039   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2040     if (X == RHS)   // X*C + X --> X * (C+1)
2041       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2042
2043     // X*C1 + X*C2 --> X * (C1+C2)
2044     ConstantInt *C1;
2045     if (X == dyn_castFoldableMul(RHS, C1))
2046       return BinaryOperator::CreateMul(X, Add(C1, C2));
2047   }
2048
2049   // X + X*C --> X * (C+1)
2050   if (dyn_castFoldableMul(RHS, C2) == LHS)
2051     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2052
2053   // X + ~X --> -1   since   ~X = -X-1
2054   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2055     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2056   
2057
2058   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2059   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2060     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2061       return R;
2062   
2063   // A+B --> A|B iff A and B have no bits set in common.
2064   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2065     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2066     APInt LHSKnownOne(IT->getBitWidth(), 0);
2067     APInt LHSKnownZero(IT->getBitWidth(), 0);
2068     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2069     if (LHSKnownZero != 0) {
2070       APInt RHSKnownOne(IT->getBitWidth(), 0);
2071       APInt RHSKnownZero(IT->getBitWidth(), 0);
2072       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2073       
2074       // No bits in common -> bitwise or.
2075       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2076         return BinaryOperator::CreateOr(LHS, RHS);
2077     }
2078   }
2079
2080   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2081   if (I.getType()->isIntOrIntVector()) {
2082     Value *W, *X, *Y, *Z;
2083     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2084         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2085       if (W != Y) {
2086         if (W == Z) {
2087           std::swap(Y, Z);
2088         } else if (Y == X) {
2089           std::swap(W, X);
2090         } else if (X == Z) {
2091           std::swap(Y, Z);
2092           std::swap(W, X);
2093         }
2094       }
2095
2096       if (W == Y) {
2097         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2098                                                             LHS->getName()), I);
2099         return BinaryOperator::CreateMul(W, NewAdd);
2100       }
2101     }
2102   }
2103
2104   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2105     Value *X = 0;
2106     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2107       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2108
2109     // (X & FF00) + xx00  -> (X+xx00) & FF00
2110     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2111       Constant *Anded = And(CRHS, C2);
2112       if (Anded == CRHS) {
2113         // See if all bits from the first bit set in the Add RHS up are included
2114         // in the mask.  First, get the rightmost bit.
2115         const APInt& AddRHSV = CRHS->getValue();
2116
2117         // Form a mask of all bits from the lowest bit added through the top.
2118         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2119
2120         // See if the and mask includes all of these bits.
2121         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2122
2123         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2124           // Okay, the xform is safe.  Insert the new add pronto.
2125           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2126                                                             LHS->getName()), I);
2127           return BinaryOperator::CreateAnd(NewAdd, C2);
2128         }
2129       }
2130     }
2131
2132     // Try to fold constant add into select arguments.
2133     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2134       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2135         return R;
2136   }
2137
2138   // add (cast *A to intptrtype) B -> 
2139   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2140   {
2141     CastInst *CI = dyn_cast<CastInst>(LHS);
2142     Value *Other = RHS;
2143     if (!CI) {
2144       CI = dyn_cast<CastInst>(RHS);
2145       Other = LHS;
2146     }
2147     if (CI && CI->getType()->isSized() && 
2148         (CI->getType()->getPrimitiveSizeInBits() == 
2149          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2150         && isa<PointerType>(CI->getOperand(0)->getType())) {
2151       unsigned AS =
2152         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2153       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2154                                       PointerType::get(Type::Int8Ty, AS), I);
2155       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2156       return new PtrToIntInst(I2, CI->getType());
2157     }
2158   }
2159   
2160   // add (select X 0 (sub n A)) A  -->  select X A n
2161   {
2162     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2163     Value *Other = RHS;
2164     if (!SI) {
2165       SI = dyn_cast<SelectInst>(RHS);
2166       Other = LHS;
2167     }
2168     if (SI && SI->hasOneUse()) {
2169       Value *TV = SI->getTrueValue();
2170       Value *FV = SI->getFalseValue();
2171       Value *A, *N;
2172
2173       // Can we fold the add into the argument of the select?
2174       // We check both true and false select arguments for a matching subtract.
2175       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2176           A == Other)  // Fold the add into the true select value.
2177         return SelectInst::Create(SI->getCondition(), N, A);
2178       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2179           A == Other)  // Fold the add into the false select value.
2180         return SelectInst::Create(SI->getCondition(), A, N);
2181     }
2182   }
2183   
2184   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2185   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2186     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2187       return ReplaceInstUsesWith(I, LHS);
2188
2189   // Check for (add (sext x), y), see if we can merge this into an
2190   // integer add followed by a sext.
2191   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2192     // (add (sext x), cst) --> (sext (add x, cst'))
2193     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2194       Constant *CI = 
2195         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2196       if (LHSConv->hasOneUse() &&
2197           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2198           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2199         // Insert the new, smaller add.
2200         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2201                                                         CI, "addconv");
2202         InsertNewInstBefore(NewAdd, I);
2203         return new SExtInst(NewAdd, I.getType());
2204       }
2205     }
2206     
2207     // (add (sext x), (sext y)) --> (sext (add int x, y))
2208     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2209       // Only do this if x/y have the same type, if at last one of them has a
2210       // single use (so we don't increase the number of sexts), and if the
2211       // integer add will not overflow.
2212       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2213           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2214           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2215                                    RHSConv->getOperand(0))) {
2216         // Insert the new integer add.
2217         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2218                                                         RHSConv->getOperand(0),
2219                                                         "addconv");
2220         InsertNewInstBefore(NewAdd, I);
2221         return new SExtInst(NewAdd, I.getType());
2222       }
2223     }
2224   }
2225   
2226   // Check for (add double (sitofp x), y), see if we can merge this into an
2227   // integer add followed by a promotion.
2228   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2229     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2230     // ... if the constant fits in the integer value.  This is useful for things
2231     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2232     // requires a constant pool load, and generally allows the add to be better
2233     // instcombined.
2234     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2235       Constant *CI = 
2236       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2237       if (LHSConv->hasOneUse() &&
2238           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2239           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2240         // Insert the new integer add.
2241         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2242                                                         CI, "addconv");
2243         InsertNewInstBefore(NewAdd, I);
2244         return new SIToFPInst(NewAdd, I.getType());
2245       }
2246     }
2247     
2248     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2249     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2250       // Only do this if x/y have the same type, if at last one of them has a
2251       // single use (so we don't increase the number of int->fp conversions),
2252       // and if the integer add will not overflow.
2253       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2254           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2255           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2256                                    RHSConv->getOperand(0))) {
2257         // Insert the new integer add.
2258         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2259                                                         RHSConv->getOperand(0),
2260                                                         "addconv");
2261         InsertNewInstBefore(NewAdd, I);
2262         return new SIToFPInst(NewAdd, I.getType());
2263       }
2264     }
2265   }
2266   
2267   return Changed ? &I : 0;
2268 }
2269
2270 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2271   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2272
2273   if (Op0 == Op1)         // sub X, X  -> 0
2274     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2275
2276   // If this is a 'B = x-(-A)', change to B = x+A...
2277   if (Value *V = dyn_castNegVal(Op1))
2278     return BinaryOperator::CreateAdd(Op0, V);
2279
2280   if (isa<UndefValue>(Op0))
2281     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2282   if (isa<UndefValue>(Op1))
2283     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2284
2285   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2286     // Replace (-1 - A) with (~A)...
2287     if (C->isAllOnesValue())
2288       return BinaryOperator::CreateNot(Op1);
2289
2290     // C - ~X == X + (1+C)
2291     Value *X = 0;
2292     if (match(Op1, m_Not(m_Value(X))))
2293       return BinaryOperator::CreateAdd(X, AddOne(C));
2294
2295     // -(X >>u 31) -> (X >>s 31)
2296     // -(X >>s 31) -> (X >>u 31)
2297     if (C->isZero()) {
2298       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2299         if (SI->getOpcode() == Instruction::LShr) {
2300           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2301             // Check to see if we are shifting out everything but the sign bit.
2302             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2303                 SI->getType()->getPrimitiveSizeInBits()-1) {
2304               // Ok, the transformation is safe.  Insert AShr.
2305               return BinaryOperator::Create(Instruction::AShr, 
2306                                           SI->getOperand(0), CU, SI->getName());
2307             }
2308           }
2309         }
2310         else if (SI->getOpcode() == Instruction::AShr) {
2311           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2312             // Check to see if we are shifting out everything but the sign bit.
2313             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2314                 SI->getType()->getPrimitiveSizeInBits()-1) {
2315               // Ok, the transformation is safe.  Insert LShr. 
2316               return BinaryOperator::CreateLShr(
2317                                           SI->getOperand(0), CU, SI->getName());
2318             }
2319           }
2320         }
2321       }
2322     }
2323
2324     // Try to fold constant sub into select arguments.
2325     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2326       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2327         return R;
2328
2329     if (isa<PHINode>(Op0))
2330       if (Instruction *NV = FoldOpIntoPhi(I))
2331         return NV;
2332   }
2333
2334   if (I.getType() == Type::Int1Ty)
2335     return BinaryOperator::CreateXor(Op0, Op1);
2336
2337   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2338     if (Op1I->getOpcode() == Instruction::Add &&
2339         !Op0->getType()->isFPOrFPVector()) {
2340       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2341         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2342       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2343         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2344       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2345         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2346           // C1-(X+C2) --> (C1-C2)-X
2347           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2348                                            Op1I->getOperand(0));
2349       }
2350     }
2351
2352     if (Op1I->hasOneUse()) {
2353       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2354       // is not used by anyone else...
2355       //
2356       if (Op1I->getOpcode() == Instruction::Sub &&
2357           !Op1I->getType()->isFPOrFPVector()) {
2358         // Swap the two operands of the subexpr...
2359         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2360         Op1I->setOperand(0, IIOp1);
2361         Op1I->setOperand(1, IIOp0);
2362
2363         // Create the new top level add instruction...
2364         return BinaryOperator::CreateAdd(Op0, Op1);
2365       }
2366
2367       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2368       //
2369       if (Op1I->getOpcode() == Instruction::And &&
2370           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2371         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2372
2373         Value *NewNot =
2374           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2375         return BinaryOperator::CreateAnd(Op0, NewNot);
2376       }
2377
2378       // 0 - (X sdiv C)  -> (X sdiv -C)
2379       if (Op1I->getOpcode() == Instruction::SDiv)
2380         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2381           if (CSI->isZero())
2382             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2383               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2384                                                ConstantExpr::getNeg(DivRHS));
2385
2386       // X - X*C --> X * (1-C)
2387       ConstantInt *C2 = 0;
2388       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2389         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2390         return BinaryOperator::CreateMul(Op0, CP1);
2391       }
2392
2393       // X - ((X / Y) * Y) --> X % Y
2394       if (Op1I->getOpcode() == Instruction::Mul)
2395         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2396           if (Op0 == I->getOperand(0) &&
2397               Op1I->getOperand(1) == I->getOperand(1)) {
2398             if (I->getOpcode() == Instruction::SDiv)
2399               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2400             if (I->getOpcode() == Instruction::UDiv)
2401               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2402           }
2403     }
2404   }
2405
2406   if (!Op0->getType()->isFPOrFPVector())
2407     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2408       if (Op0I->getOpcode() == Instruction::Add) {
2409         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2410           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2411         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2412           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2413       } else if (Op0I->getOpcode() == Instruction::Sub) {
2414         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2415           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2416       }
2417     }
2418
2419   ConstantInt *C1;
2420   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2421     if (X == Op1)  // X*C - X --> X * (C-1)
2422       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2423
2424     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2425     if (X == dyn_castFoldableMul(Op1, C2))
2426       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2427   }
2428   return 0;
2429 }
2430
2431 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2432 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2433 /// TrueIfSigned if the result of the comparison is true when the input value is
2434 /// signed.
2435 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2436                            bool &TrueIfSigned) {
2437   switch (pred) {
2438   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2439     TrueIfSigned = true;
2440     return RHS->isZero();
2441   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2442     TrueIfSigned = true;
2443     return RHS->isAllOnesValue();
2444   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2445     TrueIfSigned = false;
2446     return RHS->isAllOnesValue();
2447   case ICmpInst::ICMP_UGT:
2448     // True if LHS u> RHS and RHS == high-bit-mask - 1
2449     TrueIfSigned = true;
2450     return RHS->getValue() ==
2451       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2452   case ICmpInst::ICMP_UGE: 
2453     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2454     TrueIfSigned = true;
2455     return RHS->getValue().isSignBit();
2456   default:
2457     return false;
2458   }
2459 }
2460
2461 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2462   bool Changed = SimplifyCommutative(I);
2463   Value *Op0 = I.getOperand(0);
2464
2465   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2466     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2467
2468   // Simplify mul instructions with a constant RHS...
2469   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2470     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2471
2472       // ((X << C1)*C2) == (X * (C2 << C1))
2473       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2474         if (SI->getOpcode() == Instruction::Shl)
2475           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2476             return BinaryOperator::CreateMul(SI->getOperand(0),
2477                                              ConstantExpr::getShl(CI, ShOp));
2478
2479       if (CI->isZero())
2480         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2481       if (CI->equalsInt(1))                  // X * 1  == X
2482         return ReplaceInstUsesWith(I, Op0);
2483       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2484         return BinaryOperator::CreateNeg(Op0, I.getName());
2485
2486       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2487       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2488         return BinaryOperator::CreateShl(Op0,
2489                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2490       }
2491     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2492       if (Op1F->isNullValue())
2493         return ReplaceInstUsesWith(I, Op1);
2494
2495       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2496       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2497       // We need a better interface for long double here.
2498       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2499         if (Op1F->isExactlyValue(1.0))
2500           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2501     }
2502     
2503     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2504       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2505           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2506         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2507         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2508                                                      Op1, "tmp");
2509         InsertNewInstBefore(Add, I);
2510         Value *C1C2 = ConstantExpr::getMul(Op1, 
2511                                            cast<Constant>(Op0I->getOperand(1)));
2512         return BinaryOperator::CreateAdd(Add, C1C2);
2513         
2514       }
2515
2516     // Try to fold constant mul into select arguments.
2517     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2518       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2519         return R;
2520
2521     if (isa<PHINode>(Op0))
2522       if (Instruction *NV = FoldOpIntoPhi(I))
2523         return NV;
2524   }
2525
2526   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2527     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2528       return BinaryOperator::CreateMul(Op0v, Op1v);
2529
2530   if (I.getType() == Type::Int1Ty)
2531     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2532
2533   // If one of the operands of the multiply is a cast from a boolean value, then
2534   // we know the bool is either zero or one, so this is a 'masking' multiply.
2535   // See if we can simplify things based on how the boolean was originally
2536   // formed.
2537   CastInst *BoolCast = 0;
2538   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2539     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2540       BoolCast = CI;
2541   if (!BoolCast)
2542     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2543       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2544         BoolCast = CI;
2545   if (BoolCast) {
2546     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2547       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2548       const Type *SCOpTy = SCIOp0->getType();
2549       bool TIS = false;
2550       
2551       // If the icmp is true iff the sign bit of X is set, then convert this
2552       // multiply into a shift/and combination.
2553       if (isa<ConstantInt>(SCIOp1) &&
2554           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2555           TIS) {
2556         // Shift the X value right to turn it into "all signbits".
2557         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2558                                           SCOpTy->getPrimitiveSizeInBits()-1);
2559         Value *V =
2560           InsertNewInstBefore(
2561             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2562                                             BoolCast->getOperand(0)->getName()+
2563                                             ".mask"), I);
2564
2565         // If the multiply type is not the same as the source type, sign extend
2566         // or truncate to the multiply type.
2567         if (I.getType() != V->getType()) {
2568           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2569           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2570           Instruction::CastOps opcode = 
2571             (SrcBits == DstBits ? Instruction::BitCast : 
2572              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2573           V = InsertCastBefore(opcode, V, I.getType(), I);
2574         }
2575
2576         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2577         return BinaryOperator::CreateAnd(V, OtherOp);
2578       }
2579     }
2580   }
2581
2582   return Changed ? &I : 0;
2583 }
2584
2585 /// This function implements the transforms on div instructions that work
2586 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2587 /// used by the visitors to those instructions.
2588 /// @brief Transforms common to all three div instructions
2589 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2590   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2591
2592   // undef / X -> 0        for integer.
2593   // undef / X -> undef    for FP (the undef could be a snan).
2594   if (isa<UndefValue>(Op0)) {
2595     if (Op0->getType()->isFPOrFPVector())
2596       return ReplaceInstUsesWith(I, Op0);
2597     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2598   }
2599
2600   // X / undef -> undef
2601   if (isa<UndefValue>(Op1))
2602     return ReplaceInstUsesWith(I, Op1);
2603
2604   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2605   // This does not apply for fdiv.
2606   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2607     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2608     // the same basic block, then we replace the select with Y, and the
2609     // condition of the select with false (if the cond value is in the same BB).
2610     // If the select has uses other than the div, this allows them to be
2611     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2612     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2613       if (ST->isNullValue()) {
2614         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2615         if (CondI && CondI->getParent() == I.getParent())
2616           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2617         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2618           I.setOperand(1, SI->getOperand(2));
2619         else
2620           UpdateValueUsesWith(SI, SI->getOperand(2));
2621         return &I;
2622       }
2623
2624     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2625     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2626       if (ST->isNullValue()) {
2627         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2628         if (CondI && CondI->getParent() == I.getParent())
2629           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2630         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2631           I.setOperand(1, SI->getOperand(1));
2632         else
2633           UpdateValueUsesWith(SI, SI->getOperand(1));
2634         return &I;
2635       }
2636   }
2637
2638   return 0;
2639 }
2640
2641 /// This function implements the transforms common to both integer division
2642 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2643 /// division instructions.
2644 /// @brief Common integer divide transforms
2645 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2646   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2647
2648   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2649   if (Op0 == Op1) {
2650     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2651       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2652       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2653       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2654     }
2655
2656     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2657     return ReplaceInstUsesWith(I, CI);
2658   }
2659   
2660   if (Instruction *Common = commonDivTransforms(I))
2661     return Common;
2662
2663   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2664     // div X, 1 == X
2665     if (RHS->equalsInt(1))
2666       return ReplaceInstUsesWith(I, Op0);
2667
2668     // (X / C1) / C2  -> X / (C1*C2)
2669     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2670       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2671         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2672           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2673             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2674           else 
2675             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2676                                           Multiply(RHS, LHSRHS));
2677         }
2678
2679     if (!RHS->isZero()) { // avoid X udiv 0
2680       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2681         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2682           return R;
2683       if (isa<PHINode>(Op0))
2684         if (Instruction *NV = FoldOpIntoPhi(I))
2685           return NV;
2686     }
2687   }
2688
2689   // 0 / X == 0, we don't need to preserve faults!
2690   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2691     if (LHS->equalsInt(0))
2692       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2693
2694   // It can't be division by zero, hence it must be division by one.
2695   if (I.getType() == Type::Int1Ty)
2696     return ReplaceInstUsesWith(I, Op0);
2697
2698   return 0;
2699 }
2700
2701 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2702   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2703
2704   // Handle the integer div common cases
2705   if (Instruction *Common = commonIDivTransforms(I))
2706     return Common;
2707
2708   // X udiv C^2 -> X >> C
2709   // Check to see if this is an unsigned division with an exact power of 2,
2710   // if so, convert to a right shift.
2711   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2712     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2713       return BinaryOperator::CreateLShr(Op0, 
2714                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2715   }
2716
2717   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2718   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2719     if (RHSI->getOpcode() == Instruction::Shl &&
2720         isa<ConstantInt>(RHSI->getOperand(0))) {
2721       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2722       if (C1.isPowerOf2()) {
2723         Value *N = RHSI->getOperand(1);
2724         const Type *NTy = N->getType();
2725         if (uint32_t C2 = C1.logBase2()) {
2726           Constant *C2V = ConstantInt::get(NTy, C2);
2727           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2728         }
2729         return BinaryOperator::CreateLShr(Op0, N);
2730       }
2731     }
2732   }
2733   
2734   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2735   // where C1&C2 are powers of two.
2736   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2737     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2738       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2739         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2740         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2741           // Compute the shift amounts
2742           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2743           // Construct the "on true" case of the select
2744           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2745           Instruction *TSI = BinaryOperator::CreateLShr(
2746                                                  Op0, TC, SI->getName()+".t");
2747           TSI = InsertNewInstBefore(TSI, I);
2748   
2749           // Construct the "on false" case of the select
2750           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2751           Instruction *FSI = BinaryOperator::CreateLShr(
2752                                                  Op0, FC, SI->getName()+".f");
2753           FSI = InsertNewInstBefore(FSI, I);
2754
2755           // construct the select instruction and return it.
2756           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2757         }
2758       }
2759   return 0;
2760 }
2761
2762 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2763   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2764
2765   // Handle the integer div common cases
2766   if (Instruction *Common = commonIDivTransforms(I))
2767     return Common;
2768
2769   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2770     // sdiv X, -1 == -X
2771     if (RHS->isAllOnesValue())
2772       return BinaryOperator::CreateNeg(Op0);
2773
2774     // -X/C -> X/-C
2775     if (Value *LHSNeg = dyn_castNegVal(Op0))
2776       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2777   }
2778
2779   // If the sign bits of both operands are zero (i.e. we can prove they are
2780   // unsigned inputs), turn this into a udiv.
2781   if (I.getType()->isInteger()) {
2782     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2783     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2784       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2785       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2786     }
2787   }      
2788   
2789   return 0;
2790 }
2791
2792 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2793   return commonDivTransforms(I);
2794 }
2795
2796 /// This function implements the transforms on rem instructions that work
2797 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2798 /// is used by the visitors to those instructions.
2799 /// @brief Transforms common to all three rem instructions
2800 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2801   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2802
2803   // 0 % X == 0 for integer, we don't need to preserve faults!
2804   if (Constant *LHS = dyn_cast<Constant>(Op0))
2805     if (LHS->isNullValue())
2806       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2807
2808   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2809     if (I.getType()->isFPOrFPVector())
2810       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2811     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2812   }
2813   if (isa<UndefValue>(Op1))
2814     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2815
2816   // Handle cases involving: rem X, (select Cond, Y, Z)
2817   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2818     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2819     // the same basic block, then we replace the select with Y, and the
2820     // condition of the select with false (if the cond value is in the same
2821     // BB).  If the select has uses other than the div, this allows them to be
2822     // simplified also.
2823     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2824       if (ST->isNullValue()) {
2825         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2826         if (CondI && CondI->getParent() == I.getParent())
2827           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2828         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2829           I.setOperand(1, SI->getOperand(2));
2830         else
2831           UpdateValueUsesWith(SI, SI->getOperand(2));
2832         return &I;
2833       }
2834     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2835     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2836       if (ST->isNullValue()) {
2837         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2838         if (CondI && CondI->getParent() == I.getParent())
2839           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2840         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2841           I.setOperand(1, SI->getOperand(1));
2842         else
2843           UpdateValueUsesWith(SI, SI->getOperand(1));
2844         return &I;
2845       }
2846   }
2847
2848   return 0;
2849 }
2850
2851 /// This function implements the transforms common to both integer remainder
2852 /// instructions (urem and srem). It is called by the visitors to those integer
2853 /// remainder instructions.
2854 /// @brief Common integer remainder transforms
2855 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2856   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2857
2858   if (Instruction *common = commonRemTransforms(I))
2859     return common;
2860
2861   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2862     // X % 0 == undef, we don't need to preserve faults!
2863     if (RHS->equalsInt(0))
2864       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2865     
2866     if (RHS->equalsInt(1))  // X % 1 == 0
2867       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2868
2869     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2870       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2871         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2872           return R;
2873       } else if (isa<PHINode>(Op0I)) {
2874         if (Instruction *NV = FoldOpIntoPhi(I))
2875           return NV;
2876       }
2877
2878       // See if we can fold away this rem instruction.
2879       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2880       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2881       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2882                                KnownZero, KnownOne))
2883         return &I;
2884     }
2885   }
2886
2887   return 0;
2888 }
2889
2890 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2891   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2892
2893   if (Instruction *common = commonIRemTransforms(I))
2894     return common;
2895   
2896   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2897     // X urem C^2 -> X and C
2898     // Check to see if this is an unsigned remainder with an exact power of 2,
2899     // if so, convert to a bitwise and.
2900     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2901       if (C->getValue().isPowerOf2())
2902         return BinaryOperator::CreateAnd(Op0, SubOne(C));
2903   }
2904
2905   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2906     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2907     if (RHSI->getOpcode() == Instruction::Shl &&
2908         isa<ConstantInt>(RHSI->getOperand(0))) {
2909       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2910         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2911         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2912                                                                    "tmp"), I);
2913         return BinaryOperator::CreateAnd(Op0, Add);
2914       }
2915     }
2916   }
2917
2918   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2919   // where C1&C2 are powers of two.
2920   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2921     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2922       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2923         // STO == 0 and SFO == 0 handled above.
2924         if ((STO->getValue().isPowerOf2()) && 
2925             (SFO->getValue().isPowerOf2())) {
2926           Value *TrueAnd = InsertNewInstBefore(
2927             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2928           Value *FalseAnd = InsertNewInstBefore(
2929             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2930           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2931         }
2932       }
2933   }
2934   
2935   return 0;
2936 }
2937
2938 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2939   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2940
2941   // Handle the integer rem common cases
2942   if (Instruction *common = commonIRemTransforms(I))
2943     return common;
2944   
2945   if (Value *RHSNeg = dyn_castNegVal(Op1))
2946     if (!isa<ConstantInt>(RHSNeg) || 
2947         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2948       // X % -Y -> X % Y
2949       AddUsesToWorkList(I);
2950       I.setOperand(1, RHSNeg);
2951       return &I;
2952     }
2953  
2954   // If the sign bits of both operands are zero (i.e. we can prove they are
2955   // unsigned inputs), turn this into a urem.
2956   if (I.getType()->isInteger()) {
2957     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2958     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2959       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2960       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2961     }
2962   }
2963
2964   return 0;
2965 }
2966
2967 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2968   return commonRemTransforms(I);
2969 }
2970
2971 // isMaxValueMinusOne - return true if this is Max-1
2972 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2973   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2974   if (!isSigned)
2975     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2976   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2977 }
2978
2979 // isMinValuePlusOne - return true if this is Min+1
2980 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2981   if (!isSigned)
2982     return C->getValue() == 1; // unsigned
2983     
2984   // Calculate 1111111111000000000000
2985   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2986   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2987 }
2988
2989 // isOneBitSet - Return true if there is exactly one bit set in the specified
2990 // constant.
2991 static bool isOneBitSet(const ConstantInt *CI) {
2992   return CI->getValue().isPowerOf2();
2993 }
2994
2995 // isHighOnes - Return true if the constant is of the form 1+0+.
2996 // This is the same as lowones(~X).
2997 static bool isHighOnes(const ConstantInt *CI) {
2998   return (~CI->getValue() + 1).isPowerOf2();
2999 }
3000
3001 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3002 /// are carefully arranged to allow folding of expressions such as:
3003 ///
3004 ///      (A < B) | (A > B) --> (A != B)
3005 ///
3006 /// Note that this is only valid if the first and second predicates have the
3007 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3008 ///
3009 /// Three bits are used to represent the condition, as follows:
3010 ///   0  A > B
3011 ///   1  A == B
3012 ///   2  A < B
3013 ///
3014 /// <=>  Value  Definition
3015 /// 000     0   Always false
3016 /// 001     1   A >  B
3017 /// 010     2   A == B
3018 /// 011     3   A >= B
3019 /// 100     4   A <  B
3020 /// 101     5   A != B
3021 /// 110     6   A <= B
3022 /// 111     7   Always true
3023 ///  
3024 static unsigned getICmpCode(const ICmpInst *ICI) {
3025   switch (ICI->getPredicate()) {
3026     // False -> 0
3027   case ICmpInst::ICMP_UGT: return 1;  // 001
3028   case ICmpInst::ICMP_SGT: return 1;  // 001
3029   case ICmpInst::ICMP_EQ:  return 2;  // 010
3030   case ICmpInst::ICMP_UGE: return 3;  // 011
3031   case ICmpInst::ICMP_SGE: return 3;  // 011
3032   case ICmpInst::ICMP_ULT: return 4;  // 100
3033   case ICmpInst::ICMP_SLT: return 4;  // 100
3034   case ICmpInst::ICMP_NE:  return 5;  // 101
3035   case ICmpInst::ICMP_ULE: return 6;  // 110
3036   case ICmpInst::ICMP_SLE: return 6;  // 110
3037     // True -> 7
3038   default:
3039     assert(0 && "Invalid ICmp predicate!");
3040     return 0;
3041   }
3042 }
3043
3044 /// getICmpValue - This is the complement of getICmpCode, which turns an
3045 /// opcode and two operands into either a constant true or false, or a brand 
3046 /// new ICmp instruction. The sign is passed in to determine which kind
3047 /// of predicate to use in new icmp instructions.
3048 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3049   switch (code) {
3050   default: assert(0 && "Illegal ICmp code!");
3051   case  0: return ConstantInt::getFalse();
3052   case  1: 
3053     if (sign)
3054       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3055     else
3056       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3057   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3058   case  3: 
3059     if (sign)
3060       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3061     else
3062       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3063   case  4: 
3064     if (sign)
3065       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3066     else
3067       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3068   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3069   case  6: 
3070     if (sign)
3071       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3072     else
3073       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3074   case  7: return ConstantInt::getTrue();
3075   }
3076 }
3077
3078 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3079   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3080     (ICmpInst::isSignedPredicate(p1) && 
3081      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3082     (ICmpInst::isSignedPredicate(p2) && 
3083      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3084 }
3085
3086 namespace { 
3087 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3088 struct FoldICmpLogical {
3089   InstCombiner &IC;
3090   Value *LHS, *RHS;
3091   ICmpInst::Predicate pred;
3092   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3093     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3094       pred(ICI->getPredicate()) {}
3095   bool shouldApply(Value *V) const {
3096     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3097       if (PredicatesFoldable(pred, ICI->getPredicate()))
3098         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3099                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3100     return false;
3101   }
3102   Instruction *apply(Instruction &Log) const {
3103     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3104     if (ICI->getOperand(0) != LHS) {
3105       assert(ICI->getOperand(1) == LHS);
3106       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3107     }
3108
3109     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3110     unsigned LHSCode = getICmpCode(ICI);
3111     unsigned RHSCode = getICmpCode(RHSICI);
3112     unsigned Code;
3113     switch (Log.getOpcode()) {
3114     case Instruction::And: Code = LHSCode & RHSCode; break;
3115     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3116     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3117     default: assert(0 && "Illegal logical opcode!"); return 0;
3118     }
3119
3120     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3121                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3122       
3123     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3124     if (Instruction *I = dyn_cast<Instruction>(RV))
3125       return I;
3126     // Otherwise, it's a constant boolean value...
3127     return IC.ReplaceInstUsesWith(Log, RV);
3128   }
3129 };
3130 } // end anonymous namespace
3131
3132 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3133 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3134 // guaranteed to be a binary operator.
3135 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3136                                     ConstantInt *OpRHS,
3137                                     ConstantInt *AndRHS,
3138                                     BinaryOperator &TheAnd) {
3139   Value *X = Op->getOperand(0);
3140   Constant *Together = 0;
3141   if (!Op->isShift())
3142     Together = And(AndRHS, OpRHS);
3143
3144   switch (Op->getOpcode()) {
3145   case Instruction::Xor:
3146     if (Op->hasOneUse()) {
3147       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3148       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3149       InsertNewInstBefore(And, TheAnd);
3150       And->takeName(Op);
3151       return BinaryOperator::CreateXor(And, Together);
3152     }
3153     break;
3154   case Instruction::Or:
3155     if (Together == AndRHS) // (X | C) & C --> C
3156       return ReplaceInstUsesWith(TheAnd, AndRHS);
3157
3158     if (Op->hasOneUse() && Together != OpRHS) {
3159       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3160       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3161       InsertNewInstBefore(Or, TheAnd);
3162       Or->takeName(Op);
3163       return BinaryOperator::CreateAnd(Or, AndRHS);
3164     }
3165     break;
3166   case Instruction::Add:
3167     if (Op->hasOneUse()) {
3168       // Adding a one to a single bit bit-field should be turned into an XOR
3169       // of the bit.  First thing to check is to see if this AND is with a
3170       // single bit constant.
3171       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3172
3173       // If there is only one bit set...
3174       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3175         // Ok, at this point, we know that we are masking the result of the
3176         // ADD down to exactly one bit.  If the constant we are adding has
3177         // no bits set below this bit, then we can eliminate the ADD.
3178         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3179
3180         // Check to see if any bits below the one bit set in AndRHSV are set.
3181         if ((AddRHS & (AndRHSV-1)) == 0) {
3182           // If not, the only thing that can effect the output of the AND is
3183           // the bit specified by AndRHSV.  If that bit is set, the effect of
3184           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3185           // no effect.
3186           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3187             TheAnd.setOperand(0, X);
3188             return &TheAnd;
3189           } else {
3190             // Pull the XOR out of the AND.
3191             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3192             InsertNewInstBefore(NewAnd, TheAnd);
3193             NewAnd->takeName(Op);
3194             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3195           }
3196         }
3197       }
3198     }
3199     break;
3200
3201   case Instruction::Shl: {
3202     // We know that the AND will not produce any of the bits shifted in, so if
3203     // the anded constant includes them, clear them now!
3204     //
3205     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3206     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3207     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3208     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3209
3210     if (CI->getValue() == ShlMask) { 
3211     // Masking out bits that the shift already masks
3212       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3213     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3214       TheAnd.setOperand(1, CI);
3215       return &TheAnd;
3216     }
3217     break;
3218   }
3219   case Instruction::LShr:
3220   {
3221     // We know that the AND will not produce any of the bits shifted in, so if
3222     // the anded constant includes them, clear them now!  This only applies to
3223     // unsigned shifts, because a signed shr may bring in set bits!
3224     //
3225     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3226     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3227     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3228     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3229
3230     if (CI->getValue() == ShrMask) {   
3231     // Masking out bits that the shift already masks.
3232       return ReplaceInstUsesWith(TheAnd, Op);
3233     } else if (CI != AndRHS) {
3234       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3235       return &TheAnd;
3236     }
3237     break;
3238   }
3239   case Instruction::AShr:
3240     // Signed shr.
3241     // See if this is shifting in some sign extension, then masking it out
3242     // with an and.
3243     if (Op->hasOneUse()) {
3244       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3245       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3246       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3247       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3248       if (C == AndRHS) {          // Masking out bits shifted in.
3249         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3250         // Make the argument unsigned.
3251         Value *ShVal = Op->getOperand(0);
3252         ShVal = InsertNewInstBefore(
3253             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3254                                    Op->getName()), TheAnd);
3255         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3256       }
3257     }
3258     break;
3259   }
3260   return 0;
3261 }
3262
3263
3264 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3265 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3266 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3267 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3268 /// insert new instructions.
3269 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3270                                            bool isSigned, bool Inside, 
3271                                            Instruction &IB) {
3272   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3273             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3274          "Lo is not <= Hi in range emission code!");
3275     
3276   if (Inside) {
3277     if (Lo == Hi)  // Trivially false.
3278       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3279
3280     // V >= Min && V < Hi --> V < Hi
3281     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3282       ICmpInst::Predicate pred = (isSigned ? 
3283         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3284       return new ICmpInst(pred, V, Hi);
3285     }
3286
3287     // Emit V-Lo <u Hi-Lo
3288     Constant *NegLo = ConstantExpr::getNeg(Lo);
3289     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3290     InsertNewInstBefore(Add, IB);
3291     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3292     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3293   }
3294
3295   if (Lo == Hi)  // Trivially true.
3296     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3297
3298   // V < Min || V >= Hi -> V > Hi-1
3299   Hi = SubOne(cast<ConstantInt>(Hi));
3300   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3301     ICmpInst::Predicate pred = (isSigned ? 
3302         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3303     return new ICmpInst(pred, V, Hi);
3304   }
3305
3306   // Emit V-Lo >u Hi-1-Lo
3307   // Note that Hi has already had one subtracted from it, above.
3308   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3309   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3310   InsertNewInstBefore(Add, IB);
3311   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3312   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3313 }
3314
3315 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3316 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3317 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3318 // not, since all 1s are not contiguous.
3319 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3320   const APInt& V = Val->getValue();
3321   uint32_t BitWidth = Val->getType()->getBitWidth();
3322   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3323
3324   // look for the first zero bit after the run of ones
3325   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3326   // look for the first non-zero bit
3327   ME = V.getActiveBits(); 
3328   return true;
3329 }
3330
3331 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3332 /// where isSub determines whether the operator is a sub.  If we can fold one of
3333 /// the following xforms:
3334 /// 
3335 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3336 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3337 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3338 ///
3339 /// return (A +/- B).
3340 ///
3341 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3342                                         ConstantInt *Mask, bool isSub,
3343                                         Instruction &I) {
3344   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3345   if (!LHSI || LHSI->getNumOperands() != 2 ||
3346       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3347
3348   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3349
3350   switch (LHSI->getOpcode()) {
3351   default: return 0;
3352   case Instruction::And:
3353     if (And(N, Mask) == Mask) {
3354       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3355       if ((Mask->getValue().countLeadingZeros() + 
3356            Mask->getValue().countPopulation()) == 
3357           Mask->getValue().getBitWidth())
3358         break;
3359
3360       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3361       // part, we don't need any explicit masks to take them out of A.  If that
3362       // is all N is, ignore it.
3363       uint32_t MB = 0, ME = 0;
3364       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3365         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3366         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3367         if (MaskedValueIsZero(RHS, Mask))
3368           break;
3369       }
3370     }
3371     return 0;
3372   case Instruction::Or:
3373   case Instruction::Xor:
3374     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3375     if ((Mask->getValue().countLeadingZeros() + 
3376          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3377         && And(N, Mask)->isZero())
3378       break;
3379     return 0;
3380   }
3381   
3382   Instruction *New;
3383   if (isSub)
3384     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3385   else
3386     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3387   return InsertNewInstBefore(New, I);
3388 }
3389
3390 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3391   bool Changed = SimplifyCommutative(I);
3392   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3393
3394   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3395     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3396
3397   // and X, X = X
3398   if (Op0 == Op1)
3399     return ReplaceInstUsesWith(I, Op1);
3400
3401   // See if we can simplify any instructions used by the instruction whose sole 
3402   // purpose is to compute bits we don't care about.
3403   if (!isa<VectorType>(I.getType())) {
3404     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3405     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3406     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3407                              KnownZero, KnownOne))
3408       return &I;
3409   } else {
3410     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3411       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3412         return ReplaceInstUsesWith(I, I.getOperand(0));
3413     } else if (isa<ConstantAggregateZero>(Op1)) {
3414       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3415     }
3416   }
3417   
3418   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3419     const APInt& AndRHSMask = AndRHS->getValue();
3420     APInt NotAndRHS(~AndRHSMask);
3421
3422     // Optimize a variety of ((val OP C1) & C2) combinations...
3423     if (isa<BinaryOperator>(Op0)) {
3424       Instruction *Op0I = cast<Instruction>(Op0);
3425       Value *Op0LHS = Op0I->getOperand(0);
3426       Value *Op0RHS = Op0I->getOperand(1);
3427       switch (Op0I->getOpcode()) {
3428       case Instruction::Xor:
3429       case Instruction::Or:
3430         // If the mask is only needed on one incoming arm, push it up.
3431         if (Op0I->hasOneUse()) {
3432           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3433             // Not masking anything out for the LHS, move to RHS.
3434             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3435                                                    Op0RHS->getName()+".masked");
3436             InsertNewInstBefore(NewRHS, I);
3437             return BinaryOperator::Create(
3438                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3439           }
3440           if (!isa<Constant>(Op0RHS) &&
3441               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3442             // Not masking anything out for the RHS, move to LHS.
3443             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3444                                                    Op0LHS->getName()+".masked");
3445             InsertNewInstBefore(NewLHS, I);
3446             return BinaryOperator::Create(
3447                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3448           }
3449         }
3450
3451         break;
3452       case Instruction::Add:
3453         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3454         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3455         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3456         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3457           return BinaryOperator::CreateAnd(V, AndRHS);
3458         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3459           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3460         break;
3461
3462       case Instruction::Sub:
3463         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3464         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3465         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3466         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3467           return BinaryOperator::CreateAnd(V, AndRHS);
3468         break;
3469       }
3470
3471       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3472         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3473           return Res;
3474     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3475       // If this is an integer truncation or change from signed-to-unsigned, and
3476       // if the source is an and/or with immediate, transform it.  This
3477       // frequently occurs for bitfield accesses.
3478       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3479         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3480             CastOp->getNumOperands() == 2)
3481           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3482             if (CastOp->getOpcode() == Instruction::And) {
3483               // Change: and (cast (and X, C1) to T), C2
3484               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3485               // This will fold the two constants together, which may allow 
3486               // other simplifications.
3487               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3488                 CastOp->getOperand(0), I.getType(), 
3489                 CastOp->getName()+".shrunk");
3490               NewCast = InsertNewInstBefore(NewCast, I);
3491               // trunc_or_bitcast(C1)&C2
3492               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3493               C3 = ConstantExpr::getAnd(C3, AndRHS);
3494               return BinaryOperator::CreateAnd(NewCast, C3);
3495             } else if (CastOp->getOpcode() == Instruction::Or) {
3496               // Change: and (cast (or X, C1) to T), C2
3497               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3498               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3499               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3500                 return ReplaceInstUsesWith(I, AndRHS);
3501             }
3502           }
3503       }
3504     }
3505
3506     // Try to fold constant and into select arguments.
3507     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3508       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3509         return R;
3510     if (isa<PHINode>(Op0))
3511       if (Instruction *NV = FoldOpIntoPhi(I))
3512         return NV;
3513   }
3514
3515   Value *Op0NotVal = dyn_castNotVal(Op0);
3516   Value *Op1NotVal = dyn_castNotVal(Op1);
3517
3518   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3519     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3520
3521   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3522   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3523     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3524                                                I.getName()+".demorgan");
3525     InsertNewInstBefore(Or, I);
3526     return BinaryOperator::CreateNot(Or);
3527   }
3528   
3529   {
3530     Value *A = 0, *B = 0, *C = 0, *D = 0;
3531     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3532       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3533         return ReplaceInstUsesWith(I, Op1);
3534     
3535       // (A|B) & ~(A&B) -> A^B
3536       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3537         if ((A == C && B == D) || (A == D && B == C))
3538           return BinaryOperator::CreateXor(A, B);
3539       }
3540     }
3541     
3542     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3543       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3544         return ReplaceInstUsesWith(I, Op0);
3545
3546       // ~(A&B) & (A|B) -> A^B
3547       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3548         if ((A == C && B == D) || (A == D && B == C))
3549           return BinaryOperator::CreateXor(A, B);
3550       }
3551     }
3552     
3553     if (Op0->hasOneUse() &&
3554         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3555       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3556         I.swapOperands();     // Simplify below
3557         std::swap(Op0, Op1);
3558       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3559         cast<BinaryOperator>(Op0)->swapOperands();
3560         I.swapOperands();     // Simplify below
3561         std::swap(Op0, Op1);
3562       }
3563     }
3564     if (Op1->hasOneUse() &&
3565         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3566       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3567         cast<BinaryOperator>(Op1)->swapOperands();
3568         std::swap(A, B);
3569       }
3570       if (A == Op0) {                                // A&(A^B) -> A & ~B
3571         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3572         InsertNewInstBefore(NotB, I);
3573         return BinaryOperator::CreateAnd(A, NotB);
3574       }
3575     }
3576   }
3577   
3578   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3579     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3580     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3581       return R;
3582
3583     Value *LHSVal, *RHSVal;
3584     ConstantInt *LHSCst, *RHSCst;
3585     ICmpInst::Predicate LHSCC, RHSCC;
3586     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3587       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3588         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3589             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3590             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3591             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3592             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3593             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3594             
3595             // Don't try to fold ICMP_SLT + ICMP_ULT.
3596             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3597              ICmpInst::isSignedPredicate(LHSCC) == 
3598                  ICmpInst::isSignedPredicate(RHSCC))) {
3599           // Ensure that the larger constant is on the RHS.
3600           ICmpInst::Predicate GT;
3601           if (ICmpInst::isSignedPredicate(LHSCC) ||
3602               (ICmpInst::isEquality(LHSCC) && 
3603                ICmpInst::isSignedPredicate(RHSCC)))
3604             GT = ICmpInst::ICMP_SGT;
3605           else
3606             GT = ICmpInst::ICMP_UGT;
3607           
3608           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3609           ICmpInst *LHS = cast<ICmpInst>(Op0);
3610           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3611             std::swap(LHS, RHS);
3612             std::swap(LHSCst, RHSCst);
3613             std::swap(LHSCC, RHSCC);
3614           }
3615
3616           // At this point, we know we have have two icmp instructions
3617           // comparing a value against two constants and and'ing the result
3618           // together.  Because of the above check, we know that we only have
3619           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3620           // (from the FoldICmpLogical check above), that the two constants 
3621           // are not equal and that the larger constant is on the RHS
3622           assert(LHSCst != RHSCst && "Compares not folded above?");
3623
3624           switch (LHSCC) {
3625           default: assert(0 && "Unknown integer condition code!");
3626           case ICmpInst::ICMP_EQ:
3627             switch (RHSCC) {
3628             default: assert(0 && "Unknown integer condition code!");
3629             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3630             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3631             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3632               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3633             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3634             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3635             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3636               return ReplaceInstUsesWith(I, LHS);
3637             }
3638           case ICmpInst::ICMP_NE:
3639             switch (RHSCC) {
3640             default: assert(0 && "Unknown integer condition code!");
3641             case ICmpInst::ICMP_ULT:
3642               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3643                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3644               break;                        // (X != 13 & X u< 15) -> no change
3645             case ICmpInst::ICMP_SLT:
3646               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3647                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3648               break;                        // (X != 13 & X s< 15) -> no change
3649             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3650             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3651             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3652               return ReplaceInstUsesWith(I, RHS);
3653             case ICmpInst::ICMP_NE:
3654               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3655                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3656                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3657                                                       LHSVal->getName()+".off");
3658                 InsertNewInstBefore(Add, I);
3659                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3660                                     ConstantInt::get(Add->getType(), 1));
3661               }
3662               break;                        // (X != 13 & X != 15) -> no change
3663             }
3664             break;
3665           case ICmpInst::ICMP_ULT:
3666             switch (RHSCC) {
3667             default: assert(0 && "Unknown integer condition code!");
3668             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3669             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3670               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3671             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3672               break;
3673             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3674             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3675               return ReplaceInstUsesWith(I, LHS);
3676             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3677               break;
3678             }
3679             break;
3680           case ICmpInst::ICMP_SLT:
3681             switch (RHSCC) {
3682             default: assert(0 && "Unknown integer condition code!");
3683             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3684             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3685               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3686             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3687               break;
3688             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3689             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3690               return ReplaceInstUsesWith(I, LHS);
3691             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3692               break;
3693             }
3694             break;
3695           case ICmpInst::ICMP_UGT:
3696             switch (RHSCC) {
3697             default: assert(0 && "Unknown integer condition code!");
3698             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3699               return ReplaceInstUsesWith(I, LHS);
3700             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3701               return ReplaceInstUsesWith(I, RHS);
3702             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3703               break;
3704             case ICmpInst::ICMP_NE:
3705               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3706                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3707               break;                        // (X u> 13 & X != 15) -> no change
3708             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3709               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3710                                      true, I);
3711             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3712               break;
3713             }
3714             break;
3715           case ICmpInst::ICMP_SGT:
3716             switch (RHSCC) {
3717             default: assert(0 && "Unknown integer condition code!");
3718             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3719             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3720               return ReplaceInstUsesWith(I, RHS);
3721             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3722               break;
3723             case ICmpInst::ICMP_NE:
3724               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3725                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3726               break;                        // (X s> 13 & X != 15) -> no change
3727             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3728               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3729                                      true, I);
3730             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3731               break;
3732             }
3733             break;
3734           }
3735         }
3736   }
3737
3738   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3739   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3740     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3741       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3742         const Type *SrcTy = Op0C->getOperand(0)->getType();
3743         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3744             // Only do this if the casts both really cause code to be generated.
3745             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3746                               I.getType(), TD) &&
3747             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3748                               I.getType(), TD)) {
3749           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3750                                                          Op1C->getOperand(0),
3751                                                          I.getName());
3752           InsertNewInstBefore(NewOp, I);
3753           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3754         }
3755       }
3756     
3757   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3758   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3759     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3760       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3761           SI0->getOperand(1) == SI1->getOperand(1) &&
3762           (SI0->hasOneUse() || SI1->hasOneUse())) {
3763         Instruction *NewOp =
3764           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3765                                                         SI1->getOperand(0),
3766                                                         SI0->getName()), I);
3767         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
3768                                       SI1->getOperand(1));
3769       }
3770   }
3771
3772   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3773   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3774     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3775       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3776           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3777         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3778           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3779             // If either of the constants are nans, then the whole thing returns
3780             // false.
3781             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3782               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3783             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3784                                 RHS->getOperand(0));
3785           }
3786     }
3787   }
3788       
3789   return Changed ? &I : 0;
3790 }
3791
3792 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3793 /// in the result.  If it does, and if the specified byte hasn't been filled in
3794 /// yet, fill it in and return false.
3795 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3796   Instruction *I = dyn_cast<Instruction>(V);
3797   if (I == 0) return true;
3798
3799   // If this is an or instruction, it is an inner node of the bswap.
3800   if (I->getOpcode() == Instruction::Or)
3801     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3802            CollectBSwapParts(I->getOperand(1), ByteValues);
3803   
3804   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3805   // If this is a shift by a constant int, and it is "24", then its operand
3806   // defines a byte.  We only handle unsigned types here.
3807   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3808     // Not shifting the entire input by N-1 bytes?
3809     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3810         8*(ByteValues.size()-1))
3811       return true;
3812     
3813     unsigned DestNo;
3814     if (I->getOpcode() == Instruction::Shl) {
3815       // X << 24 defines the top byte with the lowest of the input bytes.
3816       DestNo = ByteValues.size()-1;
3817     } else {
3818       // X >>u 24 defines the low byte with the highest of the input bytes.
3819       DestNo = 0;
3820     }
3821     
3822     // If the destination byte value is already defined, the values are or'd
3823     // together, which isn't a bswap (unless it's an or of the same bits).
3824     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3825       return true;
3826     ByteValues[DestNo] = I->getOperand(0);
3827     return false;
3828   }
3829   
3830   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3831   // don't have this.
3832   Value *Shift = 0, *ShiftLHS = 0;
3833   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3834   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3835       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3836     return true;
3837   Instruction *SI = cast<Instruction>(Shift);
3838
3839   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3840   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3841       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3842     return true;
3843   
3844   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3845   unsigned DestByte;
3846   if (AndAmt->getValue().getActiveBits() > 64)
3847     return true;
3848   uint64_t AndAmtVal = AndAmt->getZExtValue();
3849   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3850     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3851       break;
3852   // Unknown mask for bswap.
3853   if (DestByte == ByteValues.size()) return true;
3854   
3855   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3856   unsigned SrcByte;
3857   if (SI->getOpcode() == Instruction::Shl)
3858     SrcByte = DestByte - ShiftBytes;
3859   else
3860     SrcByte = DestByte + ShiftBytes;
3861   
3862   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3863   if (SrcByte != ByteValues.size()-DestByte-1)
3864     return true;
3865   
3866   // If the destination byte value is already defined, the values are or'd
3867   // together, which isn't a bswap (unless it's an or of the same bits).
3868   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3869     return true;
3870   ByteValues[DestByte] = SI->getOperand(0);
3871   return false;
3872 }
3873
3874 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3875 /// If so, insert the new bswap intrinsic and return it.
3876 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3877   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3878   if (!ITy || ITy->getBitWidth() % 16) 
3879     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3880   
3881   /// ByteValues - For each byte of the result, we keep track of which value
3882   /// defines each byte.
3883   SmallVector<Value*, 8> ByteValues;
3884   ByteValues.resize(ITy->getBitWidth()/8);
3885     
3886   // Try to find all the pieces corresponding to the bswap.
3887   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3888       CollectBSwapParts(I.getOperand(1), ByteValues))
3889     return 0;
3890   
3891   // Check to see if all of the bytes come from the same value.
3892   Value *V = ByteValues[0];
3893   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3894   
3895   // Check to make sure that all of the bytes come from the same value.
3896   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3897     if (ByteValues[i] != V)
3898       return 0;
3899   const Type *Tys[] = { ITy };
3900   Module *M = I.getParent()->getParent()->getParent();
3901   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3902   return CallInst::Create(F, V);
3903 }
3904
3905
3906 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3907   bool Changed = SimplifyCommutative(I);
3908   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3909
3910   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3911     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3912
3913   // or X, X = X
3914   if (Op0 == Op1)
3915     return ReplaceInstUsesWith(I, Op0);
3916
3917   // See if we can simplify any instructions used by the instruction whose sole 
3918   // purpose is to compute bits we don't care about.
3919   if (!isa<VectorType>(I.getType())) {
3920     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3921     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3922     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3923                              KnownZero, KnownOne))
3924       return &I;
3925   } else if (isa<ConstantAggregateZero>(Op1)) {
3926     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3927   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3928     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3929       return ReplaceInstUsesWith(I, I.getOperand(1));
3930   }
3931     
3932
3933   
3934   // or X, -1 == -1
3935   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3936     ConstantInt *C1 = 0; Value *X = 0;
3937     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3938     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3939       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3940       InsertNewInstBefore(Or, I);
3941       Or->takeName(Op0);
3942       return BinaryOperator::CreateAnd(Or, 
3943                ConstantInt::get(RHS->getValue() | C1->getValue()));
3944     }
3945
3946     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3947     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3948       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3949       InsertNewInstBefore(Or, I);
3950       Or->takeName(Op0);
3951       return BinaryOperator::CreateXor(Or,
3952                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3953     }
3954
3955     // Try to fold constant and into select arguments.
3956     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3957       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3958         return R;
3959     if (isa<PHINode>(Op0))
3960       if (Instruction *NV = FoldOpIntoPhi(I))
3961         return NV;
3962   }
3963
3964   Value *A = 0, *B = 0;
3965   ConstantInt *C1 = 0, *C2 = 0;
3966
3967   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3968     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3969       return ReplaceInstUsesWith(I, Op1);
3970   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3971     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3972       return ReplaceInstUsesWith(I, Op0);
3973
3974   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3975   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3976   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3977       match(Op1, m_Or(m_Value(), m_Value())) ||
3978       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3979        match(Op1, m_Shift(m_Value(), m_Value())))) {
3980     if (Instruction *BSwap = MatchBSwap(I))
3981       return BSwap;
3982   }
3983   
3984   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3985   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3986       MaskedValueIsZero(Op1, C1->getValue())) {
3987     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
3988     InsertNewInstBefore(NOr, I);
3989     NOr->takeName(Op0);
3990     return BinaryOperator::CreateXor(NOr, C1);
3991   }
3992
3993   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3994   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3995       MaskedValueIsZero(Op0, C1->getValue())) {
3996     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
3997     InsertNewInstBefore(NOr, I);
3998     NOr->takeName(Op0);
3999     return BinaryOperator::CreateXor(NOr, C1);
4000   }
4001
4002   // (A & C)|(B & D)
4003   Value *C = 0, *D = 0;
4004   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4005       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4006     Value *V1 = 0, *V2 = 0, *V3 = 0;
4007     C1 = dyn_cast<ConstantInt>(C);
4008     C2 = dyn_cast<ConstantInt>(D);
4009     if (C1 && C2) {  // (A & C1)|(B & C2)
4010       // If we have: ((V + N) & C1) | (V & C2)
4011       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4012       // replace with V+N.
4013       if (C1->getValue() == ~C2->getValue()) {
4014         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4015             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4016           // Add commutes, try both ways.
4017           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4018             return ReplaceInstUsesWith(I, A);
4019           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4020             return ReplaceInstUsesWith(I, A);
4021         }
4022         // Or commutes, try both ways.
4023         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4024             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4025           // Add commutes, try both ways.
4026           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4027             return ReplaceInstUsesWith(I, B);
4028           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4029             return ReplaceInstUsesWith(I, B);
4030         }
4031       }
4032       V1 = 0; V2 = 0; V3 = 0;
4033     }
4034     
4035     // Check to see if we have any common things being and'ed.  If so, find the
4036     // terms for V1 & (V2|V3).
4037     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4038       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4039         V1 = A, V2 = C, V3 = D;
4040       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4041         V1 = A, V2 = B, V3 = C;
4042       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4043         V1 = C, V2 = A, V3 = D;
4044       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4045         V1 = C, V2 = A, V3 = B;
4046       
4047       if (V1) {
4048         Value *Or =
4049           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4050         return BinaryOperator::CreateAnd(V1, Or);
4051       }
4052     }
4053   }
4054   
4055   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4056   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4057     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4058       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4059           SI0->getOperand(1) == SI1->getOperand(1) &&
4060           (SI0->hasOneUse() || SI1->hasOneUse())) {
4061         Instruction *NewOp =
4062         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4063                                                      SI1->getOperand(0),
4064                                                      SI0->getName()), I);
4065         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4066                                       SI1->getOperand(1));
4067       }
4068   }
4069
4070   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4071     if (A == Op1)   // ~A | A == -1
4072       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4073   } else {
4074     A = 0;
4075   }
4076   // Note, A is still live here!
4077   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4078     if (Op0 == B)
4079       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4080
4081     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4082     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4083       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4084                                               I.getName()+".demorgan"), I);
4085       return BinaryOperator::CreateNot(And);
4086     }
4087   }
4088
4089   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4090   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4091     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4092       return R;
4093
4094     Value *LHSVal, *RHSVal;
4095     ConstantInt *LHSCst, *RHSCst;
4096     ICmpInst::Predicate LHSCC, RHSCC;
4097     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4098       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4099         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4100             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4101             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4102             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4103             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4104             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4105             // We can't fold (ugt x, C) | (sgt x, C2).
4106             PredicatesFoldable(LHSCC, RHSCC)) {
4107           // Ensure that the larger constant is on the RHS.
4108           ICmpInst *LHS = cast<ICmpInst>(Op0);
4109           bool NeedsSwap;
4110           if (ICmpInst::isSignedPredicate(LHSCC))
4111             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4112           else
4113             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4114             
4115           if (NeedsSwap) {
4116             std::swap(LHS, RHS);
4117             std::swap(LHSCst, RHSCst);
4118             std::swap(LHSCC, RHSCC);
4119           }
4120
4121           // At this point, we know we have have two icmp instructions
4122           // comparing a value against two constants and or'ing the result
4123           // together.  Because of the above check, we know that we only have
4124           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4125           // FoldICmpLogical check above), that the two constants are not
4126           // equal.
4127           assert(LHSCst != RHSCst && "Compares not folded above?");
4128
4129           switch (LHSCC) {
4130           default: assert(0 && "Unknown integer condition code!");
4131           case ICmpInst::ICMP_EQ:
4132             switch (RHSCC) {
4133             default: assert(0 && "Unknown integer condition code!");
4134             case ICmpInst::ICMP_EQ:
4135               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4136                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4137                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4138                                                       LHSVal->getName()+".off");
4139                 InsertNewInstBefore(Add, I);
4140                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4141                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4142               }
4143               break;                         // (X == 13 | X == 15) -> no change
4144             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4145             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4146               break;
4147             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4148             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4149             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4150               return ReplaceInstUsesWith(I, RHS);
4151             }
4152             break;
4153           case ICmpInst::ICMP_NE:
4154             switch (RHSCC) {
4155             default: assert(0 && "Unknown integer condition code!");
4156             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4157             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4158             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4159               return ReplaceInstUsesWith(I, LHS);
4160             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4161             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4162             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4163               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4164             }
4165             break;
4166           case ICmpInst::ICMP_ULT:
4167             switch (RHSCC) {
4168             default: assert(0 && "Unknown integer condition code!");
4169             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4170               break;
4171             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4172               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4173               // this can cause overflow.
4174               if (RHSCst->isMaxValue(false))
4175                 return ReplaceInstUsesWith(I, LHS);
4176               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4177                                      false, I);
4178             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4179               break;
4180             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4181             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4182               return ReplaceInstUsesWith(I, RHS);
4183             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4184               break;
4185             }
4186             break;
4187           case ICmpInst::ICMP_SLT:
4188             switch (RHSCC) {
4189             default: assert(0 && "Unknown integer condition code!");
4190             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4191               break;
4192             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4193               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4194               // this can cause overflow.
4195               if (RHSCst->isMaxValue(true))
4196                 return ReplaceInstUsesWith(I, LHS);
4197               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4198                                      false, I);
4199             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4200               break;
4201             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4202             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4203               return ReplaceInstUsesWith(I, RHS);
4204             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4205               break;
4206             }
4207             break;
4208           case ICmpInst::ICMP_UGT:
4209             switch (RHSCC) {
4210             default: assert(0 && "Unknown integer condition code!");
4211             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4212             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4213               return ReplaceInstUsesWith(I, LHS);
4214             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4215               break;
4216             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4217             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4218               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4219             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4220               break;
4221             }
4222             break;
4223           case ICmpInst::ICMP_SGT:
4224             switch (RHSCC) {
4225             default: assert(0 && "Unknown integer condition code!");
4226             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4227             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4228               return ReplaceInstUsesWith(I, LHS);
4229             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4230               break;
4231             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4232             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4233               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4234             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4235               break;
4236             }
4237             break;
4238           }
4239         }
4240   }
4241     
4242   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4243   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4244     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4245       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4246         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4247             !isa<ICmpInst>(Op1C->getOperand(0))) {
4248           const Type *SrcTy = Op0C->getOperand(0)->getType();
4249           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4250               // Only do this if the casts both really cause code to be
4251               // generated.
4252               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4253                                 I.getType(), TD) &&
4254               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4255                                 I.getType(), TD)) {
4256             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4257                                                           Op1C->getOperand(0),
4258                                                           I.getName());
4259             InsertNewInstBefore(NewOp, I);
4260             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4261           }
4262         }
4263       }
4264   }
4265   
4266     
4267   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4268   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4269     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4270       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4271           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4272           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4273         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4274           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4275             // If either of the constants are nans, then the whole thing returns
4276             // true.
4277             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4278               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4279             
4280             // Otherwise, no need to compare the two constants, compare the
4281             // rest.
4282             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4283                                 RHS->getOperand(0));
4284           }
4285     }
4286   }
4287
4288   return Changed ? &I : 0;
4289 }
4290
4291 namespace {
4292
4293 // XorSelf - Implements: X ^ X --> 0
4294 struct XorSelf {
4295   Value *RHS;
4296   XorSelf(Value *rhs) : RHS(rhs) {}
4297   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4298   Instruction *apply(BinaryOperator &Xor) const {
4299     return &Xor;
4300   }
4301 };
4302
4303 }
4304
4305 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4306   bool Changed = SimplifyCommutative(I);
4307   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4308
4309   if (isa<UndefValue>(Op1)) {
4310     if (isa<UndefValue>(Op0))
4311       // Handle undef ^ undef -> 0 special case. This is a common
4312       // idiom (misuse).
4313       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4314     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4315   }
4316
4317   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4318   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4319     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4320     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4321   }
4322   
4323   // See if we can simplify any instructions used by the instruction whose sole 
4324   // purpose is to compute bits we don't care about.
4325   if (!isa<VectorType>(I.getType())) {
4326     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4327     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4328     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4329                              KnownZero, KnownOne))
4330       return &I;
4331   } else if (isa<ConstantAggregateZero>(Op1)) {
4332     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4333   }
4334
4335   // Is this a ~ operation?
4336   if (Value *NotOp = dyn_castNotVal(&I)) {
4337     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4338     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4339     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4340       if (Op0I->getOpcode() == Instruction::And || 
4341           Op0I->getOpcode() == Instruction::Or) {
4342         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4343         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4344           Instruction *NotY =
4345             BinaryOperator::CreateNot(Op0I->getOperand(1),
4346                                       Op0I->getOperand(1)->getName()+".not");
4347           InsertNewInstBefore(NotY, I);
4348           if (Op0I->getOpcode() == Instruction::And)
4349             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4350           else
4351             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4352         }
4353       }
4354     }
4355   }
4356   
4357   
4358   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4359     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4360     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4361       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4362         return new ICmpInst(ICI->getInversePredicate(),
4363                             ICI->getOperand(0), ICI->getOperand(1));
4364
4365       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4366         return new FCmpInst(FCI->getInversePredicate(),
4367                             FCI->getOperand(0), FCI->getOperand(1));
4368     }
4369
4370     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4371     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4372       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4373         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4374           Instruction::CastOps Opcode = Op0C->getOpcode();
4375           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4376             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4377                                              Op0C->getDestTy())) {
4378               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4379                                      CI->getOpcode(), CI->getInversePredicate(),
4380                                      CI->getOperand(0), CI->getOperand(1)), I);
4381               NewCI->takeName(CI);
4382               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4383             }
4384           }
4385         }
4386       }
4387     }
4388
4389     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4390       // ~(c-X) == X-c-1 == X+(-c-1)
4391       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4392         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4393           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4394           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4395                                               ConstantInt::get(I.getType(), 1));
4396           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4397         }
4398           
4399       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4400         if (Op0I->getOpcode() == Instruction::Add) {
4401           // ~(X-c) --> (-c-1)-X
4402           if (RHS->isAllOnesValue()) {
4403             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4404             return BinaryOperator::CreateSub(
4405                            ConstantExpr::getSub(NegOp0CI,
4406                                              ConstantInt::get(I.getType(), 1)),
4407                                           Op0I->getOperand(0));
4408           } else if (RHS->getValue().isSignBit()) {
4409             // (X + C) ^ signbit -> (X + C + signbit)
4410             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4411             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4412
4413           }
4414         } else if (Op0I->getOpcode() == Instruction::Or) {
4415           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4416           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4417             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4418             // Anything in both C1 and C2 is known to be zero, remove it from
4419             // NewRHS.
4420             Constant *CommonBits = And(Op0CI, RHS);
4421             NewRHS = ConstantExpr::getAnd(NewRHS, 
4422                                           ConstantExpr::getNot(CommonBits));
4423             AddToWorkList(Op0I);
4424             I.setOperand(0, Op0I->getOperand(0));
4425             I.setOperand(1, NewRHS);
4426             return &I;
4427           }
4428         }
4429       }
4430     }
4431
4432     // Try to fold constant and into select arguments.
4433     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4434       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4435         return R;
4436     if (isa<PHINode>(Op0))
4437       if (Instruction *NV = FoldOpIntoPhi(I))
4438         return NV;
4439   }
4440
4441   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4442     if (X == Op1)
4443       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4444
4445   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4446     if (X == Op0)
4447       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4448
4449   
4450   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4451   if (Op1I) {
4452     Value *A, *B;
4453     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4454       if (A == Op0) {              // B^(B|A) == (A|B)^B
4455         Op1I->swapOperands();
4456         I.swapOperands();
4457         std::swap(Op0, Op1);
4458       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4459         I.swapOperands();     // Simplified below.
4460         std::swap(Op0, Op1);
4461       }
4462     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4463       if (Op0 == A)                                          // A^(A^B) == B
4464         return ReplaceInstUsesWith(I, B);
4465       else if (Op0 == B)                                     // A^(B^A) == B
4466         return ReplaceInstUsesWith(I, A);
4467     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4468       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4469         Op1I->swapOperands();
4470         std::swap(A, B);
4471       }
4472       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4473         I.swapOperands();     // Simplified below.
4474         std::swap(Op0, Op1);
4475       }
4476     }
4477   }
4478   
4479   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4480   if (Op0I) {
4481     Value *A, *B;
4482     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4483       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4484         std::swap(A, B);
4485       if (B == Op1) {                                // (A|B)^B == A & ~B
4486         Instruction *NotB =
4487           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4488         return BinaryOperator::CreateAnd(A, NotB);
4489       }
4490     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4491       if (Op1 == A)                                          // (A^B)^A == B
4492         return ReplaceInstUsesWith(I, B);
4493       else if (Op1 == B)                                     // (B^A)^A == B
4494         return ReplaceInstUsesWith(I, A);
4495     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4496       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4497         std::swap(A, B);
4498       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4499           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4500         Instruction *N =
4501           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4502         return BinaryOperator::CreateAnd(N, Op1);
4503       }
4504     }
4505   }
4506   
4507   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4508   if (Op0I && Op1I && Op0I->isShift() && 
4509       Op0I->getOpcode() == Op1I->getOpcode() && 
4510       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4511       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4512     Instruction *NewOp =
4513       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4514                                                     Op1I->getOperand(0),
4515                                                     Op0I->getName()), I);
4516     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4517                                   Op1I->getOperand(1));
4518   }
4519     
4520   if (Op0I && Op1I) {
4521     Value *A, *B, *C, *D;
4522     // (A & B)^(A | B) -> A ^ B
4523     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4524         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4525       if ((A == C && B == D) || (A == D && B == C)) 
4526         return BinaryOperator::CreateXor(A, B);
4527     }
4528     // (A | B)^(A & B) -> A ^ B
4529     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4530         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4531       if ((A == C && B == D) || (A == D && B == C)) 
4532         return BinaryOperator::CreateXor(A, B);
4533     }
4534     
4535     // (A & B)^(C & D)
4536     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4537         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4538         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4539       // (X & Y)^(X & Y) -> (Y^Z) & X
4540       Value *X = 0, *Y = 0, *Z = 0;
4541       if (A == C)
4542         X = A, Y = B, Z = D;
4543       else if (A == D)
4544         X = A, Y = B, Z = C;
4545       else if (B == C)
4546         X = B, Y = A, Z = D;
4547       else if (B == D)
4548         X = B, Y = A, Z = C;
4549       
4550       if (X) {
4551         Instruction *NewOp =
4552         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4553         return BinaryOperator::CreateAnd(NewOp, X);
4554       }
4555     }
4556   }
4557     
4558   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4559   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4560     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4561       return R;
4562
4563   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4564   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4565     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4566       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4567         const Type *SrcTy = Op0C->getOperand(0)->getType();
4568         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4569             // Only do this if the casts both really cause code to be generated.
4570             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4571                               I.getType(), TD) &&
4572             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4573                               I.getType(), TD)) {
4574           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4575                                                          Op1C->getOperand(0),
4576                                                          I.getName());
4577           InsertNewInstBefore(NewOp, I);
4578           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4579         }
4580       }
4581   }
4582
4583   return Changed ? &I : 0;
4584 }
4585
4586 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4587 /// overflowed for this type.
4588 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4589                             ConstantInt *In2, bool IsSigned = false) {
4590   Result = cast<ConstantInt>(Add(In1, In2));
4591
4592   if (IsSigned)
4593     if (In2->getValue().isNegative())
4594       return Result->getValue().sgt(In1->getValue());
4595     else
4596       return Result->getValue().slt(In1->getValue());
4597   else
4598     return Result->getValue().ult(In1->getValue());
4599 }
4600
4601 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4602 /// code necessary to compute the offset from the base pointer (without adding
4603 /// in the base pointer).  Return the result as a signed integer of intptr size.
4604 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4605   TargetData &TD = IC.getTargetData();
4606   gep_type_iterator GTI = gep_type_begin(GEP);
4607   const Type *IntPtrTy = TD.getIntPtrType();
4608   Value *Result = Constant::getNullValue(IntPtrTy);
4609
4610   // Build a mask for high order bits.
4611   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4612   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4613
4614   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4615        ++i, ++GTI) {
4616     Value *Op = *i;
4617     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4618     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4619       if (OpC->isZero()) continue;
4620       
4621       // Handle a struct index, which adds its field offset to the pointer.
4622       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4623         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4624         
4625         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4626           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4627         else
4628           Result = IC.InsertNewInstBefore(
4629                    BinaryOperator::CreateAdd(Result,
4630                                              ConstantInt::get(IntPtrTy, Size),
4631                                              GEP->getName()+".offs"), I);
4632         continue;
4633       }
4634       
4635       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4636       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4637       Scale = ConstantExpr::getMul(OC, Scale);
4638       if (Constant *RC = dyn_cast<Constant>(Result))
4639         Result = ConstantExpr::getAdd(RC, Scale);
4640       else {
4641         // Emit an add instruction.
4642         Result = IC.InsertNewInstBefore(
4643            BinaryOperator::CreateAdd(Result, Scale,
4644                                      GEP->getName()+".offs"), I);
4645       }
4646       continue;
4647     }
4648     // Convert to correct type.
4649     if (Op->getType() != IntPtrTy) {
4650       if (Constant *OpC = dyn_cast<Constant>(Op))
4651         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4652       else
4653         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4654                                                  Op->getName()+".c"), I);
4655     }
4656     if (Size != 1) {
4657       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4658       if (Constant *OpC = dyn_cast<Constant>(Op))
4659         Op = ConstantExpr::getMul(OpC, Scale);
4660       else    // We'll let instcombine(mul) convert this to a shl if possible.
4661         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4662                                                   GEP->getName()+".idx"), I);
4663     }
4664
4665     // Emit an add instruction.
4666     if (isa<Constant>(Op) && isa<Constant>(Result))
4667       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4668                                     cast<Constant>(Result));
4669     else
4670       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4671                                                   GEP->getName()+".offs"), I);
4672   }
4673   return Result;
4674 }
4675
4676
4677 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4678 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
4679 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
4680 /// complex, and scales are involved.  The above expression would also be legal
4681 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
4682 /// later form is less amenable to optimization though, and we are allowed to
4683 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4684 ///
4685 /// If we can't emit an optimized form for this expression, this returns null.
4686 /// 
4687 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4688                                           InstCombiner &IC) {
4689   TargetData &TD = IC.getTargetData();
4690   gep_type_iterator GTI = gep_type_begin(GEP);
4691
4692   // Check to see if this gep only has a single variable index.  If so, and if
4693   // any constant indices are a multiple of its scale, then we can compute this
4694   // in terms of the scale of the variable index.  For example, if the GEP
4695   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4696   // because the expression will cross zero at the same point.
4697   unsigned i, e = GEP->getNumOperands();
4698   int64_t Offset = 0;
4699   for (i = 1; i != e; ++i, ++GTI) {
4700     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4701       // Compute the aggregate offset of constant indices.
4702       if (CI->isZero()) continue;
4703
4704       // Handle a struct index, which adds its field offset to the pointer.
4705       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4706         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4707       } else {
4708         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4709         Offset += Size*CI->getSExtValue();
4710       }
4711     } else {
4712       // Found our variable index.
4713       break;
4714     }
4715   }
4716   
4717   // If there are no variable indices, we must have a constant offset, just
4718   // evaluate it the general way.
4719   if (i == e) return 0;
4720   
4721   Value *VariableIdx = GEP->getOperand(i);
4722   // Determine the scale factor of the variable element.  For example, this is
4723   // 4 if the variable index is into an array of i32.
4724   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4725   
4726   // Verify that there are no other variable indices.  If so, emit the hard way.
4727   for (++i, ++GTI; i != e; ++i, ++GTI) {
4728     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4729     if (!CI) return 0;
4730    
4731     // Compute the aggregate offset of constant indices.
4732     if (CI->isZero()) continue;
4733     
4734     // Handle a struct index, which adds its field offset to the pointer.
4735     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4736       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4737     } else {
4738       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4739       Offset += Size*CI->getSExtValue();
4740     }
4741   }
4742   
4743   // Okay, we know we have a single variable index, which must be a
4744   // pointer/array/vector index.  If there is no offset, life is simple, return
4745   // the index.
4746   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4747   if (Offset == 0) {
4748     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
4749     // we don't need to bother extending: the extension won't affect where the
4750     // computation crosses zero.
4751     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4752       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4753                                   VariableIdx->getNameStart(), &I);
4754     return VariableIdx;
4755   }
4756   
4757   // Otherwise, there is an index.  The computation we will do will be modulo
4758   // the pointer size, so get it.
4759   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4760   
4761   Offset &= PtrSizeMask;
4762   VariableScale &= PtrSizeMask;
4763
4764   // To do this transformation, any constant index must be a multiple of the
4765   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
4766   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
4767   // multiple of the variable scale.
4768   int64_t NewOffs = Offset / (int64_t)VariableScale;
4769   if (Offset != NewOffs*(int64_t)VariableScale)
4770     return 0;
4771
4772   // Okay, we can do this evaluation.  Start by converting the index to intptr.
4773   const Type *IntPtrTy = TD.getIntPtrType();
4774   if (VariableIdx->getType() != IntPtrTy)
4775     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4776                                               true /*SExt*/, 
4777                                               VariableIdx->getNameStart(), &I);
4778   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4779   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4780 }
4781
4782
4783 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4784 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4785 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4786                                        ICmpInst::Predicate Cond,
4787                                        Instruction &I) {
4788   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4789
4790   // Look through bitcasts.
4791   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4792     RHS = BCI->getOperand(0);
4793
4794   Value *PtrBase = GEPLHS->getOperand(0);
4795   if (PtrBase == RHS) {
4796     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4797     // This transformation (ignoring the base and scales) is valid because we
4798     // know pointers can't overflow.  See if we can output an optimized form.
4799     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4800     
4801     // If not, synthesize the offset the hard way.
4802     if (Offset == 0)
4803       Offset = EmitGEPOffset(GEPLHS, I, *this);
4804     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4805                         Constant::getNullValue(Offset->getType()));
4806   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4807     // If the base pointers are different, but the indices are the same, just
4808     // compare the base pointer.
4809     if (PtrBase != GEPRHS->getOperand(0)) {
4810       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4811       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4812                         GEPRHS->getOperand(0)->getType();
4813       if (IndicesTheSame)
4814         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4815           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4816             IndicesTheSame = false;
4817             break;
4818           }
4819
4820       // If all indices are the same, just compare the base pointers.
4821       if (IndicesTheSame)
4822         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4823                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4824
4825       // Otherwise, the base pointers are different and the indices are
4826       // different, bail out.
4827       return 0;
4828     }
4829
4830     // If one of the GEPs has all zero indices, recurse.
4831     bool AllZeros = true;
4832     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4833       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4834           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4835         AllZeros = false;
4836         break;
4837       }
4838     if (AllZeros)
4839       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4840                           ICmpInst::getSwappedPredicate(Cond), I);
4841
4842     // If the other GEP has all zero indices, recurse.
4843     AllZeros = true;
4844     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4845       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4846           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4847         AllZeros = false;
4848         break;
4849       }
4850     if (AllZeros)
4851       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4852
4853     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4854       // If the GEPs only differ by one index, compare it.
4855       unsigned NumDifferences = 0;  // Keep track of # differences.
4856       unsigned DiffOperand = 0;     // The operand that differs.
4857       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4858         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4859           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4860                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4861             // Irreconcilable differences.
4862             NumDifferences = 2;
4863             break;
4864           } else {
4865             if (NumDifferences++) break;
4866             DiffOperand = i;
4867           }
4868         }
4869
4870       if (NumDifferences == 0)   // SAME GEP?
4871         return ReplaceInstUsesWith(I, // No comparison is needed here.
4872                                    ConstantInt::get(Type::Int1Ty,
4873                                              ICmpInst::isTrueWhenEqual(Cond)));
4874
4875       else if (NumDifferences == 1) {
4876         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4877         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4878         // Make sure we do a signed comparison here.
4879         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4880       }
4881     }
4882
4883     // Only lower this if the icmp is the only user of the GEP or if we expect
4884     // the result to fold to a constant!
4885     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4886         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4887       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4888       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4889       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4890       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4891     }
4892   }
4893   return 0;
4894 }
4895
4896 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4897 ///
4898 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4899                                                 Instruction *LHSI,
4900                                                 Constant *RHSC) {
4901   if (!isa<ConstantFP>(RHSC)) return 0;
4902   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4903   
4904   // Get the width of the mantissa.  We don't want to hack on conversions that
4905   // might lose information from the integer, e.g. "i64 -> float"
4906   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4907   if (MantissaWidth == -1) return 0;  // Unknown.
4908   
4909   // Check to see that the input is converted from an integer type that is small
4910   // enough that preserves all bits.  TODO: check here for "known" sign bits.
4911   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4912   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4913   
4914   // If this is a uitofp instruction, we need an extra bit to hold the sign.
4915   if (isa<UIToFPInst>(LHSI))
4916     ++InputSize;
4917   
4918   // If the conversion would lose info, don't hack on this.
4919   if ((int)InputSize > MantissaWidth)
4920     return 0;
4921   
4922   // Otherwise, we can potentially simplify the comparison.  We know that it
4923   // will always come through as an integer value and we know the constant is
4924   // not a NAN (it would have been previously simplified).
4925   assert(!RHS.isNaN() && "NaN comparison not already folded!");
4926   
4927   ICmpInst::Predicate Pred;
4928   switch (I.getPredicate()) {
4929   default: assert(0 && "Unexpected predicate!");
4930   case FCmpInst::FCMP_UEQ:
4931   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4932   case FCmpInst::FCMP_UGT:
4933   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4934   case FCmpInst::FCMP_UGE:
4935   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4936   case FCmpInst::FCMP_ULT:
4937   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4938   case FCmpInst::FCMP_ULE:
4939   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4940   case FCmpInst::FCMP_UNE:
4941   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4942   case FCmpInst::FCMP_ORD:
4943     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4944   case FCmpInst::FCMP_UNO:
4945     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4946   }
4947   
4948   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4949   
4950   // Now we know that the APFloat is a normal number, zero or inf.
4951   
4952   // See if the FP constant is too large for the integer.  For example,
4953   // comparing an i8 to 300.0.
4954   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4955   
4956   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
4957   // and large values. 
4958   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4959   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4960                         APFloat::rmNearestTiesToEven);
4961   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
4962     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4963         Pred == ICmpInst::ICMP_SLE)
4964       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4965     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4966   }
4967   
4968   // See if the RHS value is < SignedMin.
4969   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4970   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4971                         APFloat::rmNearestTiesToEven);
4972   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4973     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4974         Pred == ICmpInst::ICMP_SGE)
4975       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4976     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4977   }
4978
4979   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4980   // it may still be fractional.  See if it is fractional by casting the FP
4981   // value to the integer value and back, checking for equality.  Don't do this
4982   // for zero, because -0.0 is not fractional.
4983   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4984   if (!RHS.isZero() &&
4985       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4986     // If we had a comparison against a fractional value, we have to adjust
4987     // the compare predicate and sometimes the value.  RHSC is rounded towards
4988     // zero at this point.
4989     switch (Pred) {
4990     default: assert(0 && "Unexpected integer comparison!");
4991     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
4992       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4993     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
4994       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4995     case ICmpInst::ICMP_SLE:
4996       // (float)int <= 4.4   --> int <= 4
4997       // (float)int <= -4.4  --> int < -4
4998       if (RHS.isNegative())
4999         Pred = ICmpInst::ICMP_SLT;
5000       break;
5001     case ICmpInst::ICMP_SLT:
5002       // (float)int < -4.4   --> int < -4
5003       // (float)int < 4.4    --> int <= 4
5004       if (!RHS.isNegative())
5005         Pred = ICmpInst::ICMP_SLE;
5006       break;
5007     case ICmpInst::ICMP_SGT:
5008       // (float)int > 4.4    --> int > 4
5009       // (float)int > -4.4   --> int >= -4
5010       if (RHS.isNegative())
5011         Pred = ICmpInst::ICMP_SGE;
5012       break;
5013     case ICmpInst::ICMP_SGE:
5014       // (float)int >= -4.4   --> int >= -4
5015       // (float)int >= 4.4    --> int > 4
5016       if (!RHS.isNegative())
5017         Pred = ICmpInst::ICMP_SGT;
5018       break;
5019     }
5020   }
5021
5022   // Lower this FP comparison into an appropriate integer version of the
5023   // comparison.
5024   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5025 }
5026
5027 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5028   bool Changed = SimplifyCompare(I);
5029   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5030
5031   // Fold trivial predicates.
5032   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5033     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5034   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5035     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5036   
5037   // Simplify 'fcmp pred X, X'
5038   if (Op0 == Op1) {
5039     switch (I.getPredicate()) {
5040     default: assert(0 && "Unknown predicate!");
5041     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5042     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5043     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5044       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5045     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5046     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5047     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5048       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5049       
5050     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5051     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5052     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5053     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5054       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5055       I.setPredicate(FCmpInst::FCMP_UNO);
5056       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5057       return &I;
5058       
5059     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5060     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5061     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5062     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5063       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5064       I.setPredicate(FCmpInst::FCMP_ORD);
5065       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5066       return &I;
5067     }
5068   }
5069     
5070   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5071     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5072
5073   // Handle fcmp with constant RHS
5074   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5075     // If the constant is a nan, see if we can fold the comparison based on it.
5076     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5077       if (CFP->getValueAPF().isNaN()) {
5078         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5079           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5080         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5081                "Comparison must be either ordered or unordered!");
5082         // True if unordered.
5083         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5084       }
5085     }
5086     
5087     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5088       switch (LHSI->getOpcode()) {
5089       case Instruction::PHI:
5090         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5091         // block.  If in the same block, we're encouraging jump threading.  If
5092         // not, we are just pessimizing the code by making an i1 phi.
5093         if (LHSI->getParent() == I.getParent())
5094           if (Instruction *NV = FoldOpIntoPhi(I))
5095             return NV;
5096         break;
5097       case Instruction::SIToFP:
5098       case Instruction::UIToFP:
5099         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5100           return NV;
5101         break;
5102       case Instruction::Select:
5103         // If either operand of the select is a constant, we can fold the
5104         // comparison into the select arms, which will cause one to be
5105         // constant folded and the select turned into a bitwise or.
5106         Value *Op1 = 0, *Op2 = 0;
5107         if (LHSI->hasOneUse()) {
5108           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5109             // Fold the known value into the constant operand.
5110             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5111             // Insert a new FCmp of the other select operand.
5112             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5113                                                       LHSI->getOperand(2), RHSC,
5114                                                       I.getName()), I);
5115           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5116             // Fold the known value into the constant operand.
5117             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5118             // Insert a new FCmp of the other select operand.
5119             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5120                                                       LHSI->getOperand(1), RHSC,
5121                                                       I.getName()), I);
5122           }
5123         }
5124
5125         if (Op1)
5126           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5127         break;
5128       }
5129   }
5130
5131   return Changed ? &I : 0;
5132 }
5133
5134 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5135   bool Changed = SimplifyCompare(I);
5136   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5137   const Type *Ty = Op0->getType();
5138
5139   // icmp X, X
5140   if (Op0 == Op1)
5141     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5142                                                    I.isTrueWhenEqual()));
5143
5144   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5145     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5146   
5147   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5148   // addresses never equal each other!  We already know that Op0 != Op1.
5149   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5150        isa<ConstantPointerNull>(Op0)) &&
5151       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5152        isa<ConstantPointerNull>(Op1)))
5153     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5154                                                    !I.isTrueWhenEqual()));
5155
5156   // icmp's with boolean values can always be turned into bitwise operations
5157   if (Ty == Type::Int1Ty) {
5158     switch (I.getPredicate()) {
5159     default: assert(0 && "Invalid icmp instruction!");
5160     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
5161       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5162       InsertNewInstBefore(Xor, I);
5163       return BinaryOperator::CreateNot(Xor);
5164     }
5165     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
5166       return BinaryOperator::CreateXor(Op0, Op1);
5167
5168     case ICmpInst::ICMP_UGT:
5169     case ICmpInst::ICMP_SGT:
5170       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
5171       // FALL THROUGH
5172     case ICmpInst::ICMP_ULT:
5173     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
5174       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5175       InsertNewInstBefore(Not, I);
5176       return BinaryOperator::CreateAnd(Not, Op1);
5177     }
5178     case ICmpInst::ICMP_UGE:
5179     case ICmpInst::ICMP_SGE:
5180       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
5181       // FALL THROUGH
5182     case ICmpInst::ICMP_ULE:
5183     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
5184       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5185       InsertNewInstBefore(Not, I);
5186       return BinaryOperator::CreateOr(Not, Op1);
5187     }
5188     }
5189   }
5190
5191   // See if we are doing a comparison between a constant and an instruction that
5192   // can be folded into the comparison.
5193   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5194       Value *A, *B;
5195     
5196     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5197     if (I.isEquality() && CI->isNullValue() &&
5198         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5199       // (icmp cond A B) if cond is equality
5200       return new ICmpInst(I.getPredicate(), A, B);
5201     }
5202     
5203     switch (I.getPredicate()) {
5204     default: break;
5205     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5206       if (CI->isMinValue(false))
5207         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5208       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5209         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5210       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5211         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5212       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5213       if (CI->isMinValue(true))
5214         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5215                             ConstantInt::getAllOnesValue(Op0->getType()));
5216           
5217       break;
5218
5219     case ICmpInst::ICMP_SLT:
5220       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5221         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5222       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5223         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5224       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5225         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5226       break;
5227
5228     case ICmpInst::ICMP_UGT:
5229       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5230         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5231       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5232         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5233       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5234         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5235         
5236       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5237       if (CI->isMaxValue(true))
5238         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5239                             ConstantInt::getNullValue(Op0->getType()));
5240       break;
5241
5242     case ICmpInst::ICMP_SGT:
5243       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5244         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5245       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5246         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5247       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5248         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5249       break;
5250
5251     case ICmpInst::ICMP_ULE:
5252       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5253         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5254       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5255         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5256       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5257         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5258       break;
5259
5260     case ICmpInst::ICMP_SLE:
5261       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5262         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5263       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5264         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5265       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5266         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5267       break;
5268
5269     case ICmpInst::ICMP_UGE:
5270       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5271         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5272       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5273         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5274       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5275         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5276       break;
5277
5278     case ICmpInst::ICMP_SGE:
5279       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5280         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5281       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5282         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5283       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5284         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5285       break;
5286     }
5287
5288     // If we still have a icmp le or icmp ge instruction, turn it into the
5289     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5290     // already been handled above, this requires little checking.
5291     //
5292     switch (I.getPredicate()) {
5293     default: break;
5294     case ICmpInst::ICMP_ULE: 
5295       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5296     case ICmpInst::ICMP_SLE:
5297       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5298     case ICmpInst::ICMP_UGE:
5299       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5300     case ICmpInst::ICMP_SGE:
5301       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5302     }
5303     
5304     // See if we can fold the comparison based on bits known to be zero or one
5305     // in the input.  If this comparison is a normal comparison, it demands all
5306     // bits, if it is a sign bit comparison, it only demands the sign bit.
5307     
5308     bool UnusedBit;
5309     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5310     
5311     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5312     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5313     if (SimplifyDemandedBits(Op0, 
5314                              isSignBit ? APInt::getSignBit(BitWidth)
5315                                        : APInt::getAllOnesValue(BitWidth),
5316                              KnownZero, KnownOne, 0))
5317       return &I;
5318         
5319     // Given the known and unknown bits, compute a range that the LHS could be
5320     // in.
5321     if ((KnownOne | KnownZero) != 0) {
5322       // Compute the Min, Max and RHS values based on the known bits. For the
5323       // EQ and NE we use unsigned values.
5324       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5325       const APInt& RHSVal = CI->getValue();
5326       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5327         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5328                                                Max);
5329       } else {
5330         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5331                                                  Max);
5332       }
5333       switch (I.getPredicate()) {  // LE/GE have been folded already.
5334       default: assert(0 && "Unknown icmp opcode!");
5335       case ICmpInst::ICMP_EQ:
5336         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5337           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5338         break;
5339       case ICmpInst::ICMP_NE:
5340         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5341           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5342         break;
5343       case ICmpInst::ICMP_ULT:
5344         if (Max.ult(RHSVal))
5345           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5346         if (Min.uge(RHSVal))
5347           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5348         break;
5349       case ICmpInst::ICMP_UGT:
5350         if (Min.ugt(RHSVal))
5351           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5352         if (Max.ule(RHSVal))
5353           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5354         break;
5355       case ICmpInst::ICMP_SLT:
5356         if (Max.slt(RHSVal))
5357           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5358         if (Min.sgt(RHSVal))
5359           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5360         break;
5361       case ICmpInst::ICMP_SGT: 
5362         if (Min.sgt(RHSVal))
5363           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5364         if (Max.sle(RHSVal))
5365           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5366         break;
5367       }
5368     }
5369           
5370     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5371     // instruction, see if that instruction also has constants so that the 
5372     // instruction can be folded into the icmp 
5373     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5374       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5375         return Res;
5376   }
5377
5378   // Handle icmp with constant (but not simple integer constant) RHS
5379   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5380     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5381       switch (LHSI->getOpcode()) {
5382       case Instruction::GetElementPtr:
5383         if (RHSC->isNullValue()) {
5384           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5385           bool isAllZeros = true;
5386           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5387             if (!isa<Constant>(LHSI->getOperand(i)) ||
5388                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5389               isAllZeros = false;
5390               break;
5391             }
5392           if (isAllZeros)
5393             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5394                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5395         }
5396         break;
5397
5398       case Instruction::PHI:
5399         // Only fold icmp into the PHI if the phi and fcmp are in the same
5400         // block.  If in the same block, we're encouraging jump threading.  If
5401         // not, we are just pessimizing the code by making an i1 phi.
5402         if (LHSI->getParent() == I.getParent())
5403           if (Instruction *NV = FoldOpIntoPhi(I))
5404             return NV;
5405         break;
5406       case Instruction::Select: {
5407         // If either operand of the select is a constant, we can fold the
5408         // comparison into the select arms, which will cause one to be
5409         // constant folded and the select turned into a bitwise or.
5410         Value *Op1 = 0, *Op2 = 0;
5411         if (LHSI->hasOneUse()) {
5412           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5413             // Fold the known value into the constant operand.
5414             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5415             // Insert a new ICmp of the other select operand.
5416             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5417                                                    LHSI->getOperand(2), RHSC,
5418                                                    I.getName()), I);
5419           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5420             // Fold the known value into the constant operand.
5421             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5422             // Insert a new ICmp of the other select operand.
5423             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5424                                                    LHSI->getOperand(1), RHSC,
5425                                                    I.getName()), I);
5426           }
5427         }
5428
5429         if (Op1)
5430           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5431         break;
5432       }
5433       case Instruction::Malloc:
5434         // If we have (malloc != null), and if the malloc has a single use, we
5435         // can assume it is successful and remove the malloc.
5436         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5437           AddToWorkList(LHSI);
5438           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5439                                                          !I.isTrueWhenEqual()));
5440         }
5441         break;
5442       }
5443   }
5444
5445   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5446   if (User *GEP = dyn_castGetElementPtr(Op0))
5447     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5448       return NI;
5449   if (User *GEP = dyn_castGetElementPtr(Op1))
5450     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5451                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5452       return NI;
5453
5454   // Test to see if the operands of the icmp are casted versions of other
5455   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5456   // now.
5457   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5458     if (isa<PointerType>(Op0->getType()) && 
5459         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5460       // We keep moving the cast from the left operand over to the right
5461       // operand, where it can often be eliminated completely.
5462       Op0 = CI->getOperand(0);
5463
5464       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5465       // so eliminate it as well.
5466       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5467         Op1 = CI2->getOperand(0);
5468
5469       // If Op1 is a constant, we can fold the cast into the constant.
5470       if (Op0->getType() != Op1->getType()) {
5471         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5472           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5473         } else {
5474           // Otherwise, cast the RHS right before the icmp
5475           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5476         }
5477       }
5478       return new ICmpInst(I.getPredicate(), Op0, Op1);
5479     }
5480   }
5481   
5482   if (isa<CastInst>(Op0)) {
5483     // Handle the special case of: icmp (cast bool to X), <cst>
5484     // This comes up when you have code like
5485     //   int X = A < B;
5486     //   if (X) ...
5487     // For generality, we handle any zero-extension of any operand comparison
5488     // with a constant or another cast from the same type.
5489     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5490       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5491         return R;
5492   }
5493   
5494   // ~x < ~y --> y < x
5495   { Value *A, *B;
5496     if (match(Op0, m_Not(m_Value(A))) &&
5497         match(Op1, m_Not(m_Value(B))))
5498       return new ICmpInst(I.getPredicate(), B, A);
5499   }
5500   
5501   if (I.isEquality()) {
5502     Value *A, *B, *C, *D;
5503     
5504     // -x == -y --> x == y
5505     if (match(Op0, m_Neg(m_Value(A))) &&
5506         match(Op1, m_Neg(m_Value(B))))
5507       return new ICmpInst(I.getPredicate(), A, B);
5508     
5509     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5510       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5511         Value *OtherVal = A == Op1 ? B : A;
5512         return new ICmpInst(I.getPredicate(), OtherVal,
5513                             Constant::getNullValue(A->getType()));
5514       }
5515
5516       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5517         // A^c1 == C^c2 --> A == C^(c1^c2)
5518         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5519           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5520             if (Op1->hasOneUse()) {
5521               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5522               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5523               return new ICmpInst(I.getPredicate(), A,
5524                                   InsertNewInstBefore(Xor, I));
5525             }
5526         
5527         // A^B == A^D -> B == D
5528         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5529         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5530         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5531         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5532       }
5533     }
5534     
5535     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5536         (A == Op0 || B == Op0)) {
5537       // A == (A^B)  ->  B == 0
5538       Value *OtherVal = A == Op0 ? B : A;
5539       return new ICmpInst(I.getPredicate(), OtherVal,
5540                           Constant::getNullValue(A->getType()));
5541     }
5542     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5543       // (A-B) == A  ->  B == 0
5544       return new ICmpInst(I.getPredicate(), B,
5545                           Constant::getNullValue(B->getType()));
5546     }
5547     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5548       // A == (A-B)  ->  B == 0
5549       return new ICmpInst(I.getPredicate(), B,
5550                           Constant::getNullValue(B->getType()));
5551     }
5552     
5553     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5554     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5555         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5556         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5557       Value *X = 0, *Y = 0, *Z = 0;
5558       
5559       if (A == C) {
5560         X = B; Y = D; Z = A;
5561       } else if (A == D) {
5562         X = B; Y = C; Z = A;
5563       } else if (B == C) {
5564         X = A; Y = D; Z = B;
5565       } else if (B == D) {
5566         X = A; Y = C; Z = B;
5567       }
5568       
5569       if (X) {   // Build (X^Y) & Z
5570         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5571         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5572         I.setOperand(0, Op1);
5573         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5574         return &I;
5575       }
5576     }
5577   }
5578   return Changed ? &I : 0;
5579 }
5580
5581
5582 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5583 /// and CmpRHS are both known to be integer constants.
5584 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5585                                           ConstantInt *DivRHS) {
5586   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5587   const APInt &CmpRHSV = CmpRHS->getValue();
5588   
5589   // FIXME: If the operand types don't match the type of the divide 
5590   // then don't attempt this transform. The code below doesn't have the
5591   // logic to deal with a signed divide and an unsigned compare (and
5592   // vice versa). This is because (x /s C1) <s C2  produces different 
5593   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5594   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5595   // work. :(  The if statement below tests that condition and bails 
5596   // if it finds it. 
5597   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5598   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5599     return 0;
5600   if (DivRHS->isZero())
5601     return 0; // The ProdOV computation fails on divide by zero.
5602
5603   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5604   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5605   // C2 (CI). By solving for X we can turn this into a range check 
5606   // instead of computing a divide. 
5607   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5608
5609   // Determine if the product overflows by seeing if the product is
5610   // not equal to the divide. Make sure we do the same kind of divide
5611   // as in the LHS instruction that we're folding. 
5612   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5613                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5614
5615   // Get the ICmp opcode
5616   ICmpInst::Predicate Pred = ICI.getPredicate();
5617
5618   // Figure out the interval that is being checked.  For example, a comparison
5619   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5620   // Compute this interval based on the constants involved and the signedness of
5621   // the compare/divide.  This computes a half-open interval, keeping track of
5622   // whether either value in the interval overflows.  After analysis each
5623   // overflow variable is set to 0 if it's corresponding bound variable is valid
5624   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5625   int LoOverflow = 0, HiOverflow = 0;
5626   ConstantInt *LoBound = 0, *HiBound = 0;
5627   
5628   
5629   if (!DivIsSigned) {  // udiv
5630     // e.g. X/5 op 3  --> [15, 20)
5631     LoBound = Prod;
5632     HiOverflow = LoOverflow = ProdOV;
5633     if (!HiOverflow)
5634       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5635   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5636     if (CmpRHSV == 0) {       // (X / pos) op 0
5637       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5638       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5639       HiBound = DivRHS;
5640     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5641       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5642       HiOverflow = LoOverflow = ProdOV;
5643       if (!HiOverflow)
5644         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5645     } else {                       // (X / pos) op neg
5646       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5647       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5648       LoOverflow = AddWithOverflow(LoBound, Prod,
5649                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5650       HiBound = AddOne(Prod);
5651       HiOverflow = ProdOV ? -1 : 0;
5652     }
5653   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5654     if (CmpRHSV == 0) {       // (X / neg) op 0
5655       // e.g. X/-5 op 0  --> [-4, 5)
5656       LoBound = AddOne(DivRHS);
5657       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5658       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5659         HiOverflow = 1;            // [INTMIN+1, overflow)
5660         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5661       }
5662     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5663       // e.g. X/-5 op 3  --> [-19, -14)
5664       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5665       if (!LoOverflow)
5666         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5667       HiBound = AddOne(Prod);
5668     } else {                       // (X / neg) op neg
5669       // e.g. X/-5 op -3  --> [15, 20)
5670       LoBound = Prod;
5671       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5672       HiBound = Subtract(Prod, DivRHS);
5673     }
5674     
5675     // Dividing by a negative swaps the condition.  LT <-> GT
5676     Pred = ICmpInst::getSwappedPredicate(Pred);
5677   }
5678
5679   Value *X = DivI->getOperand(0);
5680   switch (Pred) {
5681   default: assert(0 && "Unhandled icmp opcode!");
5682   case ICmpInst::ICMP_EQ:
5683     if (LoOverflow && HiOverflow)
5684       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5685     else if (HiOverflow)
5686       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5687                           ICmpInst::ICMP_UGE, X, LoBound);
5688     else if (LoOverflow)
5689       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5690                           ICmpInst::ICMP_ULT, X, HiBound);
5691     else
5692       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5693   case ICmpInst::ICMP_NE:
5694     if (LoOverflow && HiOverflow)
5695       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5696     else if (HiOverflow)
5697       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5698                           ICmpInst::ICMP_ULT, X, LoBound);
5699     else if (LoOverflow)
5700       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5701                           ICmpInst::ICMP_UGE, X, HiBound);
5702     else
5703       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5704   case ICmpInst::ICMP_ULT:
5705   case ICmpInst::ICMP_SLT:
5706     if (LoOverflow == +1)   // Low bound is greater than input range.
5707       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5708     if (LoOverflow == -1)   // Low bound is less than input range.
5709       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5710     return new ICmpInst(Pred, X, LoBound);
5711   case ICmpInst::ICMP_UGT:
5712   case ICmpInst::ICMP_SGT:
5713     if (HiOverflow == +1)       // High bound greater than input range.
5714       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5715     else if (HiOverflow == -1)  // High bound less than input range.
5716       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5717     if (Pred == ICmpInst::ICMP_UGT)
5718       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5719     else
5720       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5721   }
5722 }
5723
5724
5725 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5726 ///
5727 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5728                                                           Instruction *LHSI,
5729                                                           ConstantInt *RHS) {
5730   const APInt &RHSV = RHS->getValue();
5731   
5732   switch (LHSI->getOpcode()) {
5733   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5734     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5735       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5736       // fold the xor.
5737       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5738           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5739         Value *CompareVal = LHSI->getOperand(0);
5740         
5741         // If the sign bit of the XorCST is not set, there is no change to
5742         // the operation, just stop using the Xor.
5743         if (!XorCST->getValue().isNegative()) {
5744           ICI.setOperand(0, CompareVal);
5745           AddToWorkList(LHSI);
5746           return &ICI;
5747         }
5748         
5749         // Was the old condition true if the operand is positive?
5750         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5751         
5752         // If so, the new one isn't.
5753         isTrueIfPositive ^= true;
5754         
5755         if (isTrueIfPositive)
5756           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5757         else
5758           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5759       }
5760     }
5761     break;
5762   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5763     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5764         LHSI->getOperand(0)->hasOneUse()) {
5765       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5766       
5767       // If the LHS is an AND of a truncating cast, we can widen the
5768       // and/compare to be the input width without changing the value
5769       // produced, eliminating a cast.
5770       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5771         // We can do this transformation if either the AND constant does not
5772         // have its sign bit set or if it is an equality comparison. 
5773         // Extending a relational comparison when we're checking the sign
5774         // bit would not work.
5775         if (Cast->hasOneUse() &&
5776             (ICI.isEquality() ||
5777              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5778           uint32_t BitWidth = 
5779             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5780           APInt NewCST = AndCST->getValue();
5781           NewCST.zext(BitWidth);
5782           APInt NewCI = RHSV;
5783           NewCI.zext(BitWidth);
5784           Instruction *NewAnd = 
5785             BinaryOperator::CreateAnd(Cast->getOperand(0),
5786                                       ConstantInt::get(NewCST),LHSI->getName());
5787           InsertNewInstBefore(NewAnd, ICI);
5788           return new ICmpInst(ICI.getPredicate(), NewAnd,
5789                               ConstantInt::get(NewCI));
5790         }
5791       }
5792       
5793       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5794       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5795       // happens a LOT in code produced by the C front-end, for bitfield
5796       // access.
5797       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5798       if (Shift && !Shift->isShift())
5799         Shift = 0;
5800       
5801       ConstantInt *ShAmt;
5802       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5803       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5804       const Type *AndTy = AndCST->getType();          // Type of the and.
5805       
5806       // We can fold this as long as we can't shift unknown bits
5807       // into the mask.  This can only happen with signed shift
5808       // rights, as they sign-extend.
5809       if (ShAmt) {
5810         bool CanFold = Shift->isLogicalShift();
5811         if (!CanFold) {
5812           // To test for the bad case of the signed shr, see if any
5813           // of the bits shifted in could be tested after the mask.
5814           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5815           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5816           
5817           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5818           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5819                AndCST->getValue()) == 0)
5820             CanFold = true;
5821         }
5822         
5823         if (CanFold) {
5824           Constant *NewCst;
5825           if (Shift->getOpcode() == Instruction::Shl)
5826             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5827           else
5828             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5829           
5830           // Check to see if we are shifting out any of the bits being
5831           // compared.
5832           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5833             // If we shifted bits out, the fold is not going to work out.
5834             // As a special case, check to see if this means that the
5835             // result is always true or false now.
5836             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5837               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5838             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5839               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5840           } else {
5841             ICI.setOperand(1, NewCst);
5842             Constant *NewAndCST;
5843             if (Shift->getOpcode() == Instruction::Shl)
5844               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5845             else
5846               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5847             LHSI->setOperand(1, NewAndCST);
5848             LHSI->setOperand(0, Shift->getOperand(0));
5849             AddToWorkList(Shift); // Shift is dead.
5850             AddUsesToWorkList(ICI);
5851             return &ICI;
5852           }
5853         }
5854       }
5855       
5856       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5857       // preferable because it allows the C<<Y expression to be hoisted out
5858       // of a loop if Y is invariant and X is not.
5859       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5860           ICI.isEquality() && !Shift->isArithmeticShift() &&
5861           isa<Instruction>(Shift->getOperand(0))) {
5862         // Compute C << Y.
5863         Value *NS;
5864         if (Shift->getOpcode() == Instruction::LShr) {
5865           NS = BinaryOperator::CreateShl(AndCST, 
5866                                          Shift->getOperand(1), "tmp");
5867         } else {
5868           // Insert a logical shift.
5869           NS = BinaryOperator::CreateLShr(AndCST,
5870                                           Shift->getOperand(1), "tmp");
5871         }
5872         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5873         
5874         // Compute X & (C << Y).
5875         Instruction *NewAnd = 
5876           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5877         InsertNewInstBefore(NewAnd, ICI);
5878         
5879         ICI.setOperand(0, NewAnd);
5880         return &ICI;
5881       }
5882     }
5883     break;
5884     
5885   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5886     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5887     if (!ShAmt) break;
5888     
5889     uint32_t TypeBits = RHSV.getBitWidth();
5890     
5891     // Check that the shift amount is in range.  If not, don't perform
5892     // undefined shifts.  When the shift is visited it will be
5893     // simplified.
5894     if (ShAmt->uge(TypeBits))
5895       break;
5896     
5897     if (ICI.isEquality()) {
5898       // If we are comparing against bits always shifted out, the
5899       // comparison cannot succeed.
5900       Constant *Comp =
5901         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5902       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5903         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5904         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5905         return ReplaceInstUsesWith(ICI, Cst);
5906       }
5907       
5908       if (LHSI->hasOneUse()) {
5909         // Otherwise strength reduce the shift into an and.
5910         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5911         Constant *Mask =
5912           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5913         
5914         Instruction *AndI =
5915           BinaryOperator::CreateAnd(LHSI->getOperand(0),
5916                                     Mask, LHSI->getName()+".mask");
5917         Value *And = InsertNewInstBefore(AndI, ICI);
5918         return new ICmpInst(ICI.getPredicate(), And,
5919                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5920       }
5921     }
5922     
5923     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5924     bool TrueIfSigned = false;
5925     if (LHSI->hasOneUse() &&
5926         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5927       // (X << 31) <s 0  --> (X&1) != 0
5928       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5929                                            (TypeBits-ShAmt->getZExtValue()-1));
5930       Instruction *AndI =
5931         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5932                                   Mask, LHSI->getName()+".mask");
5933       Value *And = InsertNewInstBefore(AndI, ICI);
5934       
5935       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5936                           And, Constant::getNullValue(And->getType()));
5937     }
5938     break;
5939   }
5940     
5941   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5942   case Instruction::AShr: {
5943     // Only handle equality comparisons of shift-by-constant.
5944     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5945     if (!ShAmt || !ICI.isEquality()) break;
5946
5947     // Check that the shift amount is in range.  If not, don't perform
5948     // undefined shifts.  When the shift is visited it will be
5949     // simplified.
5950     uint32_t TypeBits = RHSV.getBitWidth();
5951     if (ShAmt->uge(TypeBits))
5952       break;
5953     
5954     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5955       
5956     // If we are comparing against bits always shifted out, the
5957     // comparison cannot succeed.
5958     APInt Comp = RHSV << ShAmtVal;
5959     if (LHSI->getOpcode() == Instruction::LShr)
5960       Comp = Comp.lshr(ShAmtVal);
5961     else
5962       Comp = Comp.ashr(ShAmtVal);
5963     
5964     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5965       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5966       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5967       return ReplaceInstUsesWith(ICI, Cst);
5968     }
5969     
5970     // Otherwise, check to see if the bits shifted out are known to be zero.
5971     // If so, we can compare against the unshifted value:
5972     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
5973     if (LHSI->hasOneUse() &&
5974         MaskedValueIsZero(LHSI->getOperand(0), 
5975                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5976       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5977                           ConstantExpr::getShl(RHS, ShAmt));
5978     }
5979       
5980     if (LHSI->hasOneUse()) {
5981       // Otherwise strength reduce the shift into an and.
5982       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5983       Constant *Mask = ConstantInt::get(Val);
5984       
5985       Instruction *AndI =
5986         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5987                                   Mask, LHSI->getName()+".mask");
5988       Value *And = InsertNewInstBefore(AndI, ICI);
5989       return new ICmpInst(ICI.getPredicate(), And,
5990                           ConstantExpr::getShl(RHS, ShAmt));
5991     }
5992     break;
5993   }
5994     
5995   case Instruction::SDiv:
5996   case Instruction::UDiv:
5997     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5998     // Fold this div into the comparison, producing a range check. 
5999     // Determine, based on the divide type, what the range is being 
6000     // checked.  If there is an overflow on the low or high side, remember 
6001     // it, otherwise compute the range [low, hi) bounding the new value.
6002     // See: InsertRangeTest above for the kinds of replacements possible.
6003     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6004       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6005                                           DivRHS))
6006         return R;
6007     break;
6008
6009   case Instruction::Add:
6010     // Fold: icmp pred (add, X, C1), C2
6011
6012     if (!ICI.isEquality()) {
6013       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6014       if (!LHSC) break;
6015       const APInt &LHSV = LHSC->getValue();
6016
6017       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6018                             .subtract(LHSV);
6019
6020       if (ICI.isSignedPredicate()) {
6021         if (CR.getLower().isSignBit()) {
6022           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6023                               ConstantInt::get(CR.getUpper()));
6024         } else if (CR.getUpper().isSignBit()) {
6025           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6026                               ConstantInt::get(CR.getLower()));
6027         }
6028       } else {
6029         if (CR.getLower().isMinValue()) {
6030           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6031                               ConstantInt::get(CR.getUpper()));
6032         } else if (CR.getUpper().isMinValue()) {
6033           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6034                               ConstantInt::get(CR.getLower()));
6035         }
6036       }
6037     }
6038     break;
6039   }
6040   
6041   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6042   if (ICI.isEquality()) {
6043     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6044     
6045     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6046     // the second operand is a constant, simplify a bit.
6047     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6048       switch (BO->getOpcode()) {
6049       case Instruction::SRem:
6050         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6051         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6052           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6053           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6054             Instruction *NewRem =
6055               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6056                                          BO->getName());
6057             InsertNewInstBefore(NewRem, ICI);
6058             return new ICmpInst(ICI.getPredicate(), NewRem, 
6059                                 Constant::getNullValue(BO->getType()));
6060           }
6061         }
6062         break;
6063       case Instruction::Add:
6064         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6065         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6066           if (BO->hasOneUse())
6067             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6068                                 Subtract(RHS, BOp1C));
6069         } else if (RHSV == 0) {
6070           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6071           // efficiently invertible, or if the add has just this one use.
6072           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6073           
6074           if (Value *NegVal = dyn_castNegVal(BOp1))
6075             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6076           else if (Value *NegVal = dyn_castNegVal(BOp0))
6077             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6078           else if (BO->hasOneUse()) {
6079             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6080             InsertNewInstBefore(Neg, ICI);
6081             Neg->takeName(BO);
6082             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6083           }
6084         }
6085         break;
6086       case Instruction::Xor:
6087         // For the xor case, we can xor two constants together, eliminating
6088         // the explicit xor.
6089         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6090           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6091                               ConstantExpr::getXor(RHS, BOC));
6092         
6093         // FALLTHROUGH
6094       case Instruction::Sub:
6095         // Replace (([sub|xor] A, B) != 0) with (A != B)
6096         if (RHSV == 0)
6097           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6098                               BO->getOperand(1));
6099         break;
6100         
6101       case Instruction::Or:
6102         // If bits are being or'd in that are not present in the constant we
6103         // are comparing against, then the comparison could never succeed!
6104         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6105           Constant *NotCI = ConstantExpr::getNot(RHS);
6106           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6107             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6108                                                              isICMP_NE));
6109         }
6110         break;
6111         
6112       case Instruction::And:
6113         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6114           // If bits are being compared against that are and'd out, then the
6115           // comparison can never succeed!
6116           if ((RHSV & ~BOC->getValue()) != 0)
6117             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6118                                                              isICMP_NE));
6119           
6120           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6121           if (RHS == BOC && RHSV.isPowerOf2())
6122             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6123                                 ICmpInst::ICMP_NE, LHSI,
6124                                 Constant::getNullValue(RHS->getType()));
6125           
6126           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6127           if (BOC->getValue().isSignBit()) {
6128             Value *X = BO->getOperand(0);
6129             Constant *Zero = Constant::getNullValue(X->getType());
6130             ICmpInst::Predicate pred = isICMP_NE ? 
6131               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6132             return new ICmpInst(pred, X, Zero);
6133           }
6134           
6135           // ((X & ~7) == 0) --> X < 8
6136           if (RHSV == 0 && isHighOnes(BOC)) {
6137             Value *X = BO->getOperand(0);
6138             Constant *NegX = ConstantExpr::getNeg(BOC);
6139             ICmpInst::Predicate pred = isICMP_NE ? 
6140               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6141             return new ICmpInst(pred, X, NegX);
6142           }
6143         }
6144       default: break;
6145       }
6146     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6147       // Handle icmp {eq|ne} <intrinsic>, intcst.
6148       if (II->getIntrinsicID() == Intrinsic::bswap) {
6149         AddToWorkList(II);
6150         ICI.setOperand(0, II->getOperand(1));
6151         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6152         return &ICI;
6153       }
6154     }
6155   } else {  // Not a ICMP_EQ/ICMP_NE
6156             // If the LHS is a cast from an integral value of the same size, 
6157             // then since we know the RHS is a constant, try to simlify.
6158     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6159       Value *CastOp = Cast->getOperand(0);
6160       const Type *SrcTy = CastOp->getType();
6161       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6162       if (SrcTy->isInteger() && 
6163           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6164         // If this is an unsigned comparison, try to make the comparison use
6165         // smaller constant values.
6166         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6167           // X u< 128 => X s> -1
6168           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6169                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6170         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6171                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6172           // X u> 127 => X s< 0
6173           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6174                               Constant::getNullValue(SrcTy));
6175         }
6176       }
6177     }
6178   }
6179   return 0;
6180 }
6181
6182 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6183 /// We only handle extending casts so far.
6184 ///
6185 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6186   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6187   Value *LHSCIOp        = LHSCI->getOperand(0);
6188   const Type *SrcTy     = LHSCIOp->getType();
6189   const Type *DestTy    = LHSCI->getType();
6190   Value *RHSCIOp;
6191
6192   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6193   // integer type is the same size as the pointer type.
6194   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6195       getTargetData().getPointerSizeInBits() == 
6196          cast<IntegerType>(DestTy)->getBitWidth()) {
6197     Value *RHSOp = 0;
6198     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6199       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6200     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6201       RHSOp = RHSC->getOperand(0);
6202       // If the pointer types don't match, insert a bitcast.
6203       if (LHSCIOp->getType() != RHSOp->getType())
6204         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6205     }
6206
6207     if (RHSOp)
6208       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6209   }
6210   
6211   // The code below only handles extension cast instructions, so far.
6212   // Enforce this.
6213   if (LHSCI->getOpcode() != Instruction::ZExt &&
6214       LHSCI->getOpcode() != Instruction::SExt)
6215     return 0;
6216
6217   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6218   bool isSignedCmp = ICI.isSignedPredicate();
6219
6220   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6221     // Not an extension from the same type?
6222     RHSCIOp = CI->getOperand(0);
6223     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6224       return 0;
6225     
6226     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6227     // and the other is a zext), then we can't handle this.
6228     if (CI->getOpcode() != LHSCI->getOpcode())
6229       return 0;
6230
6231     // Deal with equality cases early.
6232     if (ICI.isEquality())
6233       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6234
6235     // A signed comparison of sign extended values simplifies into a
6236     // signed comparison.
6237     if (isSignedCmp && isSignedExt)
6238       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6239
6240     // The other three cases all fold into an unsigned comparison.
6241     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6242   }
6243
6244   // If we aren't dealing with a constant on the RHS, exit early
6245   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6246   if (!CI)
6247     return 0;
6248
6249   // Compute the constant that would happen if we truncated to SrcTy then
6250   // reextended to DestTy.
6251   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6252   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6253
6254   // If the re-extended constant didn't change...
6255   if (Res2 == CI) {
6256     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6257     // For example, we might have:
6258     //    %A = sext short %X to uint
6259     //    %B = icmp ugt uint %A, 1330
6260     // It is incorrect to transform this into 
6261     //    %B = icmp ugt short %X, 1330 
6262     // because %A may have negative value. 
6263     //
6264     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6265     // OR operation is EQ/NE.
6266     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6267       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6268     else
6269       return 0;
6270   }
6271
6272   // The re-extended constant changed so the constant cannot be represented 
6273   // in the shorter type. Consequently, we cannot emit a simple comparison.
6274
6275   // First, handle some easy cases. We know the result cannot be equal at this
6276   // point so handle the ICI.isEquality() cases
6277   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6278     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6279   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6280     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6281
6282   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6283   // should have been folded away previously and not enter in here.
6284   Value *Result;
6285   if (isSignedCmp) {
6286     // We're performing a signed comparison.
6287     if (cast<ConstantInt>(CI)->getValue().isNegative())
6288       Result = ConstantInt::getFalse();          // X < (small) --> false
6289     else
6290       Result = ConstantInt::getTrue();           // X < (large) --> true
6291   } else {
6292     // We're performing an unsigned comparison.
6293     if (isSignedExt) {
6294       // We're performing an unsigned comp with a sign extended value.
6295       // This is true if the input is >= 0. [aka >s -1]
6296       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6297       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6298                                    NegOne, ICI.getName()), ICI);
6299     } else {
6300       // Unsigned extend & unsigned compare -> always true.
6301       Result = ConstantInt::getTrue();
6302     }
6303   }
6304
6305   // Finally, return the value computed.
6306   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6307       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6308     return ReplaceInstUsesWith(ICI, Result);
6309   } else {
6310     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6311             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6312            "ICmp should be folded!");
6313     if (Constant *CI = dyn_cast<Constant>(Result))
6314       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6315     else
6316       return BinaryOperator::CreateNot(Result);
6317   }
6318 }
6319
6320 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6321   return commonShiftTransforms(I);
6322 }
6323
6324 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6325   return commonShiftTransforms(I);
6326 }
6327
6328 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6329   if (Instruction *R = commonShiftTransforms(I))
6330     return R;
6331   
6332   Value *Op0 = I.getOperand(0);
6333   
6334   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6335   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6336     if (CSI->isAllOnesValue())
6337       return ReplaceInstUsesWith(I, CSI);
6338   
6339   // See if we can turn a signed shr into an unsigned shr.
6340   if (MaskedValueIsZero(Op0, 
6341                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6342     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6343   
6344   return 0;
6345 }
6346
6347 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6348   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6349   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6350
6351   // shl X, 0 == X and shr X, 0 == X
6352   // shl 0, X == 0 and shr 0, X == 0
6353   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6354       Op0 == Constant::getNullValue(Op0->getType()))
6355     return ReplaceInstUsesWith(I, Op0);
6356   
6357   if (isa<UndefValue>(Op0)) {            
6358     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6359       return ReplaceInstUsesWith(I, Op0);
6360     else                                    // undef << X -> 0, undef >>u X -> 0
6361       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6362   }
6363   if (isa<UndefValue>(Op1)) {
6364     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6365       return ReplaceInstUsesWith(I, Op0);          
6366     else                                     // X << undef, X >>u undef -> 0
6367       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6368   }
6369
6370   // Try to fold constant and into select arguments.
6371   if (isa<Constant>(Op0))
6372     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6373       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6374         return R;
6375
6376   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6377     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6378       return Res;
6379   return 0;
6380 }
6381
6382 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6383                                                BinaryOperator &I) {
6384   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6385
6386   // See if we can simplify any instructions used by the instruction whose sole 
6387   // purpose is to compute bits we don't care about.
6388   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6389   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6390   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6391                            KnownZero, KnownOne))
6392     return &I;
6393   
6394   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6395   // of a signed value.
6396   //
6397   if (Op1->uge(TypeBits)) {
6398     if (I.getOpcode() != Instruction::AShr)
6399       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6400     else {
6401       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6402       return &I;
6403     }
6404   }
6405   
6406   // ((X*C1) << C2) == (X * (C1 << C2))
6407   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6408     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6409       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6410         return BinaryOperator::CreateMul(BO->getOperand(0),
6411                                          ConstantExpr::getShl(BOOp, Op1));
6412   
6413   // Try to fold constant and into select arguments.
6414   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6415     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6416       return R;
6417   if (isa<PHINode>(Op0))
6418     if (Instruction *NV = FoldOpIntoPhi(I))
6419       return NV;
6420   
6421   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6422   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6423     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6424     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6425     // place.  Don't try to do this transformation in this case.  Also, we
6426     // require that the input operand is a shift-by-constant so that we have
6427     // confidence that the shifts will get folded together.  We could do this
6428     // xform in more cases, but it is unlikely to be profitable.
6429     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6430         isa<ConstantInt>(TrOp->getOperand(1))) {
6431       // Okay, we'll do this xform.  Make the shift of shift.
6432       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6433       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6434                                                 I.getName());
6435       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6436
6437       // For logical shifts, the truncation has the effect of making the high
6438       // part of the register be zeros.  Emulate this by inserting an AND to
6439       // clear the top bits as needed.  This 'and' will usually be zapped by
6440       // other xforms later if dead.
6441       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6442       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6443       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6444       
6445       // The mask we constructed says what the trunc would do if occurring
6446       // between the shifts.  We want to know the effect *after* the second
6447       // shift.  We know that it is a logical shift by a constant, so adjust the
6448       // mask as appropriate.
6449       if (I.getOpcode() == Instruction::Shl)
6450         MaskV <<= Op1->getZExtValue();
6451       else {
6452         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6453         MaskV = MaskV.lshr(Op1->getZExtValue());
6454       }
6455
6456       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6457                                                    TI->getName());
6458       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6459
6460       // Return the value truncated to the interesting size.
6461       return new TruncInst(And, I.getType());
6462     }
6463   }
6464   
6465   if (Op0->hasOneUse()) {
6466     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6467       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6468       Value *V1, *V2;
6469       ConstantInt *CC;
6470       switch (Op0BO->getOpcode()) {
6471         default: break;
6472         case Instruction::Add:
6473         case Instruction::And:
6474         case Instruction::Or:
6475         case Instruction::Xor: {
6476           // These operators commute.
6477           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6478           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6479               match(Op0BO->getOperand(1),
6480                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6481             Instruction *YS = BinaryOperator::CreateShl(
6482                                             Op0BO->getOperand(0), Op1,
6483                                             Op0BO->getName());
6484             InsertNewInstBefore(YS, I); // (Y << C)
6485             Instruction *X = 
6486               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6487                                      Op0BO->getOperand(1)->getName());
6488             InsertNewInstBefore(X, I);  // (X + (Y << C))
6489             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6490             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6491                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6492           }
6493           
6494           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6495           Value *Op0BOOp1 = Op0BO->getOperand(1);
6496           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6497               match(Op0BOOp1, 
6498                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6499               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6500               V2 == Op1) {
6501             Instruction *YS = BinaryOperator::CreateShl(
6502                                                      Op0BO->getOperand(0), Op1,
6503                                                      Op0BO->getName());
6504             InsertNewInstBefore(YS, I); // (Y << C)
6505             Instruction *XM =
6506               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6507                                         V1->getName()+".mask");
6508             InsertNewInstBefore(XM, I); // X & (CC << C)
6509             
6510             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6511           }
6512         }
6513           
6514         // FALL THROUGH.
6515         case Instruction::Sub: {
6516           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6517           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6518               match(Op0BO->getOperand(0),
6519                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6520             Instruction *YS = BinaryOperator::CreateShl(
6521                                                      Op0BO->getOperand(1), Op1,
6522                                                      Op0BO->getName());
6523             InsertNewInstBefore(YS, I); // (Y << C)
6524             Instruction *X =
6525               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6526                                      Op0BO->getOperand(0)->getName());
6527             InsertNewInstBefore(X, I);  // (X + (Y << C))
6528             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6529             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6530                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6531           }
6532           
6533           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6534           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6535               match(Op0BO->getOperand(0),
6536                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6537                           m_ConstantInt(CC))) && V2 == Op1 &&
6538               cast<BinaryOperator>(Op0BO->getOperand(0))
6539                   ->getOperand(0)->hasOneUse()) {
6540             Instruction *YS = BinaryOperator::CreateShl(
6541                                                      Op0BO->getOperand(1), Op1,
6542                                                      Op0BO->getName());
6543             InsertNewInstBefore(YS, I); // (Y << C)
6544             Instruction *XM =
6545               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6546                                         V1->getName()+".mask");
6547             InsertNewInstBefore(XM, I); // X & (CC << C)
6548             
6549             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6550           }
6551           
6552           break;
6553         }
6554       }
6555       
6556       
6557       // If the operand is an bitwise operator with a constant RHS, and the
6558       // shift is the only use, we can pull it out of the shift.
6559       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6560         bool isValid = true;     // Valid only for And, Or, Xor
6561         bool highBitSet = false; // Transform if high bit of constant set?
6562         
6563         switch (Op0BO->getOpcode()) {
6564           default: isValid = false; break;   // Do not perform transform!
6565           case Instruction::Add:
6566             isValid = isLeftShift;
6567             break;
6568           case Instruction::Or:
6569           case Instruction::Xor:
6570             highBitSet = false;
6571             break;
6572           case Instruction::And:
6573             highBitSet = true;
6574             break;
6575         }
6576         
6577         // If this is a signed shift right, and the high bit is modified
6578         // by the logical operation, do not perform the transformation.
6579         // The highBitSet boolean indicates the value of the high bit of
6580         // the constant which would cause it to be modified for this
6581         // operation.
6582         //
6583         if (isValid && I.getOpcode() == Instruction::AShr)
6584           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6585         
6586         if (isValid) {
6587           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6588           
6589           Instruction *NewShift =
6590             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6591           InsertNewInstBefore(NewShift, I);
6592           NewShift->takeName(Op0BO);
6593           
6594           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6595                                         NewRHS);
6596         }
6597       }
6598     }
6599   }
6600   
6601   // Find out if this is a shift of a shift by a constant.
6602   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6603   if (ShiftOp && !ShiftOp->isShift())
6604     ShiftOp = 0;
6605   
6606   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6607     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6608     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6609     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6610     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6611     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6612     Value *X = ShiftOp->getOperand(0);
6613     
6614     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6615     if (AmtSum > TypeBits)
6616       AmtSum = TypeBits;
6617     
6618     const IntegerType *Ty = cast<IntegerType>(I.getType());
6619     
6620     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6621     if (I.getOpcode() == ShiftOp->getOpcode()) {
6622       return BinaryOperator::Create(I.getOpcode(), X,
6623                                     ConstantInt::get(Ty, AmtSum));
6624     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6625                I.getOpcode() == Instruction::AShr) {
6626       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6627       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6628     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6629                I.getOpcode() == Instruction::LShr) {
6630       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6631       Instruction *Shift =
6632         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6633       InsertNewInstBefore(Shift, I);
6634
6635       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6636       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6637     }
6638     
6639     // Okay, if we get here, one shift must be left, and the other shift must be
6640     // right.  See if the amounts are equal.
6641     if (ShiftAmt1 == ShiftAmt2) {
6642       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6643       if (I.getOpcode() == Instruction::Shl) {
6644         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6645         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6646       }
6647       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6648       if (I.getOpcode() == Instruction::LShr) {
6649         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6650         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6651       }
6652       // We can simplify ((X << C) >>s C) into a trunc + sext.
6653       // NOTE: we could do this for any C, but that would make 'unusual' integer
6654       // types.  For now, just stick to ones well-supported by the code
6655       // generators.
6656       const Type *SExtType = 0;
6657       switch (Ty->getBitWidth() - ShiftAmt1) {
6658       case 1  :
6659       case 8  :
6660       case 16 :
6661       case 32 :
6662       case 64 :
6663       case 128:
6664         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6665         break;
6666       default: break;
6667       }
6668       if (SExtType) {
6669         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6670         InsertNewInstBefore(NewTrunc, I);
6671         return new SExtInst(NewTrunc, Ty);
6672       }
6673       // Otherwise, we can't handle it yet.
6674     } else if (ShiftAmt1 < ShiftAmt2) {
6675       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6676       
6677       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6678       if (I.getOpcode() == Instruction::Shl) {
6679         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6680                ShiftOp->getOpcode() == Instruction::AShr);
6681         Instruction *Shift =
6682           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6683         InsertNewInstBefore(Shift, I);
6684         
6685         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6686         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6687       }
6688       
6689       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6690       if (I.getOpcode() == Instruction::LShr) {
6691         assert(ShiftOp->getOpcode() == Instruction::Shl);
6692         Instruction *Shift =
6693           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6694         InsertNewInstBefore(Shift, I);
6695         
6696         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6697         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6698       }
6699       
6700       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6701     } else {
6702       assert(ShiftAmt2 < ShiftAmt1);
6703       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6704
6705       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6706       if (I.getOpcode() == Instruction::Shl) {
6707         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6708                ShiftOp->getOpcode() == Instruction::AShr);
6709         Instruction *Shift =
6710           BinaryOperator::Create(ShiftOp->getOpcode(), X,
6711                                  ConstantInt::get(Ty, ShiftDiff));
6712         InsertNewInstBefore(Shift, I);
6713         
6714         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6715         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6716       }
6717       
6718       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6719       if (I.getOpcode() == Instruction::LShr) {
6720         assert(ShiftOp->getOpcode() == Instruction::Shl);
6721         Instruction *Shift =
6722           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6723         InsertNewInstBefore(Shift, I);
6724         
6725         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6726         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6727       }
6728       
6729       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6730     }
6731   }
6732   return 0;
6733 }
6734
6735
6736 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6737 /// expression.  If so, decompose it, returning some value X, such that Val is
6738 /// X*Scale+Offset.
6739 ///
6740 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6741                                         int &Offset) {
6742   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6743   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6744     Offset = CI->getZExtValue();
6745     Scale  = 0;
6746     return ConstantInt::get(Type::Int32Ty, 0);
6747   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6748     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6749       if (I->getOpcode() == Instruction::Shl) {
6750         // This is a value scaled by '1 << the shift amt'.
6751         Scale = 1U << RHS->getZExtValue();
6752         Offset = 0;
6753         return I->getOperand(0);
6754       } else if (I->getOpcode() == Instruction::Mul) {
6755         // This value is scaled by 'RHS'.
6756         Scale = RHS->getZExtValue();
6757         Offset = 0;
6758         return I->getOperand(0);
6759       } else if (I->getOpcode() == Instruction::Add) {
6760         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6761         // where C1 is divisible by C2.
6762         unsigned SubScale;
6763         Value *SubVal = 
6764           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6765         Offset += RHS->getZExtValue();
6766         Scale = SubScale;
6767         return SubVal;
6768       }
6769     }
6770   }
6771
6772   // Otherwise, we can't look past this.
6773   Scale = 1;
6774   Offset = 0;
6775   return Val;
6776 }
6777
6778
6779 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6780 /// try to eliminate the cast by moving the type information into the alloc.
6781 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6782                                                    AllocationInst &AI) {
6783   const PointerType *PTy = cast<PointerType>(CI.getType());
6784   
6785   // Remove any uses of AI that are dead.
6786   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6787   
6788   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6789     Instruction *User = cast<Instruction>(*UI++);
6790     if (isInstructionTriviallyDead(User)) {
6791       while (UI != E && *UI == User)
6792         ++UI; // If this instruction uses AI more than once, don't break UI.
6793       
6794       ++NumDeadInst;
6795       DOUT << "IC: DCE: " << *User;
6796       EraseInstFromFunction(*User);
6797     }
6798   }
6799   
6800   // Get the type really allocated and the type casted to.
6801   const Type *AllocElTy = AI.getAllocatedType();
6802   const Type *CastElTy = PTy->getElementType();
6803   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6804
6805   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6806   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6807   if (CastElTyAlign < AllocElTyAlign) return 0;
6808
6809   // If the allocation has multiple uses, only promote it if we are strictly
6810   // increasing the alignment of the resultant allocation.  If we keep it the
6811   // same, we open the door to infinite loops of various kinds.
6812   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6813
6814   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6815   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6816   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6817
6818   // See if we can satisfy the modulus by pulling a scale out of the array
6819   // size argument.
6820   unsigned ArraySizeScale;
6821   int ArrayOffset;
6822   Value *NumElements = // See if the array size is a decomposable linear expr.
6823     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6824  
6825   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6826   // do the xform.
6827   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6828       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6829
6830   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6831   Value *Amt = 0;
6832   if (Scale == 1) {
6833     Amt = NumElements;
6834   } else {
6835     // If the allocation size is constant, form a constant mul expression
6836     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6837     if (isa<ConstantInt>(NumElements))
6838       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6839     // otherwise multiply the amount and the number of elements
6840     else if (Scale != 1) {
6841       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6842       Amt = InsertNewInstBefore(Tmp, AI);
6843     }
6844   }
6845   
6846   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6847     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6848     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6849     Amt = InsertNewInstBefore(Tmp, AI);
6850   }
6851   
6852   AllocationInst *New;
6853   if (isa<MallocInst>(AI))
6854     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6855   else
6856     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6857   InsertNewInstBefore(New, AI);
6858   New->takeName(&AI);
6859   
6860   // If the allocation has multiple uses, insert a cast and change all things
6861   // that used it to use the new cast.  This will also hack on CI, but it will
6862   // die soon.
6863   if (!AI.hasOneUse()) {
6864     AddUsesToWorkList(AI);
6865     // New is the allocation instruction, pointer typed. AI is the original
6866     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6867     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6868     InsertNewInstBefore(NewCast, AI);
6869     AI.replaceAllUsesWith(NewCast);
6870   }
6871   return ReplaceInstUsesWith(CI, New);
6872 }
6873
6874 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6875 /// and return it as type Ty without inserting any new casts and without
6876 /// changing the computed value.  This is used by code that tries to decide
6877 /// whether promoting or shrinking integer operations to wider or smaller types
6878 /// will allow us to eliminate a truncate or extend.
6879 ///
6880 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6881 /// extension operation if Ty is larger.
6882 ///
6883 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
6884 /// should return true if trunc(V) can be computed by computing V in the smaller
6885 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
6886 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6887 /// efficiently truncated.
6888 ///
6889 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6890 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6891 /// the final result.
6892 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6893                                               unsigned CastOpc,
6894                                               int &NumCastsRemoved) {
6895   // We can always evaluate constants in another type.
6896   if (isa<ConstantInt>(V))
6897     return true;
6898   
6899   Instruction *I = dyn_cast<Instruction>(V);
6900   if (!I) return false;
6901   
6902   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6903   
6904   // If this is an extension or truncate, we can often eliminate it.
6905   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6906     // If this is a cast from the destination type, we can trivially eliminate
6907     // it, and this will remove a cast overall.
6908     if (I->getOperand(0)->getType() == Ty) {
6909       // If the first operand is itself a cast, and is eliminable, do not count
6910       // this as an eliminable cast.  We would prefer to eliminate those two
6911       // casts first.
6912       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
6913         ++NumCastsRemoved;
6914       return true;
6915     }
6916   }
6917
6918   // We can't extend or shrink something that has multiple uses: doing so would
6919   // require duplicating the instruction in general, which isn't profitable.
6920   if (!I->hasOneUse()) return false;
6921
6922   switch (I->getOpcode()) {
6923   case Instruction::Add:
6924   case Instruction::Sub:
6925   case Instruction::And:
6926   case Instruction::Or:
6927   case Instruction::Xor:
6928     // These operators can all arbitrarily be extended or truncated.
6929     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6930                                       NumCastsRemoved) &&
6931            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6932                                       NumCastsRemoved);
6933
6934   case Instruction::Mul:
6935     // A multiply can be truncated by truncating its operands.
6936     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
6937            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6938                                       NumCastsRemoved) &&
6939            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6940                                       NumCastsRemoved);
6941
6942   case Instruction::Shl:
6943     // If we are truncating the result of this SHL, and if it's a shift of a
6944     // constant amount, we can always perform a SHL in a smaller type.
6945     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6946       uint32_t BitWidth = Ty->getBitWidth();
6947       if (BitWidth < OrigTy->getBitWidth() && 
6948           CI->getLimitedValue(BitWidth) < BitWidth)
6949         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6950                                           NumCastsRemoved);
6951     }
6952     break;
6953   case Instruction::LShr:
6954     // If this is a truncate of a logical shr, we can truncate it to a smaller
6955     // lshr iff we know that the bits we would otherwise be shifting in are
6956     // already zeros.
6957     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6958       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6959       uint32_t BitWidth = Ty->getBitWidth();
6960       if (BitWidth < OrigBitWidth &&
6961           MaskedValueIsZero(I->getOperand(0),
6962             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6963           CI->getLimitedValue(BitWidth) < BitWidth) {
6964         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6965                                           NumCastsRemoved);
6966       }
6967     }
6968     break;
6969   case Instruction::ZExt:
6970   case Instruction::SExt:
6971   case Instruction::Trunc:
6972     // If this is the same kind of case as our original (e.g. zext+zext), we
6973     // can safely replace it.  Note that replacing it does not reduce the number
6974     // of casts in the input.
6975     if (I->getOpcode() == CastOpc)
6976       return true;
6977     break;
6978       
6979   case Instruction::PHI: {
6980     // We can change a phi if we can change all operands.
6981     PHINode *PN = cast<PHINode>(I);
6982     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
6983       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
6984                                       NumCastsRemoved))
6985         return false;
6986     return true;
6987   }
6988   default:
6989     // TODO: Can handle more cases here.
6990     break;
6991   }
6992   
6993   return false;
6994 }
6995
6996 /// EvaluateInDifferentType - Given an expression that 
6997 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6998 /// evaluate the expression.
6999 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7000                                              bool isSigned) {
7001   if (Constant *C = dyn_cast<Constant>(V))
7002     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7003
7004   // Otherwise, it must be an instruction.
7005   Instruction *I = cast<Instruction>(V);
7006   Instruction *Res = 0;
7007   switch (I->getOpcode()) {
7008   case Instruction::Add:
7009   case Instruction::Sub:
7010   case Instruction::Mul:
7011   case Instruction::And:
7012   case Instruction::Or:
7013   case Instruction::Xor:
7014   case Instruction::AShr:
7015   case Instruction::LShr:
7016   case Instruction::Shl: {
7017     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7018     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7019     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7020                                  LHS, RHS);
7021     break;
7022   }    
7023   case Instruction::Trunc:
7024   case Instruction::ZExt:
7025   case Instruction::SExt:
7026     // If the source type of the cast is the type we're trying for then we can
7027     // just return the source.  There's no need to insert it because it is not
7028     // new.
7029     if (I->getOperand(0)->getType() == Ty)
7030       return I->getOperand(0);
7031     
7032     // Otherwise, must be the same type of cast, so just reinsert a new one.
7033     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7034                            Ty);
7035     break;
7036   case Instruction::PHI: {
7037     PHINode *OPN = cast<PHINode>(I);
7038     PHINode *NPN = PHINode::Create(Ty);
7039     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7040       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7041       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7042     }
7043     Res = NPN;
7044     break;
7045   }
7046   default: 
7047     // TODO: Can handle more cases here.
7048     assert(0 && "Unreachable!");
7049     break;
7050   }
7051   
7052   Res->takeName(I);
7053   return InsertNewInstBefore(Res, *I);
7054 }
7055
7056 /// @brief Implement the transforms common to all CastInst visitors.
7057 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7058   Value *Src = CI.getOperand(0);
7059
7060   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7061   // eliminate it now.
7062   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7063     if (Instruction::CastOps opc = 
7064         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7065       // The first cast (CSrc) is eliminable so we need to fix up or replace
7066       // the second cast (CI). CSrc will then have a good chance of being dead.
7067       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7068     }
7069   }
7070
7071   // If we are casting a select then fold the cast into the select
7072   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7073     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7074       return NV;
7075
7076   // If we are casting a PHI then fold the cast into the PHI
7077   if (isa<PHINode>(Src))
7078     if (Instruction *NV = FoldOpIntoPhi(CI))
7079       return NV;
7080   
7081   return 0;
7082 }
7083
7084 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7085 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7086   Value *Src = CI.getOperand(0);
7087   
7088   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7089     // If casting the result of a getelementptr instruction with no offset, turn
7090     // this into a cast of the original pointer!
7091     if (GEP->hasAllZeroIndices()) {
7092       // Changing the cast operand is usually not a good idea but it is safe
7093       // here because the pointer operand is being replaced with another 
7094       // pointer operand so the opcode doesn't need to change.
7095       AddToWorkList(GEP);
7096       CI.setOperand(0, GEP->getOperand(0));
7097       return &CI;
7098     }
7099     
7100     // If the GEP has a single use, and the base pointer is a bitcast, and the
7101     // GEP computes a constant offset, see if we can convert these three
7102     // instructions into fewer.  This typically happens with unions and other
7103     // non-type-safe code.
7104     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7105       if (GEP->hasAllConstantIndices()) {
7106         // We are guaranteed to get a constant from EmitGEPOffset.
7107         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7108         int64_t Offset = OffsetV->getSExtValue();
7109         
7110         // Get the base pointer input of the bitcast, and the type it points to.
7111         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7112         const Type *GEPIdxTy =
7113           cast<PointerType>(OrigBase->getType())->getElementType();
7114         if (GEPIdxTy->isSized()) {
7115           SmallVector<Value*, 8> NewIndices;
7116           
7117           // Start with the index over the outer type.  Note that the type size
7118           // might be zero (even if the offset isn't zero) if the indexed type
7119           // is something like [0 x {int, int}]
7120           const Type *IntPtrTy = TD->getIntPtrType();
7121           int64_t FirstIdx = 0;
7122           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7123             FirstIdx = Offset/TySize;
7124             Offset %= TySize;
7125           
7126             // Handle silly modulus not returning values values [0..TySize).
7127             if (Offset < 0) {
7128               --FirstIdx;
7129               Offset += TySize;
7130               assert(Offset >= 0);
7131             }
7132             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7133           }
7134           
7135           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7136
7137           // Index into the types.  If we fail, set OrigBase to null.
7138           while (Offset) {
7139             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7140               const StructLayout *SL = TD->getStructLayout(STy);
7141               if (Offset < (int64_t)SL->getSizeInBytes()) {
7142                 unsigned Elt = SL->getElementContainingOffset(Offset);
7143                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7144               
7145                 Offset -= SL->getElementOffset(Elt);
7146                 GEPIdxTy = STy->getElementType(Elt);
7147               } else {
7148                 // Otherwise, we can't index into this, bail out.
7149                 Offset = 0;
7150                 OrigBase = 0;
7151               }
7152             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7153               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7154               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7155                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7156                 Offset %= EltSize;
7157               } else {
7158                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7159               }
7160               GEPIdxTy = STy->getElementType();
7161             } else {
7162               // Otherwise, we can't index into this, bail out.
7163               Offset = 0;
7164               OrigBase = 0;
7165             }
7166           }
7167           if (OrigBase) {
7168             // If we were able to index down into an element, create the GEP
7169             // and bitcast the result.  This eliminates one bitcast, potentially
7170             // two.
7171             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7172                                                           NewIndices.begin(),
7173                                                           NewIndices.end(), "");
7174             InsertNewInstBefore(NGEP, CI);
7175             NGEP->takeName(GEP);
7176             
7177             if (isa<BitCastInst>(CI))
7178               return new BitCastInst(NGEP, CI.getType());
7179             assert(isa<PtrToIntInst>(CI));
7180             return new PtrToIntInst(NGEP, CI.getType());
7181           }
7182         }
7183       }      
7184     }
7185   }
7186     
7187   return commonCastTransforms(CI);
7188 }
7189
7190
7191
7192 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7193 /// integer types. This function implements the common transforms for all those
7194 /// cases.
7195 /// @brief Implement the transforms common to CastInst with integer operands
7196 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7197   if (Instruction *Result = commonCastTransforms(CI))
7198     return Result;
7199
7200   Value *Src = CI.getOperand(0);
7201   const Type *SrcTy = Src->getType();
7202   const Type *DestTy = CI.getType();
7203   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7204   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7205
7206   // See if we can simplify any instructions used by the LHS whose sole 
7207   // purpose is to compute bits we don't care about.
7208   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7209   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7210                            KnownZero, KnownOne))
7211     return &CI;
7212
7213   // If the source isn't an instruction or has more than one use then we
7214   // can't do anything more. 
7215   Instruction *SrcI = dyn_cast<Instruction>(Src);
7216   if (!SrcI || !Src->hasOneUse())
7217     return 0;
7218
7219   // Attempt to propagate the cast into the instruction for int->int casts.
7220   int NumCastsRemoved = 0;
7221   if (!isa<BitCastInst>(CI) &&
7222       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7223                                  CI.getOpcode(), NumCastsRemoved)) {
7224     // If this cast is a truncate, evaluting in a different type always
7225     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7226     // we need to do an AND to maintain the clear top-part of the computation,
7227     // so we require that the input have eliminated at least one cast.  If this
7228     // is a sign extension, we insert two new casts (to do the extension) so we
7229     // require that two casts have been eliminated.
7230     bool DoXForm;
7231     switch (CI.getOpcode()) {
7232     default:
7233       // All the others use floating point so we shouldn't actually 
7234       // get here because of the check above.
7235       assert(0 && "Unknown cast type");
7236     case Instruction::Trunc:
7237       DoXForm = true;
7238       break;
7239     case Instruction::ZExt:
7240       DoXForm = NumCastsRemoved >= 1;
7241       break;
7242     case Instruction::SExt:
7243       DoXForm = NumCastsRemoved >= 2;
7244       break;
7245     }
7246     
7247     if (DoXForm) {
7248       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7249                                            CI.getOpcode() == Instruction::SExt);
7250       assert(Res->getType() == DestTy);
7251       switch (CI.getOpcode()) {
7252       default: assert(0 && "Unknown cast type!");
7253       case Instruction::Trunc:
7254       case Instruction::BitCast:
7255         // Just replace this cast with the result.
7256         return ReplaceInstUsesWith(CI, Res);
7257       case Instruction::ZExt: {
7258         // We need to emit an AND to clear the high bits.
7259         assert(SrcBitSize < DestBitSize && "Not a zext?");
7260         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7261                                                             SrcBitSize));
7262         return BinaryOperator::CreateAnd(Res, C);
7263       }
7264       case Instruction::SExt:
7265         // We need to emit a cast to truncate, then a cast to sext.
7266         return CastInst::Create(Instruction::SExt,
7267             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7268                              CI), DestTy);
7269       }
7270     }
7271   }
7272   
7273   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7274   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7275
7276   switch (SrcI->getOpcode()) {
7277   case Instruction::Add:
7278   case Instruction::Mul:
7279   case Instruction::And:
7280   case Instruction::Or:
7281   case Instruction::Xor:
7282     // If we are discarding information, rewrite.
7283     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7284       // Don't insert two casts if they cannot be eliminated.  We allow 
7285       // two casts to be inserted if the sizes are the same.  This could 
7286       // only be converting signedness, which is a noop.
7287       if (DestBitSize == SrcBitSize || 
7288           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7289           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7290         Instruction::CastOps opcode = CI.getOpcode();
7291         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7292         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7293         return BinaryOperator::Create(
7294             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7295       }
7296     }
7297
7298     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7299     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7300         SrcI->getOpcode() == Instruction::Xor &&
7301         Op1 == ConstantInt::getTrue() &&
7302         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7303       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7304       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7305     }
7306     break;
7307   case Instruction::SDiv:
7308   case Instruction::UDiv:
7309   case Instruction::SRem:
7310   case Instruction::URem:
7311     // If we are just changing the sign, rewrite.
7312     if (DestBitSize == SrcBitSize) {
7313       // Don't insert two casts if they cannot be eliminated.  We allow 
7314       // two casts to be inserted if the sizes are the same.  This could 
7315       // only be converting signedness, which is a noop.
7316       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7317           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7318         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7319                                               Op0, DestTy, SrcI);
7320         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7321                                               Op1, DestTy, SrcI);
7322         return BinaryOperator::Create(
7323           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7324       }
7325     }
7326     break;
7327
7328   case Instruction::Shl:
7329     // Allow changing the sign of the source operand.  Do not allow 
7330     // changing the size of the shift, UNLESS the shift amount is a 
7331     // constant.  We must not change variable sized shifts to a smaller 
7332     // size, because it is undefined to shift more bits out than exist 
7333     // in the value.
7334     if (DestBitSize == SrcBitSize ||
7335         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7336       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7337           Instruction::BitCast : Instruction::Trunc);
7338       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7339       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7340       return BinaryOperator::CreateShl(Op0c, Op1c);
7341     }
7342     break;
7343   case Instruction::AShr:
7344     // If this is a signed shr, and if all bits shifted in are about to be
7345     // truncated off, turn it into an unsigned shr to allow greater
7346     // simplifications.
7347     if (DestBitSize < SrcBitSize &&
7348         isa<ConstantInt>(Op1)) {
7349       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7350       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7351         // Insert the new logical shift right.
7352         return BinaryOperator::CreateLShr(Op0, Op1);
7353       }
7354     }
7355     break;
7356   }
7357   return 0;
7358 }
7359
7360 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7361   if (Instruction *Result = commonIntCastTransforms(CI))
7362     return Result;
7363   
7364   Value *Src = CI.getOperand(0);
7365   const Type *Ty = CI.getType();
7366   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7367   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7368   
7369   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7370     switch (SrcI->getOpcode()) {
7371     default: break;
7372     case Instruction::LShr:
7373       // We can shrink lshr to something smaller if we know the bits shifted in
7374       // are already zeros.
7375       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7376         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7377         
7378         // Get a mask for the bits shifting in.
7379         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7380         Value* SrcIOp0 = SrcI->getOperand(0);
7381         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7382           if (ShAmt >= DestBitWidth)        // All zeros.
7383             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7384
7385           // Okay, we can shrink this.  Truncate the input, then return a new
7386           // shift.
7387           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7388           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7389                                        Ty, CI);
7390           return BinaryOperator::CreateLShr(V1, V2);
7391         }
7392       } else {     // This is a variable shr.
7393         
7394         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7395         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7396         // loop-invariant and CSE'd.
7397         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7398           Value *One = ConstantInt::get(SrcI->getType(), 1);
7399
7400           Value *V = InsertNewInstBefore(
7401               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7402                                      "tmp"), CI);
7403           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7404                                                             SrcI->getOperand(0),
7405                                                             "tmp"), CI);
7406           Value *Zero = Constant::getNullValue(V->getType());
7407           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7408         }
7409       }
7410       break;
7411     }
7412   }
7413   
7414   return 0;
7415 }
7416
7417 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7418 /// in order to eliminate the icmp.
7419 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7420                                              bool DoXform) {
7421   // If we are just checking for a icmp eq of a single bit and zext'ing it
7422   // to an integer, then shift the bit to the appropriate place and then
7423   // cast to integer to avoid the comparison.
7424   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7425     const APInt &Op1CV = Op1C->getValue();
7426       
7427     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7428     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7429     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7430         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7431       if (!DoXform) return ICI;
7432
7433       Value *In = ICI->getOperand(0);
7434       Value *Sh = ConstantInt::get(In->getType(),
7435                                    In->getType()->getPrimitiveSizeInBits()-1);
7436       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7437                                                         In->getName()+".lobit"),
7438                                CI);
7439       if (In->getType() != CI.getType())
7440         In = CastInst::CreateIntegerCast(In, CI.getType(),
7441                                          false/*ZExt*/, "tmp", &CI);
7442
7443       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7444         Constant *One = ConstantInt::get(In->getType(), 1);
7445         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7446                                                          In->getName()+".not"),
7447                                  CI);
7448       }
7449
7450       return ReplaceInstUsesWith(CI, In);
7451     }
7452       
7453       
7454       
7455     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7456     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7457     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7458     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7459     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7460     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7461     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7462     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7463     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7464         // This only works for EQ and NE
7465         ICI->isEquality()) {
7466       // If Op1C some other power of two, convert:
7467       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7468       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7469       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7470       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7471         
7472       APInt KnownZeroMask(~KnownZero);
7473       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7474         if (!DoXform) return ICI;
7475
7476         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7477         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7478           // (X&4) == 2 --> false
7479           // (X&4) != 2 --> true
7480           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7481           Res = ConstantExpr::getZExt(Res, CI.getType());
7482           return ReplaceInstUsesWith(CI, Res);
7483         }
7484           
7485         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7486         Value *In = ICI->getOperand(0);
7487         if (ShiftAmt) {
7488           // Perform a logical shr by shiftamt.
7489           // Insert the shift to put the result in the low bit.
7490           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7491                                   ConstantInt::get(In->getType(), ShiftAmt),
7492                                                    In->getName()+".lobit"), CI);
7493         }
7494           
7495         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7496           Constant *One = ConstantInt::get(In->getType(), 1);
7497           In = BinaryOperator::CreateXor(In, One, "tmp");
7498           InsertNewInstBefore(cast<Instruction>(In), CI);
7499         }
7500           
7501         if (CI.getType() == In->getType())
7502           return ReplaceInstUsesWith(CI, In);
7503         else
7504           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7505       }
7506     }
7507   }
7508
7509   return 0;
7510 }
7511
7512 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7513   // If one of the common conversion will work ..
7514   if (Instruction *Result = commonIntCastTransforms(CI))
7515     return Result;
7516
7517   Value *Src = CI.getOperand(0);
7518
7519   // If this is a cast of a cast
7520   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7521     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7522     // types and if the sizes are just right we can convert this into a logical
7523     // 'and' which will be much cheaper than the pair of casts.
7524     if (isa<TruncInst>(CSrc)) {
7525       // Get the sizes of the types involved
7526       Value *A = CSrc->getOperand(0);
7527       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7528       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7529       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7530       // If we're actually extending zero bits and the trunc is a no-op
7531       if (MidSize < DstSize && SrcSize == DstSize) {
7532         // Replace both of the casts with an And of the type mask.
7533         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7534         Constant *AndConst = ConstantInt::get(AndValue);
7535         Instruction *And = 
7536           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7537         // Unfortunately, if the type changed, we need to cast it back.
7538         if (And->getType() != CI.getType()) {
7539           And->setName(CSrc->getName()+".mask");
7540           InsertNewInstBefore(And, CI);
7541           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7542         }
7543         return And;
7544       }
7545     }
7546   }
7547
7548   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7549     return transformZExtICmp(ICI, CI);
7550
7551   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7552   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7553     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7554     // of the (zext icmp) will be transformed.
7555     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7556     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7557     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7558         (transformZExtICmp(LHS, CI, false) ||
7559          transformZExtICmp(RHS, CI, false))) {
7560       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7561       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7562       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7563     }
7564   }
7565
7566   return 0;
7567 }
7568
7569 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7570   if (Instruction *I = commonIntCastTransforms(CI))
7571     return I;
7572   
7573   Value *Src = CI.getOperand(0);
7574   
7575   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7576   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7577   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7578     // If we are just checking for a icmp eq of a single bit and zext'ing it
7579     // to an integer, then shift the bit to the appropriate place and then
7580     // cast to integer to avoid the comparison.
7581     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7582       const APInt &Op1CV = Op1C->getValue();
7583       
7584       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7585       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7586       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7587           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7588         Value *In = ICI->getOperand(0);
7589         Value *Sh = ConstantInt::get(In->getType(),
7590                                      In->getType()->getPrimitiveSizeInBits()-1);
7591         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7592                                                         In->getName()+".lobit"),
7593                                  CI);
7594         if (In->getType() != CI.getType())
7595           In = CastInst::CreateIntegerCast(In, CI.getType(),
7596                                            true/*SExt*/, "tmp", &CI);
7597         
7598         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7599           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7600                                      In->getName()+".not"), CI);
7601         
7602         return ReplaceInstUsesWith(CI, In);
7603       }
7604     }
7605   }
7606
7607   // See if the value being truncated is already sign extended.  If so, just
7608   // eliminate the trunc/sext pair.
7609   if (getOpcode(Src) == Instruction::Trunc) {
7610     Value *Op = cast<User>(Src)->getOperand(0);
7611     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
7612     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
7613     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7614     unsigned NumSignBits = ComputeNumSignBits(Op);
7615
7616     if (OpBits == DestBits) {
7617       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7618       // bits, it is already ready.
7619       if (NumSignBits > DestBits-MidBits)
7620         return ReplaceInstUsesWith(CI, Op);
7621     } else if (OpBits < DestBits) {
7622       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7623       // bits, just sext from i32.
7624       if (NumSignBits > OpBits-MidBits)
7625         return new SExtInst(Op, CI.getType(), "tmp");
7626     } else {
7627       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7628       // bits, just truncate to i32.
7629       if (NumSignBits > OpBits-MidBits)
7630         return new TruncInst(Op, CI.getType(), "tmp");
7631     }
7632   }
7633       
7634   return 0;
7635 }
7636
7637 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7638 /// in the specified FP type without changing its value.
7639 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7640   APFloat F = CFP->getValueAPF();
7641   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7642     return ConstantFP::get(F);
7643   return 0;
7644 }
7645
7646 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7647 /// through it until we get the source value.
7648 static Value *LookThroughFPExtensions(Value *V) {
7649   if (Instruction *I = dyn_cast<Instruction>(V))
7650     if (I->getOpcode() == Instruction::FPExt)
7651       return LookThroughFPExtensions(I->getOperand(0));
7652   
7653   // If this value is a constant, return the constant in the smallest FP type
7654   // that can accurately represent it.  This allows us to turn
7655   // (float)((double)X+2.0) into x+2.0f.
7656   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7657     if (CFP->getType() == Type::PPC_FP128Ty)
7658       return V;  // No constant folding of this.
7659     // See if the value can be truncated to float and then reextended.
7660     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7661       return V;
7662     if (CFP->getType() == Type::DoubleTy)
7663       return V;  // Won't shrink.
7664     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7665       return V;
7666     // Don't try to shrink to various long double types.
7667   }
7668   
7669   return V;
7670 }
7671
7672 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7673   if (Instruction *I = commonCastTransforms(CI))
7674     return I;
7675   
7676   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7677   // smaller than the destination type, we can eliminate the truncate by doing
7678   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7679   // many builtins (sqrt, etc).
7680   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7681   if (OpI && OpI->hasOneUse()) {
7682     switch (OpI->getOpcode()) {
7683     default: break;
7684     case Instruction::Add:
7685     case Instruction::Sub:
7686     case Instruction::Mul:
7687     case Instruction::FDiv:
7688     case Instruction::FRem:
7689       const Type *SrcTy = OpI->getType();
7690       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7691       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7692       if (LHSTrunc->getType() != SrcTy && 
7693           RHSTrunc->getType() != SrcTy) {
7694         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7695         // If the source types were both smaller than the destination type of
7696         // the cast, do this xform.
7697         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7698             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7699           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7700                                       CI.getType(), CI);
7701           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7702                                       CI.getType(), CI);
7703           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7704         }
7705       }
7706       break;  
7707     }
7708   }
7709   return 0;
7710 }
7711
7712 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7713   return commonCastTransforms(CI);
7714 }
7715
7716 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7717   // fptoui(uitofp(X)) --> X  if the intermediate type has enough bits in its
7718   // mantissa to accurately represent all values of X.  For example, do not
7719   // do this with i64->float->i64.
7720   if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7721     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7722         (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7723                     SrcI->getType()->getFPMantissaWidth())
7724       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7725
7726   return commonCastTransforms(FI);
7727 }
7728
7729 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7730   // fptosi(sitofp(X)) --> X  if the intermediate type has enough bits in its
7731   // mantissa to accurately represent all values of X.  For example, do not
7732   // do this with i64->float->i64.
7733   if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7734     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7735         (int)FI.getType()->getPrimitiveSizeInBits() <= 
7736                     SrcI->getType()->getFPMantissaWidth())
7737       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7738   
7739   return commonCastTransforms(FI);
7740 }
7741
7742 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7743   return commonCastTransforms(CI);
7744 }
7745
7746 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7747   return commonCastTransforms(CI);
7748 }
7749
7750 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7751   return commonPointerCastTransforms(CI);
7752 }
7753
7754 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7755   if (Instruction *I = commonCastTransforms(CI))
7756     return I;
7757   
7758   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7759   if (!DestPointee->isSized()) return 0;
7760
7761   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7762   ConstantInt *Cst;
7763   Value *X;
7764   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7765                                     m_ConstantInt(Cst)))) {
7766     // If the source and destination operands have the same type, see if this
7767     // is a single-index GEP.
7768     if (X->getType() == CI.getType()) {
7769       // Get the size of the pointee type.
7770       uint64_t Size = TD->getABITypeSize(DestPointee);
7771
7772       // Convert the constant to intptr type.
7773       APInt Offset = Cst->getValue();
7774       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7775
7776       // If Offset is evenly divisible by Size, we can do this xform.
7777       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7778         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7779         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7780       }
7781     }
7782     // TODO: Could handle other cases, e.g. where add is indexing into field of
7783     // struct etc.
7784   } else if (CI.getOperand(0)->hasOneUse() &&
7785              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7786     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7787     // "inttoptr+GEP" instead of "add+intptr".
7788     
7789     // Get the size of the pointee type.
7790     uint64_t Size = TD->getABITypeSize(DestPointee);
7791     
7792     // Convert the constant to intptr type.
7793     APInt Offset = Cst->getValue();
7794     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7795     
7796     // If Offset is evenly divisible by Size, we can do this xform.
7797     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7798       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7799       
7800       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7801                                                             "tmp"), CI);
7802       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7803     }
7804   }
7805   return 0;
7806 }
7807
7808 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7809   // If the operands are integer typed then apply the integer transforms,
7810   // otherwise just apply the common ones.
7811   Value *Src = CI.getOperand(0);
7812   const Type *SrcTy = Src->getType();
7813   const Type *DestTy = CI.getType();
7814
7815   if (SrcTy->isInteger() && DestTy->isInteger()) {
7816     if (Instruction *Result = commonIntCastTransforms(CI))
7817       return Result;
7818   } else if (isa<PointerType>(SrcTy)) {
7819     if (Instruction *I = commonPointerCastTransforms(CI))
7820       return I;
7821   } else {
7822     if (Instruction *Result = commonCastTransforms(CI))
7823       return Result;
7824   }
7825
7826
7827   // Get rid of casts from one type to the same type. These are useless and can
7828   // be replaced by the operand.
7829   if (DestTy == Src->getType())
7830     return ReplaceInstUsesWith(CI, Src);
7831
7832   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7833     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7834     const Type *DstElTy = DstPTy->getElementType();
7835     const Type *SrcElTy = SrcPTy->getElementType();
7836     
7837     // If the address spaces don't match, don't eliminate the bitcast, which is
7838     // required for changing types.
7839     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7840       return 0;
7841     
7842     // If we are casting a malloc or alloca to a pointer to a type of the same
7843     // size, rewrite the allocation instruction to allocate the "right" type.
7844     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7845       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7846         return V;
7847     
7848     // If the source and destination are pointers, and this cast is equivalent
7849     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7850     // This can enhance SROA and other transforms that want type-safe pointers.
7851     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7852     unsigned NumZeros = 0;
7853     while (SrcElTy != DstElTy && 
7854            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7855            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7856       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7857       ++NumZeros;
7858     }
7859
7860     // If we found a path from the src to dest, create the getelementptr now.
7861     if (SrcElTy == DstElTy) {
7862       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7863       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
7864                                        ((Instruction*) NULL));
7865     }
7866   }
7867
7868   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7869     if (SVI->hasOneUse()) {
7870       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7871       // a bitconvert to a vector with the same # elts.
7872       if (isa<VectorType>(DestTy) && 
7873           cast<VectorType>(DestTy)->getNumElements() == 
7874                 SVI->getType()->getNumElements()) {
7875         CastInst *Tmp;
7876         // If either of the operands is a cast from CI.getType(), then
7877         // evaluating the shuffle in the casted destination's type will allow
7878         // us to eliminate at least one cast.
7879         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7880              Tmp->getOperand(0)->getType() == DestTy) ||
7881             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7882              Tmp->getOperand(0)->getType() == DestTy)) {
7883           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7884                                                SVI->getOperand(0), DestTy, &CI);
7885           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7886                                                SVI->getOperand(1), DestTy, &CI);
7887           // Return a new shuffle vector.  Use the same element ID's, as we
7888           // know the vector types match #elts.
7889           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7890         }
7891       }
7892     }
7893   }
7894   return 0;
7895 }
7896
7897 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7898 ///   %C = or %A, %B
7899 ///   %D = select %cond, %C, %A
7900 /// into:
7901 ///   %C = select %cond, %B, 0
7902 ///   %D = or %A, %C
7903 ///
7904 /// Assuming that the specified instruction is an operand to the select, return
7905 /// a bitmask indicating which operands of this instruction are foldable if they
7906 /// equal the other incoming value of the select.
7907 ///
7908 static unsigned GetSelectFoldableOperands(Instruction *I) {
7909   switch (I->getOpcode()) {
7910   case Instruction::Add:
7911   case Instruction::Mul:
7912   case Instruction::And:
7913   case Instruction::Or:
7914   case Instruction::Xor:
7915     return 3;              // Can fold through either operand.
7916   case Instruction::Sub:   // Can only fold on the amount subtracted.
7917   case Instruction::Shl:   // Can only fold on the shift amount.
7918   case Instruction::LShr:
7919   case Instruction::AShr:
7920     return 1;
7921   default:
7922     return 0;              // Cannot fold
7923   }
7924 }
7925
7926 /// GetSelectFoldableConstant - For the same transformation as the previous
7927 /// function, return the identity constant that goes into the select.
7928 static Constant *GetSelectFoldableConstant(Instruction *I) {
7929   switch (I->getOpcode()) {
7930   default: assert(0 && "This cannot happen!"); abort();
7931   case Instruction::Add:
7932   case Instruction::Sub:
7933   case Instruction::Or:
7934   case Instruction::Xor:
7935   case Instruction::Shl:
7936   case Instruction::LShr:
7937   case Instruction::AShr:
7938     return Constant::getNullValue(I->getType());
7939   case Instruction::And:
7940     return Constant::getAllOnesValue(I->getType());
7941   case Instruction::Mul:
7942     return ConstantInt::get(I->getType(), 1);
7943   }
7944 }
7945
7946 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7947 /// have the same opcode and only one use each.  Try to simplify this.
7948 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7949                                           Instruction *FI) {
7950   if (TI->getNumOperands() == 1) {
7951     // If this is a non-volatile load or a cast from the same type,
7952     // merge.
7953     if (TI->isCast()) {
7954       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7955         return 0;
7956     } else {
7957       return 0;  // unknown unary op.
7958     }
7959
7960     // Fold this by inserting a select from the input values.
7961     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7962                                            FI->getOperand(0), SI.getName()+".v");
7963     InsertNewInstBefore(NewSI, SI);
7964     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7965                             TI->getType());
7966   }
7967
7968   // Only handle binary operators here.
7969   if (!isa<BinaryOperator>(TI))
7970     return 0;
7971
7972   // Figure out if the operations have any operands in common.
7973   Value *MatchOp, *OtherOpT, *OtherOpF;
7974   bool MatchIsOpZero;
7975   if (TI->getOperand(0) == FI->getOperand(0)) {
7976     MatchOp  = TI->getOperand(0);
7977     OtherOpT = TI->getOperand(1);
7978     OtherOpF = FI->getOperand(1);
7979     MatchIsOpZero = true;
7980   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7981     MatchOp  = TI->getOperand(1);
7982     OtherOpT = TI->getOperand(0);
7983     OtherOpF = FI->getOperand(0);
7984     MatchIsOpZero = false;
7985   } else if (!TI->isCommutative()) {
7986     return 0;
7987   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7988     MatchOp  = TI->getOperand(0);
7989     OtherOpT = TI->getOperand(1);
7990     OtherOpF = FI->getOperand(0);
7991     MatchIsOpZero = true;
7992   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7993     MatchOp  = TI->getOperand(1);
7994     OtherOpT = TI->getOperand(0);
7995     OtherOpF = FI->getOperand(1);
7996     MatchIsOpZero = true;
7997   } else {
7998     return 0;
7999   }
8000
8001   // If we reach here, they do have operations in common.
8002   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8003                                          OtherOpF, SI.getName()+".v");
8004   InsertNewInstBefore(NewSI, SI);
8005
8006   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8007     if (MatchIsOpZero)
8008       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8009     else
8010       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8011   }
8012   assert(0 && "Shouldn't get here");
8013   return 0;
8014 }
8015
8016 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8017   Value *CondVal = SI.getCondition();
8018   Value *TrueVal = SI.getTrueValue();
8019   Value *FalseVal = SI.getFalseValue();
8020
8021   // select true, X, Y  -> X
8022   // select false, X, Y -> Y
8023   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8024     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8025
8026   // select C, X, X -> X
8027   if (TrueVal == FalseVal)
8028     return ReplaceInstUsesWith(SI, TrueVal);
8029
8030   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8031     return ReplaceInstUsesWith(SI, FalseVal);
8032   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8033     return ReplaceInstUsesWith(SI, TrueVal);
8034   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8035     if (isa<Constant>(TrueVal))
8036       return ReplaceInstUsesWith(SI, TrueVal);
8037     else
8038       return ReplaceInstUsesWith(SI, FalseVal);
8039   }
8040
8041   if (SI.getType() == Type::Int1Ty) {
8042     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8043       if (C->getZExtValue()) {
8044         // Change: A = select B, true, C --> A = or B, C
8045         return BinaryOperator::CreateOr(CondVal, FalseVal);
8046       } else {
8047         // Change: A = select B, false, C --> A = and !B, C
8048         Value *NotCond =
8049           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8050                                              "not."+CondVal->getName()), SI);
8051         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8052       }
8053     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8054       if (C->getZExtValue() == false) {
8055         // Change: A = select B, C, false --> A = and B, C
8056         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8057       } else {
8058         // Change: A = select B, C, true --> A = or !B, C
8059         Value *NotCond =
8060           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8061                                              "not."+CondVal->getName()), SI);
8062         return BinaryOperator::CreateOr(NotCond, TrueVal);
8063       }
8064     }
8065     
8066     // select a, b, a  -> a&b
8067     // select a, a, b  -> a|b
8068     if (CondVal == TrueVal)
8069       return BinaryOperator::CreateOr(CondVal, FalseVal);
8070     else if (CondVal == FalseVal)
8071       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8072   }
8073
8074   // Selecting between two integer constants?
8075   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8076     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8077       // select C, 1, 0 -> zext C to int
8078       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8079         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8080       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8081         // select C, 0, 1 -> zext !C to int
8082         Value *NotCond =
8083           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8084                                                "not."+CondVal->getName()), SI);
8085         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8086       }
8087       
8088       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8089
8090       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8091
8092         // (x <s 0) ? -1 : 0 -> ashr x, 31
8093         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8094           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8095             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8096               // The comparison constant and the result are not neccessarily the
8097               // same width. Make an all-ones value by inserting a AShr.
8098               Value *X = IC->getOperand(0);
8099               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8100               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8101               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8102                                                         ShAmt, "ones");
8103               InsertNewInstBefore(SRA, SI);
8104               
8105               // Finally, convert to the type of the select RHS.  We figure out
8106               // if this requires a SExt, Trunc or BitCast based on the sizes.
8107               Instruction::CastOps opc = Instruction::BitCast;
8108               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8109               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8110               if (SRASize < SISize)
8111                 opc = Instruction::SExt;
8112               else if (SRASize > SISize)
8113                 opc = Instruction::Trunc;
8114               return CastInst::Create(opc, SRA, SI.getType());
8115             }
8116           }
8117
8118
8119         // If one of the constants is zero (we know they can't both be) and we
8120         // have an icmp instruction with zero, and we have an 'and' with the
8121         // non-constant value, eliminate this whole mess.  This corresponds to
8122         // cases like this: ((X & 27) ? 27 : 0)
8123         if (TrueValC->isZero() || FalseValC->isZero())
8124           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8125               cast<Constant>(IC->getOperand(1))->isNullValue())
8126             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8127               if (ICA->getOpcode() == Instruction::And &&
8128                   isa<ConstantInt>(ICA->getOperand(1)) &&
8129                   (ICA->getOperand(1) == TrueValC ||
8130                    ICA->getOperand(1) == FalseValC) &&
8131                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8132                 // Okay, now we know that everything is set up, we just don't
8133                 // know whether we have a icmp_ne or icmp_eq and whether the 
8134                 // true or false val is the zero.
8135                 bool ShouldNotVal = !TrueValC->isZero();
8136                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8137                 Value *V = ICA;
8138                 if (ShouldNotVal)
8139                   V = InsertNewInstBefore(BinaryOperator::Create(
8140                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8141                 return ReplaceInstUsesWith(SI, V);
8142               }
8143       }
8144     }
8145
8146   // See if we are selecting two values based on a comparison of the two values.
8147   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8148     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8149       // Transform (X == Y) ? X : Y  -> Y
8150       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8151         // This is not safe in general for floating point:  
8152         // consider X== -0, Y== +0.
8153         // It becomes safe if either operand is a nonzero constant.
8154         ConstantFP *CFPt, *CFPf;
8155         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8156               !CFPt->getValueAPF().isZero()) ||
8157             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8158              !CFPf->getValueAPF().isZero()))
8159         return ReplaceInstUsesWith(SI, FalseVal);
8160       }
8161       // Transform (X != Y) ? X : Y  -> X
8162       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8163         return ReplaceInstUsesWith(SI, TrueVal);
8164       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8165
8166     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8167       // Transform (X == Y) ? Y : X  -> X
8168       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8169         // This is not safe in general for floating point:  
8170         // consider X== -0, Y== +0.
8171         // It becomes safe if either operand is a nonzero constant.
8172         ConstantFP *CFPt, *CFPf;
8173         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8174               !CFPt->getValueAPF().isZero()) ||
8175             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8176              !CFPf->getValueAPF().isZero()))
8177           return ReplaceInstUsesWith(SI, FalseVal);
8178       }
8179       // Transform (X != Y) ? Y : X  -> Y
8180       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8181         return ReplaceInstUsesWith(SI, TrueVal);
8182       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8183     }
8184   }
8185
8186   // See if we are selecting two values based on a comparison of the two values.
8187   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8188     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8189       // Transform (X == Y) ? X : Y  -> Y
8190       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8191         return ReplaceInstUsesWith(SI, FalseVal);
8192       // Transform (X != Y) ? X : Y  -> X
8193       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8194         return ReplaceInstUsesWith(SI, TrueVal);
8195       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8196
8197     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8198       // Transform (X == Y) ? Y : X  -> X
8199       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8200         return ReplaceInstUsesWith(SI, FalseVal);
8201       // Transform (X != Y) ? Y : X  -> Y
8202       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8203         return ReplaceInstUsesWith(SI, TrueVal);
8204       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8205     }
8206   }
8207
8208   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8209     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8210       if (TI->hasOneUse() && FI->hasOneUse()) {
8211         Instruction *AddOp = 0, *SubOp = 0;
8212
8213         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8214         if (TI->getOpcode() == FI->getOpcode())
8215           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8216             return IV;
8217
8218         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8219         // even legal for FP.
8220         if (TI->getOpcode() == Instruction::Sub &&
8221             FI->getOpcode() == Instruction::Add) {
8222           AddOp = FI; SubOp = TI;
8223         } else if (FI->getOpcode() == Instruction::Sub &&
8224                    TI->getOpcode() == Instruction::Add) {
8225           AddOp = TI; SubOp = FI;
8226         }
8227
8228         if (AddOp) {
8229           Value *OtherAddOp = 0;
8230           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8231             OtherAddOp = AddOp->getOperand(1);
8232           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8233             OtherAddOp = AddOp->getOperand(0);
8234           }
8235
8236           if (OtherAddOp) {
8237             // So at this point we know we have (Y -> OtherAddOp):
8238             //        select C, (add X, Y), (sub X, Z)
8239             Value *NegVal;  // Compute -Z
8240             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8241               NegVal = ConstantExpr::getNeg(C);
8242             } else {
8243               NegVal = InsertNewInstBefore(
8244                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8245             }
8246
8247             Value *NewTrueOp = OtherAddOp;
8248             Value *NewFalseOp = NegVal;
8249             if (AddOp != TI)
8250               std::swap(NewTrueOp, NewFalseOp);
8251             Instruction *NewSel =
8252               SelectInst::Create(CondVal, NewTrueOp,
8253                                  NewFalseOp, SI.getName() + ".p");
8254
8255             NewSel = InsertNewInstBefore(NewSel, SI);
8256             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8257           }
8258         }
8259       }
8260
8261   // See if we can fold the select into one of our operands.
8262   if (SI.getType()->isInteger()) {
8263     // See the comment above GetSelectFoldableOperands for a description of the
8264     // transformation we are doing here.
8265     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8266       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8267           !isa<Constant>(FalseVal))
8268         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8269           unsigned OpToFold = 0;
8270           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8271             OpToFold = 1;
8272           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8273             OpToFold = 2;
8274           }
8275
8276           if (OpToFold) {
8277             Constant *C = GetSelectFoldableConstant(TVI);
8278             Instruction *NewSel =
8279               SelectInst::Create(SI.getCondition(),
8280                                  TVI->getOperand(2-OpToFold), C);
8281             InsertNewInstBefore(NewSel, SI);
8282             NewSel->takeName(TVI);
8283             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8284               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8285             else {
8286               assert(0 && "Unknown instruction!!");
8287             }
8288           }
8289         }
8290
8291     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8292       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8293           !isa<Constant>(TrueVal))
8294         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8295           unsigned OpToFold = 0;
8296           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8297             OpToFold = 1;
8298           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8299             OpToFold = 2;
8300           }
8301
8302           if (OpToFold) {
8303             Constant *C = GetSelectFoldableConstant(FVI);
8304             Instruction *NewSel =
8305               SelectInst::Create(SI.getCondition(), C,
8306                                  FVI->getOperand(2-OpToFold));
8307             InsertNewInstBefore(NewSel, SI);
8308             NewSel->takeName(FVI);
8309             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8310               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8311             else
8312               assert(0 && "Unknown instruction!!");
8313           }
8314         }
8315   }
8316
8317   if (BinaryOperator::isNot(CondVal)) {
8318     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8319     SI.setOperand(1, FalseVal);
8320     SI.setOperand(2, TrueVal);
8321     return &SI;
8322   }
8323
8324   return 0;
8325 }
8326
8327 /// EnforceKnownAlignment - If the specified pointer points to an object that
8328 /// we control, modify the object's alignment to PrefAlign. This isn't
8329 /// often possible though. If alignment is important, a more reliable approach
8330 /// is to simply align all global variables and allocation instructions to
8331 /// their preferred alignment from the beginning.
8332 ///
8333 static unsigned EnforceKnownAlignment(Value *V,
8334                                       unsigned Align, unsigned PrefAlign) {
8335
8336   User *U = dyn_cast<User>(V);
8337   if (!U) return Align;
8338
8339   switch (getOpcode(U)) {
8340   default: break;
8341   case Instruction::BitCast:
8342     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8343   case Instruction::GetElementPtr: {
8344     // If all indexes are zero, it is just the alignment of the base pointer.
8345     bool AllZeroOperands = true;
8346     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8347       if (!isa<Constant>(*i) ||
8348           !cast<Constant>(*i)->isNullValue()) {
8349         AllZeroOperands = false;
8350         break;
8351       }
8352
8353     if (AllZeroOperands) {
8354       // Treat this like a bitcast.
8355       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8356     }
8357     break;
8358   }
8359   }
8360
8361   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8362     // If there is a large requested alignment and we can, bump up the alignment
8363     // of the global.
8364     if (!GV->isDeclaration()) {
8365       GV->setAlignment(PrefAlign);
8366       Align = PrefAlign;
8367     }
8368   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8369     // If there is a requested alignment and if this is an alloca, round up.  We
8370     // don't do this for malloc, because some systems can't respect the request.
8371     if (isa<AllocaInst>(AI)) {
8372       AI->setAlignment(PrefAlign);
8373       Align = PrefAlign;
8374     }
8375   }
8376
8377   return Align;
8378 }
8379
8380 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8381 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8382 /// and it is more than the alignment of the ultimate object, see if we can
8383 /// increase the alignment of the ultimate object, making this check succeed.
8384 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8385                                                   unsigned PrefAlign) {
8386   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8387                       sizeof(PrefAlign) * CHAR_BIT;
8388   APInt Mask = APInt::getAllOnesValue(BitWidth);
8389   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8390   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8391   unsigned TrailZ = KnownZero.countTrailingOnes();
8392   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8393
8394   if (PrefAlign > Align)
8395     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8396   
8397     // We don't need to make any adjustment.
8398   return Align;
8399 }
8400
8401 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8402   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8403   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8404   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8405   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8406
8407   if (CopyAlign < MinAlign) {
8408     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8409     return MI;
8410   }
8411   
8412   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8413   // load/store.
8414   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8415   if (MemOpLength == 0) return 0;
8416   
8417   // Source and destination pointer types are always "i8*" for intrinsic.  See
8418   // if the size is something we can handle with a single primitive load/store.
8419   // A single load+store correctly handles overlapping memory in the memmove
8420   // case.
8421   unsigned Size = MemOpLength->getZExtValue();
8422   if (Size == 0) return MI;  // Delete this mem transfer.
8423   
8424   if (Size > 8 || (Size&(Size-1)))
8425     return 0;  // If not 1/2/4/8 bytes, exit.
8426   
8427   // Use an integer load+store unless we can find something better.
8428   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8429   
8430   // Memcpy forces the use of i8* for the source and destination.  That means
8431   // that if you're using memcpy to move one double around, you'll get a cast
8432   // from double* to i8*.  We'd much rather use a double load+store rather than
8433   // an i64 load+store, here because this improves the odds that the source or
8434   // dest address will be promotable.  See if we can find a better type than the
8435   // integer datatype.
8436   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8437     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8438     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8439       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8440       // down through these levels if so.
8441       while (!SrcETy->isSingleValueType()) {
8442         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8443           if (STy->getNumElements() == 1)
8444             SrcETy = STy->getElementType(0);
8445           else
8446             break;
8447         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8448           if (ATy->getNumElements() == 1)
8449             SrcETy = ATy->getElementType();
8450           else
8451             break;
8452         } else
8453           break;
8454       }
8455       
8456       if (SrcETy->isSingleValueType())
8457         NewPtrTy = PointerType::getUnqual(SrcETy);
8458     }
8459   }
8460   
8461   
8462   // If the memcpy/memmove provides better alignment info than we can
8463   // infer, use it.
8464   SrcAlign = std::max(SrcAlign, CopyAlign);
8465   DstAlign = std::max(DstAlign, CopyAlign);
8466   
8467   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8468   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8469   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8470   InsertNewInstBefore(L, *MI);
8471   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8472
8473   // Set the size of the copy to 0, it will be deleted on the next iteration.
8474   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8475   return MI;
8476 }
8477
8478 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8479   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8480   if (MI->getAlignment()->getZExtValue() < Alignment) {
8481     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8482     return MI;
8483   }
8484   
8485   // Extract the length and alignment and fill if they are constant.
8486   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8487   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8488   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8489     return 0;
8490   uint64_t Len = LenC->getZExtValue();
8491   Alignment = MI->getAlignment()->getZExtValue();
8492   
8493   // If the length is zero, this is a no-op
8494   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8495   
8496   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8497   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8498     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
8499     
8500     Value *Dest = MI->getDest();
8501     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8502
8503     // Alignment 0 is identity for alignment 1 for memset, but not store.
8504     if (Alignment == 0) Alignment = 1;
8505     
8506     // Extract the fill value and store.
8507     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8508     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8509                                       Alignment), *MI);
8510     
8511     // Set the size of the copy to 0, it will be deleted on the next iteration.
8512     MI->setLength(Constant::getNullValue(LenC->getType()));
8513     return MI;
8514   }
8515
8516   return 0;
8517 }
8518
8519
8520 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8521 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8522 /// the heavy lifting.
8523 ///
8524 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8525   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8526   if (!II) return visitCallSite(&CI);
8527   
8528   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8529   // visitCallSite.
8530   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8531     bool Changed = false;
8532
8533     // memmove/cpy/set of zero bytes is a noop.
8534     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8535       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8536
8537       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8538         if (CI->getZExtValue() == 1) {
8539           // Replace the instruction with just byte operations.  We would
8540           // transform other cases to loads/stores, but we don't know if
8541           // alignment is sufficient.
8542         }
8543     }
8544
8545     // If we have a memmove and the source operation is a constant global,
8546     // then the source and dest pointers can't alias, so we can change this
8547     // into a call to memcpy.
8548     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8549       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8550         if (GVSrc->isConstant()) {
8551           Module *M = CI.getParent()->getParent()->getParent();
8552           Intrinsic::ID MemCpyID;
8553           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8554             MemCpyID = Intrinsic::memcpy_i32;
8555           else
8556             MemCpyID = Intrinsic::memcpy_i64;
8557           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8558           Changed = true;
8559         }
8560
8561       // memmove(x,x,size) -> noop.
8562       if (MMI->getSource() == MMI->getDest())
8563         return EraseInstFromFunction(CI);
8564     }
8565
8566     // If we can determine a pointer alignment that is bigger than currently
8567     // set, update the alignment.
8568     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8569       if (Instruction *I = SimplifyMemTransfer(MI))
8570         return I;
8571     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8572       if (Instruction *I = SimplifyMemSet(MSI))
8573         return I;
8574     }
8575           
8576     if (Changed) return II;
8577   }
8578   
8579   switch (II->getIntrinsicID()) {
8580   default: break;
8581   case Intrinsic::bswap:
8582     // bswap(bswap(x)) -> x
8583     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8584       if (Operand->getIntrinsicID() == Intrinsic::bswap)
8585         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8586     break;
8587   case Intrinsic::ppc_altivec_lvx:
8588   case Intrinsic::ppc_altivec_lvxl:
8589   case Intrinsic::x86_sse_loadu_ps:
8590   case Intrinsic::x86_sse2_loadu_pd:
8591   case Intrinsic::x86_sse2_loadu_dq:
8592     // Turn PPC lvx     -> load if the pointer is known aligned.
8593     // Turn X86 loadups -> load if the pointer is known aligned.
8594     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8595       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8596                                        PointerType::getUnqual(II->getType()),
8597                                        CI);
8598       return new LoadInst(Ptr);
8599     }
8600     break;
8601   case Intrinsic::ppc_altivec_stvx:
8602   case Intrinsic::ppc_altivec_stvxl:
8603     // Turn stvx -> store if the pointer is known aligned.
8604     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8605       const Type *OpPtrTy = 
8606         PointerType::getUnqual(II->getOperand(1)->getType());
8607       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8608       return new StoreInst(II->getOperand(1), Ptr);
8609     }
8610     break;
8611   case Intrinsic::x86_sse_storeu_ps:
8612   case Intrinsic::x86_sse2_storeu_pd:
8613   case Intrinsic::x86_sse2_storeu_dq:
8614   case Intrinsic::x86_sse2_storel_dq:
8615     // Turn X86 storeu -> store if the pointer is known aligned.
8616     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8617       const Type *OpPtrTy = 
8618         PointerType::getUnqual(II->getOperand(2)->getType());
8619       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8620       return new StoreInst(II->getOperand(2), Ptr);
8621     }
8622     break;
8623     
8624   case Intrinsic::x86_sse_cvttss2si: {
8625     // These intrinsics only demands the 0th element of its input vector.  If
8626     // we can simplify the input based on that, do so now.
8627     uint64_t UndefElts;
8628     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8629                                               UndefElts)) {
8630       II->setOperand(1, V);
8631       return II;
8632     }
8633     break;
8634   }
8635     
8636   case Intrinsic::ppc_altivec_vperm:
8637     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8638     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8639       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8640       
8641       // Check that all of the elements are integer constants or undefs.
8642       bool AllEltsOk = true;
8643       for (unsigned i = 0; i != 16; ++i) {
8644         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8645             !isa<UndefValue>(Mask->getOperand(i))) {
8646           AllEltsOk = false;
8647           break;
8648         }
8649       }
8650       
8651       if (AllEltsOk) {
8652         // Cast the input vectors to byte vectors.
8653         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8654         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8655         Value *Result = UndefValue::get(Op0->getType());
8656         
8657         // Only extract each element once.
8658         Value *ExtractedElts[32];
8659         memset(ExtractedElts, 0, sizeof(ExtractedElts));
8660         
8661         for (unsigned i = 0; i != 16; ++i) {
8662           if (isa<UndefValue>(Mask->getOperand(i)))
8663             continue;
8664           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8665           Idx &= 31;  // Match the hardware behavior.
8666           
8667           if (ExtractedElts[Idx] == 0) {
8668             Instruction *Elt = 
8669               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8670             InsertNewInstBefore(Elt, CI);
8671             ExtractedElts[Idx] = Elt;
8672           }
8673         
8674           // Insert this value into the result vector.
8675           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8676                                              i, "tmp");
8677           InsertNewInstBefore(cast<Instruction>(Result), CI);
8678         }
8679         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8680       }
8681     }
8682     break;
8683
8684   case Intrinsic::stackrestore: {
8685     // If the save is right next to the restore, remove the restore.  This can
8686     // happen when variable allocas are DCE'd.
8687     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8688       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8689         BasicBlock::iterator BI = SS;
8690         if (&*++BI == II)
8691           return EraseInstFromFunction(CI);
8692       }
8693     }
8694     
8695     // Scan down this block to see if there is another stack restore in the
8696     // same block without an intervening call/alloca.
8697     BasicBlock::iterator BI = II;
8698     TerminatorInst *TI = II->getParent()->getTerminator();
8699     bool CannotRemove = false;
8700     for (++BI; &*BI != TI; ++BI) {
8701       if (isa<AllocaInst>(BI)) {
8702         CannotRemove = true;
8703         break;
8704       }
8705       if (isa<CallInst>(BI)) {
8706         if (!isa<IntrinsicInst>(BI)) {
8707           CannotRemove = true;
8708           break;
8709         }
8710         // If there is a stackrestore below this one, remove this one.
8711         return EraseInstFromFunction(CI);
8712       }
8713     }
8714     
8715     // If the stack restore is in a return/unwind block and if there are no
8716     // allocas or calls between the restore and the return, nuke the restore.
8717     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8718       return EraseInstFromFunction(CI);
8719     break;
8720   }
8721   }
8722
8723   return visitCallSite(II);
8724 }
8725
8726 // InvokeInst simplification
8727 //
8728 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8729   return visitCallSite(&II);
8730 }
8731
8732 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
8733 /// passed through the varargs area, we can eliminate the use of the cast.
8734 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8735                                          const CastInst * const CI,
8736                                          const TargetData * const TD,
8737                                          const int ix) {
8738   if (!CI->isLosslessCast())
8739     return false;
8740
8741   // The size of ByVal arguments is derived from the type, so we
8742   // can't change to a type with a different size.  If the size were
8743   // passed explicitly we could avoid this check.
8744   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8745     return true;
8746
8747   const Type* SrcTy = 
8748             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8749   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8750   if (!SrcTy->isSized() || !DstTy->isSized())
8751     return false;
8752   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8753     return false;
8754   return true;
8755 }
8756
8757 // visitCallSite - Improvements for call and invoke instructions.
8758 //
8759 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8760   bool Changed = false;
8761
8762   // If the callee is a constexpr cast of a function, attempt to move the cast
8763   // to the arguments of the call/invoke.
8764   if (transformConstExprCastCall(CS)) return 0;
8765
8766   Value *Callee = CS.getCalledValue();
8767
8768   if (Function *CalleeF = dyn_cast<Function>(Callee))
8769     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8770       Instruction *OldCall = CS.getInstruction();
8771       // If the call and callee calling conventions don't match, this call must
8772       // be unreachable, as the call is undefined.
8773       new StoreInst(ConstantInt::getTrue(),
8774                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8775                                     OldCall);
8776       if (!OldCall->use_empty())
8777         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8778       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8779         return EraseInstFromFunction(*OldCall);
8780       return 0;
8781     }
8782
8783   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8784     // This instruction is not reachable, just remove it.  We insert a store to
8785     // undef so that we know that this code is not reachable, despite the fact
8786     // that we can't modify the CFG here.
8787     new StoreInst(ConstantInt::getTrue(),
8788                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8789                   CS.getInstruction());
8790
8791     if (!CS.getInstruction()->use_empty())
8792       CS.getInstruction()->
8793         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8794
8795     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8796       // Don't break the CFG, insert a dummy cond branch.
8797       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8798                          ConstantInt::getTrue(), II);
8799     }
8800     return EraseInstFromFunction(*CS.getInstruction());
8801   }
8802
8803   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8804     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8805       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8806         return transformCallThroughTrampoline(CS);
8807
8808   const PointerType *PTy = cast<PointerType>(Callee->getType());
8809   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8810   if (FTy->isVarArg()) {
8811     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8812     // See if we can optimize any arguments passed through the varargs area of
8813     // the call.
8814     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8815            E = CS.arg_end(); I != E; ++I, ++ix) {
8816       CastInst *CI = dyn_cast<CastInst>(*I);
8817       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8818         *I = CI->getOperand(0);
8819         Changed = true;
8820       }
8821     }
8822   }
8823
8824   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8825     // Inline asm calls cannot throw - mark them 'nounwind'.
8826     CS.setDoesNotThrow();
8827     Changed = true;
8828   }
8829
8830   return Changed ? CS.getInstruction() : 0;
8831 }
8832
8833 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8834 // attempt to move the cast to the arguments of the call/invoke.
8835 //
8836 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8837   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8838   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8839   if (CE->getOpcode() != Instruction::BitCast || 
8840       !isa<Function>(CE->getOperand(0)))
8841     return false;
8842   Function *Callee = cast<Function>(CE->getOperand(0));
8843   Instruction *Caller = CS.getInstruction();
8844   const PAListPtr &CallerPAL = CS.getParamAttrs();
8845
8846   // Okay, this is a cast from a function to a different type.  Unless doing so
8847   // would cause a type conversion of one of our arguments, change this call to
8848   // be a direct call with arguments casted to the appropriate types.
8849   //
8850   const FunctionType *FT = Callee->getFunctionType();
8851   const Type *OldRetTy = Caller->getType();
8852   const Type *NewRetTy = FT->getReturnType();
8853
8854   if (isa<StructType>(NewRetTy))
8855     return false; // TODO: Handle multiple return values.
8856
8857   // Check to see if we are changing the return type...
8858   if (OldRetTy != NewRetTy) {
8859     if (Callee->isDeclaration() &&
8860         // Conversion is ok if changing from one pointer type to another or from
8861         // a pointer to an integer of the same size.
8862         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8863           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
8864       return false;   // Cannot transform this return value.
8865
8866     if (!Caller->use_empty() &&
8867         // void -> non-void is handled specially
8868         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8869       return false;   // Cannot transform this return value.
8870
8871     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8872       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8873       if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8874         return false;   // Attribute not compatible with transformed value.
8875     }
8876
8877     // If the callsite is an invoke instruction, and the return value is used by
8878     // a PHI node in a successor, we cannot change the return type of the call
8879     // because there is no place to put the cast instruction (without breaking
8880     // the critical edge).  Bail out in this case.
8881     if (!Caller->use_empty())
8882       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8883         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8884              UI != E; ++UI)
8885           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8886             if (PN->getParent() == II->getNormalDest() ||
8887                 PN->getParent() == II->getUnwindDest())
8888               return false;
8889   }
8890
8891   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8892   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8893
8894   CallSite::arg_iterator AI = CS.arg_begin();
8895   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8896     const Type *ParamTy = FT->getParamType(i);
8897     const Type *ActTy = (*AI)->getType();
8898
8899     if (!CastInst::isCastable(ActTy, ParamTy))
8900       return false;   // Cannot transform this parameter value.
8901
8902     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8903       return false;   // Attribute not compatible with transformed value.
8904
8905     // Converting from one pointer type to another or between a pointer and an
8906     // integer of the same size is safe even if we do not have a body.
8907     bool isConvertible = ActTy == ParamTy ||
8908       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8909        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8910     if (Callee->isDeclaration() && !isConvertible) return false;
8911   }
8912
8913   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8914       Callee->isDeclaration())
8915     return false;   // Do not delete arguments unless we have a function body.
8916
8917   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8918       !CallerPAL.isEmpty())
8919     // In this case we have more arguments than the new function type, but we
8920     // won't be dropping them.  Check that these extra arguments have attributes
8921     // that are compatible with being a vararg call argument.
8922     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8923       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8924         break;
8925       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8926       if (PAttrs & ParamAttr::VarArgsIncompatible)
8927         return false;
8928     }
8929
8930   // Okay, we decided that this is a safe thing to do: go ahead and start
8931   // inserting cast instructions as necessary...
8932   std::vector<Value*> Args;
8933   Args.reserve(NumActualArgs);
8934   SmallVector<ParamAttrsWithIndex, 8> attrVec;
8935   attrVec.reserve(NumCommonArgs);
8936
8937   // Get any return attributes.
8938   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8939
8940   // If the return value is not being used, the type may not be compatible
8941   // with the existing attributes.  Wipe out any problematic attributes.
8942   RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
8943
8944   // Add the new return attributes.
8945   if (RAttrs)
8946     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8947
8948   AI = CS.arg_begin();
8949   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8950     const Type *ParamTy = FT->getParamType(i);
8951     if ((*AI)->getType() == ParamTy) {
8952       Args.push_back(*AI);
8953     } else {
8954       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8955           false, ParamTy, false);
8956       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
8957       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8958     }
8959
8960     // Add any parameter attributes.
8961     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8962       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8963   }
8964
8965   // If the function takes more arguments than the call was taking, add them
8966   // now...
8967   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8968     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8969
8970   // If we are removing arguments to the function, emit an obnoxious warning...
8971   if (FT->getNumParams() < NumActualArgs) {
8972     if (!FT->isVarArg()) {
8973       cerr << "WARNING: While resolving call to function '"
8974            << Callee->getName() << "' arguments were dropped!\n";
8975     } else {
8976       // Add all of the arguments in their promoted form to the arg list...
8977       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8978         const Type *PTy = getPromotedType((*AI)->getType());
8979         if (PTy != (*AI)->getType()) {
8980           // Must promote to pass through va_arg area!
8981           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8982                                                                 PTy, false);
8983           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
8984           InsertNewInstBefore(Cast, *Caller);
8985           Args.push_back(Cast);
8986         } else {
8987           Args.push_back(*AI);
8988         }
8989
8990         // Add any parameter attributes.
8991         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8992           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8993       }
8994     }
8995   }
8996
8997   if (NewRetTy == Type::VoidTy)
8998     Caller->setName("");   // Void type should not have a name.
8999
9000   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9001
9002   Instruction *NC;
9003   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9004     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9005                             Args.begin(), Args.end(),
9006                             Caller->getName(), Caller);
9007     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9008     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9009   } else {
9010     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9011                           Caller->getName(), Caller);
9012     CallInst *CI = cast<CallInst>(Caller);
9013     if (CI->isTailCall())
9014       cast<CallInst>(NC)->setTailCall();
9015     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9016     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9017   }
9018
9019   // Insert a cast of the return type as necessary.
9020   Value *NV = NC;
9021   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9022     if (NV->getType() != Type::VoidTy) {
9023       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9024                                                             OldRetTy, false);
9025       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9026
9027       // If this is an invoke instruction, we should insert it after the first
9028       // non-phi, instruction in the normal successor block.
9029       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9030         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9031         InsertNewInstBefore(NC, *I);
9032       } else {
9033         // Otherwise, it's a call, just insert cast right after the call instr
9034         InsertNewInstBefore(NC, *Caller);
9035       }
9036       AddUsersToWorkList(*Caller);
9037     } else {
9038       NV = UndefValue::get(Caller->getType());
9039     }
9040   }
9041
9042   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9043     Caller->replaceAllUsesWith(NV);
9044   Caller->eraseFromParent();
9045   RemoveFromWorkList(Caller);
9046   return true;
9047 }
9048
9049 // transformCallThroughTrampoline - Turn a call to a function created by the
9050 // init_trampoline intrinsic into a direct call to the underlying function.
9051 //
9052 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9053   Value *Callee = CS.getCalledValue();
9054   const PointerType *PTy = cast<PointerType>(Callee->getType());
9055   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9056   const PAListPtr &Attrs = CS.getParamAttrs();
9057
9058   // If the call already has the 'nest' attribute somewhere then give up -
9059   // otherwise 'nest' would occur twice after splicing in the chain.
9060   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9061     return 0;
9062
9063   IntrinsicInst *Tramp =
9064     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9065
9066   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9067   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9068   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9069
9070   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9071   if (!NestAttrs.isEmpty()) {
9072     unsigned NestIdx = 1;
9073     const Type *NestTy = 0;
9074     ParameterAttributes NestAttr = ParamAttr::None;
9075
9076     // Look for a parameter marked with the 'nest' attribute.
9077     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9078          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9079       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9080         // Record the parameter type and any other attributes.
9081         NestTy = *I;
9082         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9083         break;
9084       }
9085
9086     if (NestTy) {
9087       Instruction *Caller = CS.getInstruction();
9088       std::vector<Value*> NewArgs;
9089       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9090
9091       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9092       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9093
9094       // Insert the nest argument into the call argument list, which may
9095       // mean appending it.  Likewise for attributes.
9096
9097       // Add any function result attributes.
9098       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9099         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9100
9101       {
9102         unsigned Idx = 1;
9103         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9104         do {
9105           if (Idx == NestIdx) {
9106             // Add the chain argument and attributes.
9107             Value *NestVal = Tramp->getOperand(3);
9108             if (NestVal->getType() != NestTy)
9109               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9110             NewArgs.push_back(NestVal);
9111             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9112           }
9113
9114           if (I == E)
9115             break;
9116
9117           // Add the original argument and attributes.
9118           NewArgs.push_back(*I);
9119           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9120             NewAttrs.push_back
9121               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9122
9123           ++Idx, ++I;
9124         } while (1);
9125       }
9126
9127       // The trampoline may have been bitcast to a bogus type (FTy).
9128       // Handle this by synthesizing a new function type, equal to FTy
9129       // with the chain parameter inserted.
9130
9131       std::vector<const Type*> NewTypes;
9132       NewTypes.reserve(FTy->getNumParams()+1);
9133
9134       // Insert the chain's type into the list of parameter types, which may
9135       // mean appending it.
9136       {
9137         unsigned Idx = 1;
9138         FunctionType::param_iterator I = FTy->param_begin(),
9139           E = FTy->param_end();
9140
9141         do {
9142           if (Idx == NestIdx)
9143             // Add the chain's type.
9144             NewTypes.push_back(NestTy);
9145
9146           if (I == E)
9147             break;
9148
9149           // Add the original type.
9150           NewTypes.push_back(*I);
9151
9152           ++Idx, ++I;
9153         } while (1);
9154       }
9155
9156       // Replace the trampoline call with a direct call.  Let the generic
9157       // code sort out any function type mismatches.
9158       FunctionType *NewFTy =
9159         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9160       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9161         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9162       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9163
9164       Instruction *NewCaller;
9165       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9166         NewCaller = InvokeInst::Create(NewCallee,
9167                                        II->getNormalDest(), II->getUnwindDest(),
9168                                        NewArgs.begin(), NewArgs.end(),
9169                                        Caller->getName(), Caller);
9170         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9171         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9172       } else {
9173         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9174                                      Caller->getName(), Caller);
9175         if (cast<CallInst>(Caller)->isTailCall())
9176           cast<CallInst>(NewCaller)->setTailCall();
9177         cast<CallInst>(NewCaller)->
9178           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9179         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9180       }
9181       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9182         Caller->replaceAllUsesWith(NewCaller);
9183       Caller->eraseFromParent();
9184       RemoveFromWorkList(Caller);
9185       return 0;
9186     }
9187   }
9188
9189   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9190   // parameter, there is no need to adjust the argument list.  Let the generic
9191   // code sort out any function type mismatches.
9192   Constant *NewCallee =
9193     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9194   CS.setCalledFunction(NewCallee);
9195   return CS.getInstruction();
9196 }
9197
9198 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9199 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9200 /// and a single binop.
9201 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9202   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9203   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9204          isa<CmpInst>(FirstInst));
9205   unsigned Opc = FirstInst->getOpcode();
9206   Value *LHSVal = FirstInst->getOperand(0);
9207   Value *RHSVal = FirstInst->getOperand(1);
9208     
9209   const Type *LHSType = LHSVal->getType();
9210   const Type *RHSType = RHSVal->getType();
9211   
9212   // Scan to see if all operands are the same opcode, all have one use, and all
9213   // kill their operands (i.e. the operands have one use).
9214   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9215     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9216     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9217         // Verify type of the LHS matches so we don't fold cmp's of different
9218         // types or GEP's with different index types.
9219         I->getOperand(0)->getType() != LHSType ||
9220         I->getOperand(1)->getType() != RHSType)
9221       return 0;
9222
9223     // If they are CmpInst instructions, check their predicates
9224     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9225       if (cast<CmpInst>(I)->getPredicate() !=
9226           cast<CmpInst>(FirstInst)->getPredicate())
9227         return 0;
9228     
9229     // Keep track of which operand needs a phi node.
9230     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9231     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9232   }
9233   
9234   // Otherwise, this is safe to transform, determine if it is profitable.
9235
9236   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9237   // Indexes are often folded into load/store instructions, so we don't want to
9238   // hide them behind a phi.
9239   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9240     return 0;
9241   
9242   Value *InLHS = FirstInst->getOperand(0);
9243   Value *InRHS = FirstInst->getOperand(1);
9244   PHINode *NewLHS = 0, *NewRHS = 0;
9245   if (LHSVal == 0) {
9246     NewLHS = PHINode::Create(LHSType,
9247                              FirstInst->getOperand(0)->getName() + ".pn");
9248     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9249     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9250     InsertNewInstBefore(NewLHS, PN);
9251     LHSVal = NewLHS;
9252   }
9253   
9254   if (RHSVal == 0) {
9255     NewRHS = PHINode::Create(RHSType,
9256                              FirstInst->getOperand(1)->getName() + ".pn");
9257     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9258     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9259     InsertNewInstBefore(NewRHS, PN);
9260     RHSVal = NewRHS;
9261   }
9262   
9263   // Add all operands to the new PHIs.
9264   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9265     if (NewLHS) {
9266       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9267       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9268     }
9269     if (NewRHS) {
9270       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9271       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9272     }
9273   }
9274     
9275   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9276     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9277   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9278     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9279                            RHSVal);
9280   else {
9281     assert(isa<GetElementPtrInst>(FirstInst));
9282     return GetElementPtrInst::Create(LHSVal, RHSVal);
9283   }
9284 }
9285
9286 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9287 /// of the block that defines it.  This means that it must be obvious the value
9288 /// of the load is not changed from the point of the load to the end of the
9289 /// block it is in.
9290 ///
9291 /// Finally, it is safe, but not profitable, to sink a load targetting a
9292 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9293 /// to a register.
9294 static bool isSafeToSinkLoad(LoadInst *L) {
9295   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9296   
9297   for (++BBI; BBI != E; ++BBI)
9298     if (BBI->mayWriteToMemory())
9299       return false;
9300   
9301   // Check for non-address taken alloca.  If not address-taken already, it isn't
9302   // profitable to do this xform.
9303   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9304     bool isAddressTaken = false;
9305     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9306          UI != E; ++UI) {
9307       if (isa<LoadInst>(UI)) continue;
9308       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9309         // If storing TO the alloca, then the address isn't taken.
9310         if (SI->getOperand(1) == AI) continue;
9311       }
9312       isAddressTaken = true;
9313       break;
9314     }
9315     
9316     if (!isAddressTaken)
9317       return false;
9318   }
9319   
9320   return true;
9321 }
9322
9323
9324 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9325 // operator and they all are only used by the PHI, PHI together their
9326 // inputs, and do the operation once, to the result of the PHI.
9327 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9328   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9329
9330   // Scan the instruction, looking for input operations that can be folded away.
9331   // If all input operands to the phi are the same instruction (e.g. a cast from
9332   // the same type or "+42") we can pull the operation through the PHI, reducing
9333   // code size and simplifying code.
9334   Constant *ConstantOp = 0;
9335   const Type *CastSrcTy = 0;
9336   bool isVolatile = false;
9337   if (isa<CastInst>(FirstInst)) {
9338     CastSrcTy = FirstInst->getOperand(0)->getType();
9339   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9340     // Can fold binop, compare or shift here if the RHS is a constant, 
9341     // otherwise call FoldPHIArgBinOpIntoPHI.
9342     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9343     if (ConstantOp == 0)
9344       return FoldPHIArgBinOpIntoPHI(PN);
9345   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9346     isVolatile = LI->isVolatile();
9347     // We can't sink the load if the loaded value could be modified between the
9348     // load and the PHI.
9349     if (LI->getParent() != PN.getIncomingBlock(0) ||
9350         !isSafeToSinkLoad(LI))
9351       return 0;
9352   } else if (isa<GetElementPtrInst>(FirstInst)) {
9353     if (FirstInst->getNumOperands() == 2)
9354       return FoldPHIArgBinOpIntoPHI(PN);
9355     // Can't handle general GEPs yet.
9356     return 0;
9357   } else {
9358     return 0;  // Cannot fold this operation.
9359   }
9360
9361   // Check to see if all arguments are the same operation.
9362   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9363     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9364     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9365     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9366       return 0;
9367     if (CastSrcTy) {
9368       if (I->getOperand(0)->getType() != CastSrcTy)
9369         return 0;  // Cast operation must match.
9370     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9371       // We can't sink the load if the loaded value could be modified between 
9372       // the load and the PHI.
9373       if (LI->isVolatile() != isVolatile ||
9374           LI->getParent() != PN.getIncomingBlock(i) ||
9375           !isSafeToSinkLoad(LI))
9376         return 0;
9377       
9378       // If the PHI is volatile and its block has multiple successors, sinking
9379       // it would remove a load of the volatile value from the path through the
9380       // other successor.
9381       if (isVolatile &&
9382           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9383         return 0;
9384
9385       
9386     } else if (I->getOperand(1) != ConstantOp) {
9387       return 0;
9388     }
9389   }
9390
9391   // Okay, they are all the same operation.  Create a new PHI node of the
9392   // correct type, and PHI together all of the LHS's of the instructions.
9393   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9394                                    PN.getName()+".in");
9395   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9396
9397   Value *InVal = FirstInst->getOperand(0);
9398   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9399
9400   // Add all operands to the new PHI.
9401   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9402     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9403     if (NewInVal != InVal)
9404       InVal = 0;
9405     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9406   }
9407
9408   Value *PhiVal;
9409   if (InVal) {
9410     // The new PHI unions all of the same values together.  This is really
9411     // common, so we handle it intelligently here for compile-time speed.
9412     PhiVal = InVal;
9413     delete NewPN;
9414   } else {
9415     InsertNewInstBefore(NewPN, PN);
9416     PhiVal = NewPN;
9417   }
9418
9419   // Insert and return the new operation.
9420   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9421     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9422   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9423     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9424   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9425     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9426                            PhiVal, ConstantOp);
9427   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9428   
9429   // If this was a volatile load that we are merging, make sure to loop through
9430   // and mark all the input loads as non-volatile.  If we don't do this, we will
9431   // insert a new volatile load and the old ones will not be deletable.
9432   if (isVolatile)
9433     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9434       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9435   
9436   return new LoadInst(PhiVal, "", isVolatile);
9437 }
9438
9439 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9440 /// that is dead.
9441 static bool DeadPHICycle(PHINode *PN,
9442                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9443   if (PN->use_empty()) return true;
9444   if (!PN->hasOneUse()) return false;
9445
9446   // Remember this node, and if we find the cycle, return.
9447   if (!PotentiallyDeadPHIs.insert(PN))
9448     return true;
9449   
9450   // Don't scan crazily complex things.
9451   if (PotentiallyDeadPHIs.size() == 16)
9452     return false;
9453
9454   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9455     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9456
9457   return false;
9458 }
9459
9460 /// PHIsEqualValue - Return true if this phi node is always equal to
9461 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9462 ///   z = some value; x = phi (y, z); y = phi (x, z)
9463 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9464                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9465   // See if we already saw this PHI node.
9466   if (!ValueEqualPHIs.insert(PN))
9467     return true;
9468   
9469   // Don't scan crazily complex things.
9470   if (ValueEqualPHIs.size() == 16)
9471     return false;
9472  
9473   // Scan the operands to see if they are either phi nodes or are equal to
9474   // the value.
9475   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9476     Value *Op = PN->getIncomingValue(i);
9477     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9478       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9479         return false;
9480     } else if (Op != NonPhiInVal)
9481       return false;
9482   }
9483   
9484   return true;
9485 }
9486
9487
9488 // PHINode simplification
9489 //
9490 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9491   // If LCSSA is around, don't mess with Phi nodes
9492   if (MustPreserveLCSSA) return 0;
9493   
9494   if (Value *V = PN.hasConstantValue())
9495     return ReplaceInstUsesWith(PN, V);
9496
9497   // If all PHI operands are the same operation, pull them through the PHI,
9498   // reducing code size.
9499   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9500       PN.getIncomingValue(0)->hasOneUse())
9501     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9502       return Result;
9503
9504   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9505   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9506   // PHI)... break the cycle.
9507   if (PN.hasOneUse()) {
9508     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9509     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9510       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9511       PotentiallyDeadPHIs.insert(&PN);
9512       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9513         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9514     }
9515    
9516     // If this phi has a single use, and if that use just computes a value for
9517     // the next iteration of a loop, delete the phi.  This occurs with unused
9518     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9519     // common case here is good because the only other things that catch this
9520     // are induction variable analysis (sometimes) and ADCE, which is only run
9521     // late.
9522     if (PHIUser->hasOneUse() &&
9523         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9524         PHIUser->use_back() == &PN) {
9525       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9526     }
9527   }
9528
9529   // We sometimes end up with phi cycles that non-obviously end up being the
9530   // same value, for example:
9531   //   z = some value; x = phi (y, z); y = phi (x, z)
9532   // where the phi nodes don't necessarily need to be in the same block.  Do a
9533   // quick check to see if the PHI node only contains a single non-phi value, if
9534   // so, scan to see if the phi cycle is actually equal to that value.
9535   {
9536     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9537     // Scan for the first non-phi operand.
9538     while (InValNo != NumOperandVals && 
9539            isa<PHINode>(PN.getIncomingValue(InValNo)))
9540       ++InValNo;
9541
9542     if (InValNo != NumOperandVals) {
9543       Value *NonPhiInVal = PN.getOperand(InValNo);
9544       
9545       // Scan the rest of the operands to see if there are any conflicts, if so
9546       // there is no need to recursively scan other phis.
9547       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9548         Value *OpVal = PN.getIncomingValue(InValNo);
9549         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9550           break;
9551       }
9552       
9553       // If we scanned over all operands, then we have one unique value plus
9554       // phi values.  Scan PHI nodes to see if they all merge in each other or
9555       // the value.
9556       if (InValNo == NumOperandVals) {
9557         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9558         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9559           return ReplaceInstUsesWith(PN, NonPhiInVal);
9560       }
9561     }
9562   }
9563   return 0;
9564 }
9565
9566 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9567                                    Instruction *InsertPoint,
9568                                    InstCombiner *IC) {
9569   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9570   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9571   // We must cast correctly to the pointer type. Ensure that we
9572   // sign extend the integer value if it is smaller as this is
9573   // used for address computation.
9574   Instruction::CastOps opcode = 
9575      (VTySize < PtrSize ? Instruction::SExt :
9576       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9577   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9578 }
9579
9580
9581 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9582   Value *PtrOp = GEP.getOperand(0);
9583   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9584   // If so, eliminate the noop.
9585   if (GEP.getNumOperands() == 1)
9586     return ReplaceInstUsesWith(GEP, PtrOp);
9587
9588   if (isa<UndefValue>(GEP.getOperand(0)))
9589     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9590
9591   bool HasZeroPointerIndex = false;
9592   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9593     HasZeroPointerIndex = C->isNullValue();
9594
9595   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9596     return ReplaceInstUsesWith(GEP, PtrOp);
9597
9598   // Eliminate unneeded casts for indices.
9599   bool MadeChange = false;
9600   
9601   gep_type_iterator GTI = gep_type_begin(GEP);
9602   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9603        i != e; ++i, ++GTI) {
9604     if (isa<SequentialType>(*GTI)) {
9605       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9606         if (CI->getOpcode() == Instruction::ZExt ||
9607             CI->getOpcode() == Instruction::SExt) {
9608           const Type *SrcTy = CI->getOperand(0)->getType();
9609           // We can eliminate a cast from i32 to i64 iff the target 
9610           // is a 32-bit pointer target.
9611           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9612             MadeChange = true;
9613             *i = CI->getOperand(0);
9614           }
9615         }
9616       }
9617       // If we are using a wider index than needed for this platform, shrink it
9618       // to what we need.  If the incoming value needs a cast instruction,
9619       // insert it.  This explicit cast can make subsequent optimizations more
9620       // obvious.
9621       Value *Op = *i;
9622       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9623         if (Constant *C = dyn_cast<Constant>(Op)) {
9624           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9625           MadeChange = true;
9626         } else {
9627           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9628                                 GEP);
9629           *i = Op;
9630           MadeChange = true;
9631         }
9632       }
9633     }
9634   }
9635   if (MadeChange) return &GEP;
9636
9637   // If this GEP instruction doesn't move the pointer, and if the input operand
9638   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9639   // real input to the dest type.
9640   if (GEP.hasAllZeroIndices()) {
9641     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9642       // If the bitcast is of an allocation, and the allocation will be
9643       // converted to match the type of the cast, don't touch this.
9644       if (isa<AllocationInst>(BCI->getOperand(0))) {
9645         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9646         if (Instruction *I = visitBitCast(*BCI)) {
9647           if (I != BCI) {
9648             I->takeName(BCI);
9649             BCI->getParent()->getInstList().insert(BCI, I);
9650             ReplaceInstUsesWith(*BCI, I);
9651           }
9652           return &GEP;
9653         }
9654       }
9655       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9656     }
9657   }
9658   
9659   // Combine Indices - If the source pointer to this getelementptr instruction
9660   // is a getelementptr instruction, combine the indices of the two
9661   // getelementptr instructions into a single instruction.
9662   //
9663   SmallVector<Value*, 8> SrcGEPOperands;
9664   if (User *Src = dyn_castGetElementPtr(PtrOp))
9665     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9666
9667   if (!SrcGEPOperands.empty()) {
9668     // Note that if our source is a gep chain itself that we wait for that
9669     // chain to be resolved before we perform this transformation.  This
9670     // avoids us creating a TON of code in some cases.
9671     //
9672     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9673         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9674       return 0;   // Wait until our source is folded to completion.
9675
9676     SmallVector<Value*, 8> Indices;
9677
9678     // Find out whether the last index in the source GEP is a sequential idx.
9679     bool EndsWithSequential = false;
9680     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9681            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9682       EndsWithSequential = !isa<StructType>(*I);
9683
9684     // Can we combine the two pointer arithmetics offsets?
9685     if (EndsWithSequential) {
9686       // Replace: gep (gep %P, long B), long A, ...
9687       // With:    T = long A+B; gep %P, T, ...
9688       //
9689       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9690       if (SO1 == Constant::getNullValue(SO1->getType())) {
9691         Sum = GO1;
9692       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9693         Sum = SO1;
9694       } else {
9695         // If they aren't the same type, convert both to an integer of the
9696         // target's pointer size.
9697         if (SO1->getType() != GO1->getType()) {
9698           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9699             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9700           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9701             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9702           } else {
9703             unsigned PS = TD->getPointerSizeInBits();
9704             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9705               // Convert GO1 to SO1's type.
9706               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9707
9708             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9709               // Convert SO1 to GO1's type.
9710               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9711             } else {
9712               const Type *PT = TD->getIntPtrType();
9713               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9714               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9715             }
9716           }
9717         }
9718         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9719           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9720         else {
9721           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9722           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9723         }
9724       }
9725
9726       // Recycle the GEP we already have if possible.
9727       if (SrcGEPOperands.size() == 2) {
9728         GEP.setOperand(0, SrcGEPOperands[0]);
9729         GEP.setOperand(1, Sum);
9730         return &GEP;
9731       } else {
9732         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9733                        SrcGEPOperands.end()-1);
9734         Indices.push_back(Sum);
9735         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9736       }
9737     } else if (isa<Constant>(*GEP.idx_begin()) &&
9738                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9739                SrcGEPOperands.size() != 1) {
9740       // Otherwise we can do the fold if the first index of the GEP is a zero
9741       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9742                      SrcGEPOperands.end());
9743       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9744     }
9745
9746     if (!Indices.empty())
9747       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9748                                        Indices.end(), GEP.getName());
9749
9750   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9751     // GEP of global variable.  If all of the indices for this GEP are
9752     // constants, we can promote this to a constexpr instead of an instruction.
9753
9754     // Scan for nonconstants...
9755     SmallVector<Constant*, 8> Indices;
9756     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9757     for (; I != E && isa<Constant>(*I); ++I)
9758       Indices.push_back(cast<Constant>(*I));
9759
9760     if (I == E) {  // If they are all constants...
9761       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9762                                                     &Indices[0],Indices.size());
9763
9764       // Replace all uses of the GEP with the new constexpr...
9765       return ReplaceInstUsesWith(GEP, CE);
9766     }
9767   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9768     if (!isa<PointerType>(X->getType())) {
9769       // Not interesting.  Source pointer must be a cast from pointer.
9770     } else if (HasZeroPointerIndex) {
9771       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9772       // into     : GEP [10 x i8]* X, i32 0, ...
9773       //
9774       // This occurs when the program declares an array extern like "int X[];"
9775       //
9776       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9777       const PointerType *XTy = cast<PointerType>(X->getType());
9778       if (const ArrayType *XATy =
9779           dyn_cast<ArrayType>(XTy->getElementType()))
9780         if (const ArrayType *CATy =
9781             dyn_cast<ArrayType>(CPTy->getElementType()))
9782           if (CATy->getElementType() == XATy->getElementType()) {
9783             // At this point, we know that the cast source type is a pointer
9784             // to an array of the same type as the destination pointer
9785             // array.  Because the array type is never stepped over (there
9786             // is a leading zero) we can fold the cast into this GEP.
9787             GEP.setOperand(0, X);
9788             return &GEP;
9789           }
9790     } else if (GEP.getNumOperands() == 2) {
9791       // Transform things like:
9792       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9793       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9794       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9795       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9796       if (isa<ArrayType>(SrcElTy) &&
9797           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9798           TD->getABITypeSize(ResElTy)) {
9799         Value *Idx[2];
9800         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9801         Idx[1] = GEP.getOperand(1);
9802         Value *V = InsertNewInstBefore(
9803                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9804         // V and GEP are both pointer types --> BitCast
9805         return new BitCastInst(V, GEP.getType());
9806       }
9807       
9808       // Transform things like:
9809       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9810       //   (where tmp = 8*tmp2) into:
9811       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9812       
9813       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9814         uint64_t ArrayEltSize =
9815             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9816         
9817         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9818         // allow either a mul, shift, or constant here.
9819         Value *NewIdx = 0;
9820         ConstantInt *Scale = 0;
9821         if (ArrayEltSize == 1) {
9822           NewIdx = GEP.getOperand(1);
9823           Scale = ConstantInt::get(NewIdx->getType(), 1);
9824         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9825           NewIdx = ConstantInt::get(CI->getType(), 1);
9826           Scale = CI;
9827         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9828           if (Inst->getOpcode() == Instruction::Shl &&
9829               isa<ConstantInt>(Inst->getOperand(1))) {
9830             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9831             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9832             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9833             NewIdx = Inst->getOperand(0);
9834           } else if (Inst->getOpcode() == Instruction::Mul &&
9835                      isa<ConstantInt>(Inst->getOperand(1))) {
9836             Scale = cast<ConstantInt>(Inst->getOperand(1));
9837             NewIdx = Inst->getOperand(0);
9838           }
9839         }
9840         
9841         // If the index will be to exactly the right offset with the scale taken
9842         // out, perform the transformation. Note, we don't know whether Scale is
9843         // signed or not. We'll use unsigned version of division/modulo
9844         // operation after making sure Scale doesn't have the sign bit set.
9845         if (Scale && Scale->getSExtValue() >= 0LL &&
9846             Scale->getZExtValue() % ArrayEltSize == 0) {
9847           Scale = ConstantInt::get(Scale->getType(),
9848                                    Scale->getZExtValue() / ArrayEltSize);
9849           if (Scale->getZExtValue() != 1) {
9850             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9851                                                        false /*ZExt*/);
9852             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9853             NewIdx = InsertNewInstBefore(Sc, GEP);
9854           }
9855
9856           // Insert the new GEP instruction.
9857           Value *Idx[2];
9858           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9859           Idx[1] = NewIdx;
9860           Instruction *NewGEP =
9861             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9862           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9863           // The NewGEP must be pointer typed, so must the old one -> BitCast
9864           return new BitCastInst(NewGEP, GEP.getType());
9865         }
9866       }
9867     }
9868   }
9869
9870   return 0;
9871 }
9872
9873 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9874   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9875   if (AI.isArrayAllocation()) {  // Check C != 1
9876     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9877       const Type *NewTy = 
9878         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9879       AllocationInst *New = 0;
9880
9881       // Create and insert the replacement instruction...
9882       if (isa<MallocInst>(AI))
9883         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9884       else {
9885         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9886         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9887       }
9888
9889       InsertNewInstBefore(New, AI);
9890
9891       // Scan to the end of the allocation instructions, to skip over a block of
9892       // allocas if possible...
9893       //
9894       BasicBlock::iterator It = New;
9895       while (isa<AllocationInst>(*It)) ++It;
9896
9897       // Now that I is pointing to the first non-allocation-inst in the block,
9898       // insert our getelementptr instruction...
9899       //
9900       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9901       Value *Idx[2];
9902       Idx[0] = NullIdx;
9903       Idx[1] = NullIdx;
9904       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9905                                            New->getName()+".sub", It);
9906
9907       // Now make everything use the getelementptr instead of the original
9908       // allocation.
9909       return ReplaceInstUsesWith(AI, V);
9910     } else if (isa<UndefValue>(AI.getArraySize())) {
9911       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9912     }
9913   }
9914
9915   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9916   // Note that we only do this for alloca's, because malloc should allocate and
9917   // return a unique pointer, even for a zero byte allocation.
9918   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9919       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9920     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9921
9922   return 0;
9923 }
9924
9925 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9926   Value *Op = FI.getOperand(0);
9927
9928   // free undef -> unreachable.
9929   if (isa<UndefValue>(Op)) {
9930     // Insert a new store to null because we cannot modify the CFG here.
9931     new StoreInst(ConstantInt::getTrue(),
9932                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9933     return EraseInstFromFunction(FI);
9934   }
9935   
9936   // If we have 'free null' delete the instruction.  This can happen in stl code
9937   // when lots of inlining happens.
9938   if (isa<ConstantPointerNull>(Op))
9939     return EraseInstFromFunction(FI);
9940   
9941   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9942   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9943     FI.setOperand(0, CI->getOperand(0));
9944     return &FI;
9945   }
9946   
9947   // Change free (gep X, 0,0,0,0) into free(X)
9948   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9949     if (GEPI->hasAllZeroIndices()) {
9950       AddToWorkList(GEPI);
9951       FI.setOperand(0, GEPI->getOperand(0));
9952       return &FI;
9953     }
9954   }
9955   
9956   // Change free(malloc) into nothing, if the malloc has a single use.
9957   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9958     if (MI->hasOneUse()) {
9959       EraseInstFromFunction(FI);
9960       return EraseInstFromFunction(*MI);
9961     }
9962
9963   return 0;
9964 }
9965
9966
9967 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9968 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9969                                         const TargetData *TD) {
9970   User *CI = cast<User>(LI.getOperand(0));
9971   Value *CastOp = CI->getOperand(0);
9972
9973   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9974     // Instead of loading constant c string, use corresponding integer value
9975     // directly if string length is small enough.
9976     const std::string &Str = CE->getOperand(0)->getStringValue();
9977     if (!Str.empty()) {
9978       unsigned len = Str.length();
9979       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9980       unsigned numBits = Ty->getPrimitiveSizeInBits();
9981       // Replace LI with immediate integer store.
9982       if ((numBits >> 3) == len + 1) {
9983         APInt StrVal(numBits, 0);
9984         APInt SingleChar(numBits, 0);
9985         if (TD->isLittleEndian()) {
9986           for (signed i = len-1; i >= 0; i--) {
9987             SingleChar = (uint64_t) Str[i];
9988             StrVal = (StrVal << 8) | SingleChar;
9989           }
9990         } else {
9991           for (unsigned i = 0; i < len; i++) {
9992             SingleChar = (uint64_t) Str[i];
9993             StrVal = (StrVal << 8) | SingleChar;
9994           }
9995           // Append NULL at the end.
9996           SingleChar = 0;
9997           StrVal = (StrVal << 8) | SingleChar;
9998         }
9999         Value *NL = ConstantInt::get(StrVal);
10000         return IC.ReplaceInstUsesWith(LI, NL);
10001       }
10002     }
10003   }
10004
10005   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10006   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10007     const Type *SrcPTy = SrcTy->getElementType();
10008
10009     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10010          isa<VectorType>(DestPTy)) {
10011       // If the source is an array, the code below will not succeed.  Check to
10012       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10013       // constants.
10014       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10015         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10016           if (ASrcTy->getNumElements() != 0) {
10017             Value *Idxs[2];
10018             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10019             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10020             SrcTy = cast<PointerType>(CastOp->getType());
10021             SrcPTy = SrcTy->getElementType();
10022           }
10023
10024       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10025             isa<VectorType>(SrcPTy)) &&
10026           // Do not allow turning this into a load of an integer, which is then
10027           // casted to a pointer, this pessimizes pointer analysis a lot.
10028           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10029           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10030                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10031
10032         // Okay, we are casting from one integer or pointer type to another of
10033         // the same size.  Instead of casting the pointer before the load, cast
10034         // the result of the loaded value.
10035         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10036                                                              CI->getName(),
10037                                                          LI.isVolatile()),LI);
10038         // Now cast the result of the load.
10039         return new BitCastInst(NewLoad, LI.getType());
10040       }
10041     }
10042   }
10043   return 0;
10044 }
10045
10046 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10047 /// from this value cannot trap.  If it is not obviously safe to load from the
10048 /// specified pointer, we do a quick local scan of the basic block containing
10049 /// ScanFrom, to determine if the address is already accessed.
10050 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10051   // If it is an alloca it is always safe to load from.
10052   if (isa<AllocaInst>(V)) return true;
10053
10054   // If it is a global variable it is mostly safe to load from.
10055   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10056     // Don't try to evaluate aliases.  External weak GV can be null.
10057     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10058
10059   // Otherwise, be a little bit agressive by scanning the local block where we
10060   // want to check to see if the pointer is already being loaded or stored
10061   // from/to.  If so, the previous load or store would have already trapped,
10062   // so there is no harm doing an extra load (also, CSE will later eliminate
10063   // the load entirely).
10064   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10065
10066   while (BBI != E) {
10067     --BBI;
10068
10069     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10070       if (LI->getOperand(0) == V) return true;
10071     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10072       if (SI->getOperand(1) == V) return true;
10073
10074   }
10075   return false;
10076 }
10077
10078 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10079 /// until we find the underlying object a pointer is referring to or something
10080 /// we don't understand.  Note that the returned pointer may be offset from the
10081 /// input, because we ignore GEP indices.
10082 static Value *GetUnderlyingObject(Value *Ptr) {
10083   while (1) {
10084     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10085       if (CE->getOpcode() == Instruction::BitCast ||
10086           CE->getOpcode() == Instruction::GetElementPtr)
10087         Ptr = CE->getOperand(0);
10088       else
10089         return Ptr;
10090     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10091       Ptr = BCI->getOperand(0);
10092     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10093       Ptr = GEP->getOperand(0);
10094     } else {
10095       return Ptr;
10096     }
10097   }
10098 }
10099
10100 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10101   Value *Op = LI.getOperand(0);
10102
10103   // Attempt to improve the alignment.
10104   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10105   if (KnownAlign >
10106       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10107                                 LI.getAlignment()))
10108     LI.setAlignment(KnownAlign);
10109
10110   // load (cast X) --> cast (load X) iff safe
10111   if (isa<CastInst>(Op))
10112     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10113       return Res;
10114
10115   // None of the following transforms are legal for volatile loads.
10116   if (LI.isVolatile()) return 0;
10117   
10118   if (&LI.getParent()->front() != &LI) {
10119     BasicBlock::iterator BBI = &LI; --BBI;
10120     // If the instruction immediately before this is a store to the same
10121     // address, do a simple form of store->load forwarding.
10122     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10123       if (SI->getOperand(1) == LI.getOperand(0))
10124         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10125     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10126       if (LIB->getOperand(0) == LI.getOperand(0))
10127         return ReplaceInstUsesWith(LI, LIB);
10128   }
10129
10130   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10131     const Value *GEPI0 = GEPI->getOperand(0);
10132     // TODO: Consider a target hook for valid address spaces for this xform.
10133     if (isa<ConstantPointerNull>(GEPI0) &&
10134         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10135       // Insert a new store to null instruction before the load to indicate
10136       // that this code is not reachable.  We do this instead of inserting
10137       // an unreachable instruction directly because we cannot modify the
10138       // CFG.
10139       new StoreInst(UndefValue::get(LI.getType()),
10140                     Constant::getNullValue(Op->getType()), &LI);
10141       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10142     }
10143   } 
10144
10145   if (Constant *C = dyn_cast<Constant>(Op)) {
10146     // load null/undef -> undef
10147     // TODO: Consider a target hook for valid address spaces for this xform.
10148     if (isa<UndefValue>(C) || (C->isNullValue() && 
10149         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10150       // Insert a new store to null instruction before the load to indicate that
10151       // this code is not reachable.  We do this instead of inserting an
10152       // unreachable instruction directly because we cannot modify the CFG.
10153       new StoreInst(UndefValue::get(LI.getType()),
10154                     Constant::getNullValue(Op->getType()), &LI);
10155       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10156     }
10157
10158     // Instcombine load (constant global) into the value loaded.
10159     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10160       if (GV->isConstant() && !GV->isDeclaration())
10161         return ReplaceInstUsesWith(LI, GV->getInitializer());
10162
10163     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10164     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10165       if (CE->getOpcode() == Instruction::GetElementPtr) {
10166         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10167           if (GV->isConstant() && !GV->isDeclaration())
10168             if (Constant *V = 
10169                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10170               return ReplaceInstUsesWith(LI, V);
10171         if (CE->getOperand(0)->isNullValue()) {
10172           // Insert a new store to null instruction before the load to indicate
10173           // that this code is not reachable.  We do this instead of inserting
10174           // an unreachable instruction directly because we cannot modify the
10175           // CFG.
10176           new StoreInst(UndefValue::get(LI.getType()),
10177                         Constant::getNullValue(Op->getType()), &LI);
10178           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10179         }
10180
10181       } else if (CE->isCast()) {
10182         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10183           return Res;
10184       }
10185     }
10186   }
10187     
10188   // If this load comes from anywhere in a constant global, and if the global
10189   // is all undef or zero, we know what it loads.
10190   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10191     if (GV->isConstant() && GV->hasInitializer()) {
10192       if (GV->getInitializer()->isNullValue())
10193         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10194       else if (isa<UndefValue>(GV->getInitializer()))
10195         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10196     }
10197   }
10198
10199   if (Op->hasOneUse()) {
10200     // Change select and PHI nodes to select values instead of addresses: this
10201     // helps alias analysis out a lot, allows many others simplifications, and
10202     // exposes redundancy in the code.
10203     //
10204     // Note that we cannot do the transformation unless we know that the
10205     // introduced loads cannot trap!  Something like this is valid as long as
10206     // the condition is always false: load (select bool %C, int* null, int* %G),
10207     // but it would not be valid if we transformed it to load from null
10208     // unconditionally.
10209     //
10210     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10211       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10212       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10213           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10214         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10215                                      SI->getOperand(1)->getName()+".val"), LI);
10216         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10217                                      SI->getOperand(2)->getName()+".val"), LI);
10218         return SelectInst::Create(SI->getCondition(), V1, V2);
10219       }
10220
10221       // load (select (cond, null, P)) -> load P
10222       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10223         if (C->isNullValue()) {
10224           LI.setOperand(0, SI->getOperand(2));
10225           return &LI;
10226         }
10227
10228       // load (select (cond, P, null)) -> load P
10229       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10230         if (C->isNullValue()) {
10231           LI.setOperand(0, SI->getOperand(1));
10232           return &LI;
10233         }
10234     }
10235   }
10236   return 0;
10237 }
10238
10239 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10240 /// when possible.
10241 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10242   User *CI = cast<User>(SI.getOperand(1));
10243   Value *CastOp = CI->getOperand(0);
10244
10245   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10246   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10247     const Type *SrcPTy = SrcTy->getElementType();
10248
10249     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10250       // If the source is an array, the code below will not succeed.  Check to
10251       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10252       // constants.
10253       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10254         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10255           if (ASrcTy->getNumElements() != 0) {
10256             Value* Idxs[2];
10257             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10258             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10259             SrcTy = cast<PointerType>(CastOp->getType());
10260             SrcPTy = SrcTy->getElementType();
10261           }
10262
10263       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10264           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10265                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10266
10267         // Okay, we are casting from one integer or pointer type to another of
10268         // the same size.  Instead of casting the pointer before 
10269         // the store, cast the value to be stored.
10270         Value *NewCast;
10271         Value *SIOp0 = SI.getOperand(0);
10272         Instruction::CastOps opcode = Instruction::BitCast;
10273         const Type* CastSrcTy = SIOp0->getType();
10274         const Type* CastDstTy = SrcPTy;
10275         if (isa<PointerType>(CastDstTy)) {
10276           if (CastSrcTy->isInteger())
10277             opcode = Instruction::IntToPtr;
10278         } else if (isa<IntegerType>(CastDstTy)) {
10279           if (isa<PointerType>(SIOp0->getType()))
10280             opcode = Instruction::PtrToInt;
10281         }
10282         if (Constant *C = dyn_cast<Constant>(SIOp0))
10283           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10284         else
10285           NewCast = IC.InsertNewInstBefore(
10286             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10287             SI);
10288         return new StoreInst(NewCast, CastOp);
10289       }
10290     }
10291   }
10292   return 0;
10293 }
10294
10295 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10296   Value *Val = SI.getOperand(0);
10297   Value *Ptr = SI.getOperand(1);
10298
10299   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10300     EraseInstFromFunction(SI);
10301     ++NumCombined;
10302     return 0;
10303   }
10304   
10305   // If the RHS is an alloca with a single use, zapify the store, making the
10306   // alloca dead.
10307   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10308     if (isa<AllocaInst>(Ptr)) {
10309       EraseInstFromFunction(SI);
10310       ++NumCombined;
10311       return 0;
10312     }
10313     
10314     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10315       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10316           GEP->getOperand(0)->hasOneUse()) {
10317         EraseInstFromFunction(SI);
10318         ++NumCombined;
10319         return 0;
10320       }
10321   }
10322
10323   // Attempt to improve the alignment.
10324   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10325   if (KnownAlign >
10326       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10327                                 SI.getAlignment()))
10328     SI.setAlignment(KnownAlign);
10329
10330   // Do really simple DSE, to catch cases where there are several consequtive
10331   // stores to the same location, separated by a few arithmetic operations. This
10332   // situation often occurs with bitfield accesses.
10333   BasicBlock::iterator BBI = &SI;
10334   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10335        --ScanInsts) {
10336     --BBI;
10337     
10338     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10339       // Prev store isn't volatile, and stores to the same location?
10340       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10341         ++NumDeadStore;
10342         ++BBI;
10343         EraseInstFromFunction(*PrevSI);
10344         continue;
10345       }
10346       break;
10347     }
10348     
10349     // If this is a load, we have to stop.  However, if the loaded value is from
10350     // the pointer we're loading and is producing the pointer we're storing,
10351     // then *this* store is dead (X = load P; store X -> P).
10352     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10353       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10354         EraseInstFromFunction(SI);
10355         ++NumCombined;
10356         return 0;
10357       }
10358       // Otherwise, this is a load from some other location.  Stores before it
10359       // may not be dead.
10360       break;
10361     }
10362     
10363     // Don't skip over loads or things that can modify memory.
10364     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10365       break;
10366   }
10367   
10368   
10369   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10370
10371   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10372   if (isa<ConstantPointerNull>(Ptr)) {
10373     if (!isa<UndefValue>(Val)) {
10374       SI.setOperand(0, UndefValue::get(Val->getType()));
10375       if (Instruction *U = dyn_cast<Instruction>(Val))
10376         AddToWorkList(U);  // Dropped a use.
10377       ++NumCombined;
10378     }
10379     return 0;  // Do not modify these!
10380   }
10381
10382   // store undef, Ptr -> noop
10383   if (isa<UndefValue>(Val)) {
10384     EraseInstFromFunction(SI);
10385     ++NumCombined;
10386     return 0;
10387   }
10388
10389   // If the pointer destination is a cast, see if we can fold the cast into the
10390   // source instead.
10391   if (isa<CastInst>(Ptr))
10392     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10393       return Res;
10394   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10395     if (CE->isCast())
10396       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10397         return Res;
10398
10399   
10400   // If this store is the last instruction in the basic block, and if the block
10401   // ends with an unconditional branch, try to move it to the successor block.
10402   BBI = &SI; ++BBI;
10403   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10404     if (BI->isUnconditional())
10405       if (SimplifyStoreAtEndOfBlock(SI))
10406         return 0;  // xform done!
10407   
10408   return 0;
10409 }
10410
10411 /// SimplifyStoreAtEndOfBlock - Turn things like:
10412 ///   if () { *P = v1; } else { *P = v2 }
10413 /// into a phi node with a store in the successor.
10414 ///
10415 /// Simplify things like:
10416 ///   *P = v1; if () { *P = v2; }
10417 /// into a phi node with a store in the successor.
10418 ///
10419 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10420   BasicBlock *StoreBB = SI.getParent();
10421   
10422   // Check to see if the successor block has exactly two incoming edges.  If
10423   // so, see if the other predecessor contains a store to the same location.
10424   // if so, insert a PHI node (if needed) and move the stores down.
10425   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10426   
10427   // Determine whether Dest has exactly two predecessors and, if so, compute
10428   // the other predecessor.
10429   pred_iterator PI = pred_begin(DestBB);
10430   BasicBlock *OtherBB = 0;
10431   if (*PI != StoreBB)
10432     OtherBB = *PI;
10433   ++PI;
10434   if (PI == pred_end(DestBB))
10435     return false;
10436   
10437   if (*PI != StoreBB) {
10438     if (OtherBB)
10439       return false;
10440     OtherBB = *PI;
10441   }
10442   if (++PI != pred_end(DestBB))
10443     return false;
10444
10445   // Bail out if all the relevant blocks aren't distinct (this can happen,
10446   // for example, if SI is in an infinite loop)
10447   if (StoreBB == DestBB || OtherBB == DestBB)
10448     return false;
10449
10450   // Verify that the other block ends in a branch and is not otherwise empty.
10451   BasicBlock::iterator BBI = OtherBB->getTerminator();
10452   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10453   if (!OtherBr || BBI == OtherBB->begin())
10454     return false;
10455   
10456   // If the other block ends in an unconditional branch, check for the 'if then
10457   // else' case.  there is an instruction before the branch.
10458   StoreInst *OtherStore = 0;
10459   if (OtherBr->isUnconditional()) {
10460     // If this isn't a store, or isn't a store to the same location, bail out.
10461     --BBI;
10462     OtherStore = dyn_cast<StoreInst>(BBI);
10463     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10464       return false;
10465   } else {
10466     // Otherwise, the other block ended with a conditional branch. If one of the
10467     // destinations is StoreBB, then we have the if/then case.
10468     if (OtherBr->getSuccessor(0) != StoreBB && 
10469         OtherBr->getSuccessor(1) != StoreBB)
10470       return false;
10471     
10472     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10473     // if/then triangle.  See if there is a store to the same ptr as SI that
10474     // lives in OtherBB.
10475     for (;; --BBI) {
10476       // Check to see if we find the matching store.
10477       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10478         if (OtherStore->getOperand(1) != SI.getOperand(1))
10479           return false;
10480         break;
10481       }
10482       // If we find something that may be using or overwriting the stored
10483       // value, or if we run out of instructions, we can't do the xform.
10484       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10485           BBI == OtherBB->begin())
10486         return false;
10487     }
10488     
10489     // In order to eliminate the store in OtherBr, we have to
10490     // make sure nothing reads or overwrites the stored value in
10491     // StoreBB.
10492     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10493       // FIXME: This should really be AA driven.
10494       if (I->mayReadFromMemory() || I->mayWriteToMemory())
10495         return false;
10496     }
10497   }
10498   
10499   // Insert a PHI node now if we need it.
10500   Value *MergedVal = OtherStore->getOperand(0);
10501   if (MergedVal != SI.getOperand(0)) {
10502     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10503     PN->reserveOperandSpace(2);
10504     PN->addIncoming(SI.getOperand(0), SI.getParent());
10505     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10506     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10507   }
10508   
10509   // Advance to a place where it is safe to insert the new store and
10510   // insert it.
10511   BBI = DestBB->getFirstNonPHI();
10512   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10513                                     OtherStore->isVolatile()), *BBI);
10514   
10515   // Nuke the old stores.
10516   EraseInstFromFunction(SI);
10517   EraseInstFromFunction(*OtherStore);
10518   ++NumCombined;
10519   return true;
10520 }
10521
10522
10523 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10524   // Change br (not X), label True, label False to: br X, label False, True
10525   Value *X = 0;
10526   BasicBlock *TrueDest;
10527   BasicBlock *FalseDest;
10528   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10529       !isa<Constant>(X)) {
10530     // Swap Destinations and condition...
10531     BI.setCondition(X);
10532     BI.setSuccessor(0, FalseDest);
10533     BI.setSuccessor(1, TrueDest);
10534     return &BI;
10535   }
10536
10537   // Cannonicalize fcmp_one -> fcmp_oeq
10538   FCmpInst::Predicate FPred; Value *Y;
10539   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10540                              TrueDest, FalseDest)))
10541     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10542          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10543       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10544       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10545       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10546       NewSCC->takeName(I);
10547       // Swap Destinations and condition...
10548       BI.setCondition(NewSCC);
10549       BI.setSuccessor(0, FalseDest);
10550       BI.setSuccessor(1, TrueDest);
10551       RemoveFromWorkList(I);
10552       I->eraseFromParent();
10553       AddToWorkList(NewSCC);
10554       return &BI;
10555     }
10556
10557   // Cannonicalize icmp_ne -> icmp_eq
10558   ICmpInst::Predicate IPred;
10559   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10560                       TrueDest, FalseDest)))
10561     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10562          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10563          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10564       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10565       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10566       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10567       NewSCC->takeName(I);
10568       // Swap Destinations and condition...
10569       BI.setCondition(NewSCC);
10570       BI.setSuccessor(0, FalseDest);
10571       BI.setSuccessor(1, TrueDest);
10572       RemoveFromWorkList(I);
10573       I->eraseFromParent();;
10574       AddToWorkList(NewSCC);
10575       return &BI;
10576     }
10577
10578   return 0;
10579 }
10580
10581 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10582   Value *Cond = SI.getCondition();
10583   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10584     if (I->getOpcode() == Instruction::Add)
10585       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10586         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10587         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10588           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10589                                                 AddRHS));
10590         SI.setOperand(0, I->getOperand(0));
10591         AddToWorkList(I);
10592         return &SI;
10593       }
10594   }
10595   return 0;
10596 }
10597
10598 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10599   // See if we are trying to extract a known value. If so, use that instead.
10600   if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
10601                                      EV.idx_end(), &EV))
10602     return ReplaceInstUsesWith(EV, Elt);
10603
10604   // No changes
10605   return 0;
10606 }
10607
10608 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10609 /// is to leave as a vector operation.
10610 static bool CheapToScalarize(Value *V, bool isConstant) {
10611   if (isa<ConstantAggregateZero>(V)) 
10612     return true;
10613   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10614     if (isConstant) return true;
10615     // If all elts are the same, we can extract.
10616     Constant *Op0 = C->getOperand(0);
10617     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10618       if (C->getOperand(i) != Op0)
10619         return false;
10620     return true;
10621   }
10622   Instruction *I = dyn_cast<Instruction>(V);
10623   if (!I) return false;
10624   
10625   // Insert element gets simplified to the inserted element or is deleted if
10626   // this is constant idx extract element and its a constant idx insertelt.
10627   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10628       isa<ConstantInt>(I->getOperand(2)))
10629     return true;
10630   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10631     return true;
10632   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10633     if (BO->hasOneUse() &&
10634         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10635          CheapToScalarize(BO->getOperand(1), isConstant)))
10636       return true;
10637   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10638     if (CI->hasOneUse() &&
10639         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10640          CheapToScalarize(CI->getOperand(1), isConstant)))
10641       return true;
10642   
10643   return false;
10644 }
10645
10646 /// Read and decode a shufflevector mask.
10647 ///
10648 /// It turns undef elements into values that are larger than the number of
10649 /// elements in the input.
10650 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10651   unsigned NElts = SVI->getType()->getNumElements();
10652   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10653     return std::vector<unsigned>(NElts, 0);
10654   if (isa<UndefValue>(SVI->getOperand(2)))
10655     return std::vector<unsigned>(NElts, 2*NElts);
10656
10657   std::vector<unsigned> Result;
10658   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10659   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10660     if (isa<UndefValue>(*i))
10661       Result.push_back(NElts*2);  // undef -> 8
10662     else
10663       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10664   return Result;
10665 }
10666
10667 /// FindScalarElement - Given a vector and an element number, see if the scalar
10668 /// value is already around as a register, for example if it were inserted then
10669 /// extracted from the vector.
10670 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10671   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10672   const VectorType *PTy = cast<VectorType>(V->getType());
10673   unsigned Width = PTy->getNumElements();
10674   if (EltNo >= Width)  // Out of range access.
10675     return UndefValue::get(PTy->getElementType());
10676   
10677   if (isa<UndefValue>(V))
10678     return UndefValue::get(PTy->getElementType());
10679   else if (isa<ConstantAggregateZero>(V))
10680     return Constant::getNullValue(PTy->getElementType());
10681   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10682     return CP->getOperand(EltNo);
10683   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10684     // If this is an insert to a variable element, we don't know what it is.
10685     if (!isa<ConstantInt>(III->getOperand(2))) 
10686       return 0;
10687     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10688     
10689     // If this is an insert to the element we are looking for, return the
10690     // inserted value.
10691     if (EltNo == IIElt) 
10692       return III->getOperand(1);
10693     
10694     // Otherwise, the insertelement doesn't modify the value, recurse on its
10695     // vector input.
10696     return FindScalarElement(III->getOperand(0), EltNo);
10697   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10698     unsigned InEl = getShuffleMask(SVI)[EltNo];
10699     if (InEl < Width)
10700       return FindScalarElement(SVI->getOperand(0), InEl);
10701     else if (InEl < Width*2)
10702       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10703     else
10704       return UndefValue::get(PTy->getElementType());
10705   }
10706   
10707   // Otherwise, we don't know.
10708   return 0;
10709 }
10710
10711 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10712   // If vector val is undef, replace extract with scalar undef.
10713   if (isa<UndefValue>(EI.getOperand(0)))
10714     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10715
10716   // If vector val is constant 0, replace extract with scalar 0.
10717   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10718     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10719   
10720   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10721     // If vector val is constant with all elements the same, replace EI with
10722     // that element. When the elements are not identical, we cannot replace yet
10723     // (we do that below, but only when the index is constant).
10724     Constant *op0 = C->getOperand(0);
10725     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10726       if (C->getOperand(i) != op0) {
10727         op0 = 0; 
10728         break;
10729       }
10730     if (op0)
10731       return ReplaceInstUsesWith(EI, op0);
10732   }
10733   
10734   // If extracting a specified index from the vector, see if we can recursively
10735   // find a previously computed scalar that was inserted into the vector.
10736   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10737     unsigned IndexVal = IdxC->getZExtValue();
10738     unsigned VectorWidth = 
10739       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10740       
10741     // If this is extracting an invalid index, turn this into undef, to avoid
10742     // crashing the code below.
10743     if (IndexVal >= VectorWidth)
10744       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10745     
10746     // This instruction only demands the single element from the input vector.
10747     // If the input vector has a single use, simplify it based on this use
10748     // property.
10749     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10750       uint64_t UndefElts;
10751       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10752                                                 1 << IndexVal,
10753                                                 UndefElts)) {
10754         EI.setOperand(0, V);
10755         return &EI;
10756       }
10757     }
10758     
10759     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10760       return ReplaceInstUsesWith(EI, Elt);
10761     
10762     // If the this extractelement is directly using a bitcast from a vector of
10763     // the same number of elements, see if we can find the source element from
10764     // it.  In this case, we will end up needing to bitcast the scalars.
10765     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10766       if (const VectorType *VT = 
10767               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10768         if (VT->getNumElements() == VectorWidth)
10769           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10770             return new BitCastInst(Elt, EI.getType());
10771     }
10772   }
10773   
10774   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10775     if (I->hasOneUse()) {
10776       // Push extractelement into predecessor operation if legal and
10777       // profitable to do so
10778       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10779         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10780         if (CheapToScalarize(BO, isConstantElt)) {
10781           ExtractElementInst *newEI0 = 
10782             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10783                                    EI.getName()+".lhs");
10784           ExtractElementInst *newEI1 =
10785             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10786                                    EI.getName()+".rhs");
10787           InsertNewInstBefore(newEI0, EI);
10788           InsertNewInstBefore(newEI1, EI);
10789           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10790         }
10791       } else if (isa<LoadInst>(I)) {
10792         unsigned AS = 
10793           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10794         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10795                                          PointerType::get(EI.getType(), AS),EI);
10796         GetElementPtrInst *GEP =
10797           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10798         InsertNewInstBefore(GEP, EI);
10799         return new LoadInst(GEP);
10800       }
10801     }
10802     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10803       // Extracting the inserted element?
10804       if (IE->getOperand(2) == EI.getOperand(1))
10805         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10806       // If the inserted and extracted elements are constants, they must not
10807       // be the same value, extract from the pre-inserted value instead.
10808       if (isa<Constant>(IE->getOperand(2)) &&
10809           isa<Constant>(EI.getOperand(1))) {
10810         AddUsesToWorkList(EI);
10811         EI.setOperand(0, IE->getOperand(0));
10812         return &EI;
10813       }
10814     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10815       // If this is extracting an element from a shufflevector, figure out where
10816       // it came from and extract from the appropriate input element instead.
10817       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10818         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10819         Value *Src;
10820         if (SrcIdx < SVI->getType()->getNumElements())
10821           Src = SVI->getOperand(0);
10822         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10823           SrcIdx -= SVI->getType()->getNumElements();
10824           Src = SVI->getOperand(1);
10825         } else {
10826           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10827         }
10828         return new ExtractElementInst(Src, SrcIdx);
10829       }
10830     }
10831   }
10832   return 0;
10833 }
10834
10835 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10836 /// elements from either LHS or RHS, return the shuffle mask and true. 
10837 /// Otherwise, return false.
10838 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10839                                          std::vector<Constant*> &Mask) {
10840   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10841          "Invalid CollectSingleShuffleElements");
10842   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10843
10844   if (isa<UndefValue>(V)) {
10845     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10846     return true;
10847   } else if (V == LHS) {
10848     for (unsigned i = 0; i != NumElts; ++i)
10849       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10850     return true;
10851   } else if (V == RHS) {
10852     for (unsigned i = 0; i != NumElts; ++i)
10853       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10854     return true;
10855   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10856     // If this is an insert of an extract from some other vector, include it.
10857     Value *VecOp    = IEI->getOperand(0);
10858     Value *ScalarOp = IEI->getOperand(1);
10859     Value *IdxOp    = IEI->getOperand(2);
10860     
10861     if (!isa<ConstantInt>(IdxOp))
10862       return false;
10863     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10864     
10865     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10866       // Okay, we can handle this if the vector we are insertinting into is
10867       // transitively ok.
10868       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10869         // If so, update the mask to reflect the inserted undef.
10870         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10871         return true;
10872       }      
10873     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10874       if (isa<ConstantInt>(EI->getOperand(1)) &&
10875           EI->getOperand(0)->getType() == V->getType()) {
10876         unsigned ExtractedIdx =
10877           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10878         
10879         // This must be extracting from either LHS or RHS.
10880         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10881           // Okay, we can handle this if the vector we are insertinting into is
10882           // transitively ok.
10883           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10884             // If so, update the mask to reflect the inserted value.
10885             if (EI->getOperand(0) == LHS) {
10886               Mask[InsertedIdx & (NumElts-1)] = 
10887                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10888             } else {
10889               assert(EI->getOperand(0) == RHS);
10890               Mask[InsertedIdx & (NumElts-1)] = 
10891                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10892               
10893             }
10894             return true;
10895           }
10896         }
10897       }
10898     }
10899   }
10900   // TODO: Handle shufflevector here!
10901   
10902   return false;
10903 }
10904
10905 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10906 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10907 /// that computes V and the LHS value of the shuffle.
10908 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10909                                      Value *&RHS) {
10910   assert(isa<VectorType>(V->getType()) && 
10911          (RHS == 0 || V->getType() == RHS->getType()) &&
10912          "Invalid shuffle!");
10913   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10914
10915   if (isa<UndefValue>(V)) {
10916     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10917     return V;
10918   } else if (isa<ConstantAggregateZero>(V)) {
10919     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10920     return V;
10921   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10922     // If this is an insert of an extract from some other vector, include it.
10923     Value *VecOp    = IEI->getOperand(0);
10924     Value *ScalarOp = IEI->getOperand(1);
10925     Value *IdxOp    = IEI->getOperand(2);
10926     
10927     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10928       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10929           EI->getOperand(0)->getType() == V->getType()) {
10930         unsigned ExtractedIdx =
10931           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10932         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10933         
10934         // Either the extracted from or inserted into vector must be RHSVec,
10935         // otherwise we'd end up with a shuffle of three inputs.
10936         if (EI->getOperand(0) == RHS || RHS == 0) {
10937           RHS = EI->getOperand(0);
10938           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10939           Mask[InsertedIdx & (NumElts-1)] = 
10940             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10941           return V;
10942         }
10943         
10944         if (VecOp == RHS) {
10945           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10946           // Everything but the extracted element is replaced with the RHS.
10947           for (unsigned i = 0; i != NumElts; ++i) {
10948             if (i != InsertedIdx)
10949               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10950           }
10951           return V;
10952         }
10953         
10954         // If this insertelement is a chain that comes from exactly these two
10955         // vectors, return the vector and the effective shuffle.
10956         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10957           return EI->getOperand(0);
10958         
10959       }
10960     }
10961   }
10962   // TODO: Handle shufflevector here!
10963   
10964   // Otherwise, can't do anything fancy.  Return an identity vector.
10965   for (unsigned i = 0; i != NumElts; ++i)
10966     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10967   return V;
10968 }
10969
10970 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10971   Value *VecOp    = IE.getOperand(0);
10972   Value *ScalarOp = IE.getOperand(1);
10973   Value *IdxOp    = IE.getOperand(2);
10974   
10975   // Inserting an undef or into an undefined place, remove this.
10976   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10977     ReplaceInstUsesWith(IE, VecOp);
10978   
10979   // If the inserted element was extracted from some other vector, and if the 
10980   // indexes are constant, try to turn this into a shufflevector operation.
10981   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10982     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10983         EI->getOperand(0)->getType() == IE.getType()) {
10984       unsigned NumVectorElts = IE.getType()->getNumElements();
10985       unsigned ExtractedIdx =
10986         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10987       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10988       
10989       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10990         return ReplaceInstUsesWith(IE, VecOp);
10991       
10992       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
10993         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10994       
10995       // If we are extracting a value from a vector, then inserting it right
10996       // back into the same place, just use the input vector.
10997       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10998         return ReplaceInstUsesWith(IE, VecOp);      
10999       
11000       // We could theoretically do this for ANY input.  However, doing so could
11001       // turn chains of insertelement instructions into a chain of shufflevector
11002       // instructions, and right now we do not merge shufflevectors.  As such,
11003       // only do this in a situation where it is clear that there is benefit.
11004       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11005         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11006         // the values of VecOp, except then one read from EIOp0.
11007         // Build a new shuffle mask.
11008         std::vector<Constant*> Mask;
11009         if (isa<UndefValue>(VecOp))
11010           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11011         else {
11012           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11013           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11014                                                        NumVectorElts));
11015         } 
11016         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11017         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11018                                      ConstantVector::get(Mask));
11019       }
11020       
11021       // If this insertelement isn't used by some other insertelement, turn it
11022       // (and any insertelements it points to), into one big shuffle.
11023       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11024         std::vector<Constant*> Mask;
11025         Value *RHS = 0;
11026         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11027         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11028         // We now have a shuffle of LHS, RHS, Mask.
11029         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11030       }
11031     }
11032   }
11033
11034   return 0;
11035 }
11036
11037
11038 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11039   Value *LHS = SVI.getOperand(0);
11040   Value *RHS = SVI.getOperand(1);
11041   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11042
11043   bool MadeChange = false;
11044   
11045   // Undefined shuffle mask -> undefined value.
11046   if (isa<UndefValue>(SVI.getOperand(2)))
11047     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11048   
11049   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11050   // the undef, change them to undefs.
11051   if (isa<UndefValue>(SVI.getOperand(1))) {
11052     // Scan to see if there are any references to the RHS.  If so, replace them
11053     // with undef element refs and set MadeChange to true.
11054     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11055       if (Mask[i] >= e && Mask[i] != 2*e) {
11056         Mask[i] = 2*e;
11057         MadeChange = true;
11058       }
11059     }
11060     
11061     if (MadeChange) {
11062       // Remap any references to RHS to use LHS.
11063       std::vector<Constant*> Elts;
11064       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11065         if (Mask[i] == 2*e)
11066           Elts.push_back(UndefValue::get(Type::Int32Ty));
11067         else
11068           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11069       }
11070       SVI.setOperand(2, ConstantVector::get(Elts));
11071     }
11072   }
11073   
11074   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11075   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11076   if (LHS == RHS || isa<UndefValue>(LHS)) {
11077     if (isa<UndefValue>(LHS) && LHS == RHS) {
11078       // shuffle(undef,undef,mask) -> undef.
11079       return ReplaceInstUsesWith(SVI, LHS);
11080     }
11081     
11082     // Remap any references to RHS to use LHS.
11083     std::vector<Constant*> Elts;
11084     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11085       if (Mask[i] >= 2*e)
11086         Elts.push_back(UndefValue::get(Type::Int32Ty));
11087       else {
11088         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11089             (Mask[i] <  e && isa<UndefValue>(LHS)))
11090           Mask[i] = 2*e;     // Turn into undef.
11091         else
11092           Mask[i] &= (e-1);  // Force to LHS.
11093         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11094       }
11095     }
11096     SVI.setOperand(0, SVI.getOperand(1));
11097     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11098     SVI.setOperand(2, ConstantVector::get(Elts));
11099     LHS = SVI.getOperand(0);
11100     RHS = SVI.getOperand(1);
11101     MadeChange = true;
11102   }
11103   
11104   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11105   bool isLHSID = true, isRHSID = true;
11106     
11107   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11108     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11109     // Is this an identity shuffle of the LHS value?
11110     isLHSID &= (Mask[i] == i);
11111       
11112     // Is this an identity shuffle of the RHS value?
11113     isRHSID &= (Mask[i]-e == i);
11114   }
11115
11116   // Eliminate identity shuffles.
11117   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11118   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11119   
11120   // If the LHS is a shufflevector itself, see if we can combine it with this
11121   // one without producing an unusual shuffle.  Here we are really conservative:
11122   // we are absolutely afraid of producing a shuffle mask not in the input
11123   // program, because the code gen may not be smart enough to turn a merged
11124   // shuffle into two specific shuffles: it may produce worse code.  As such,
11125   // we only merge two shuffles if the result is one of the two input shuffle
11126   // masks.  In this case, merging the shuffles just removes one instruction,
11127   // which we know is safe.  This is good for things like turning:
11128   // (splat(splat)) -> splat.
11129   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11130     if (isa<UndefValue>(RHS)) {
11131       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11132
11133       std::vector<unsigned> NewMask;
11134       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11135         if (Mask[i] >= 2*e)
11136           NewMask.push_back(2*e);
11137         else
11138           NewMask.push_back(LHSMask[Mask[i]]);
11139       
11140       // If the result mask is equal to the src shuffle or this shuffle mask, do
11141       // the replacement.
11142       if (NewMask == LHSMask || NewMask == Mask) {
11143         std::vector<Constant*> Elts;
11144         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11145           if (NewMask[i] >= e*2) {
11146             Elts.push_back(UndefValue::get(Type::Int32Ty));
11147           } else {
11148             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11149           }
11150         }
11151         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11152                                      LHSSVI->getOperand(1),
11153                                      ConstantVector::get(Elts));
11154       }
11155     }
11156   }
11157
11158   return MadeChange ? &SVI : 0;
11159 }
11160
11161
11162
11163
11164 /// TryToSinkInstruction - Try to move the specified instruction from its
11165 /// current block into the beginning of DestBlock, which can only happen if it's
11166 /// safe to move the instruction past all of the instructions between it and the
11167 /// end of its block.
11168 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11169   assert(I->hasOneUse() && "Invariants didn't hold!");
11170
11171   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11172   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11173     return false;
11174
11175   // Do not sink alloca instructions out of the entry block.
11176   if (isa<AllocaInst>(I) && I->getParent() ==
11177         &DestBlock->getParent()->getEntryBlock())
11178     return false;
11179
11180   // We can only sink load instructions if there is nothing between the load and
11181   // the end of block that could change the value.
11182   if (I->mayReadFromMemory()) {
11183     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11184          Scan != E; ++Scan)
11185       if (Scan->mayWriteToMemory())
11186         return false;
11187   }
11188
11189   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11190
11191   I->moveBefore(InsertPos);
11192   ++NumSunkInst;
11193   return true;
11194 }
11195
11196
11197 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11198 /// all reachable code to the worklist.
11199 ///
11200 /// This has a couple of tricks to make the code faster and more powerful.  In
11201 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11202 /// them to the worklist (this significantly speeds up instcombine on code where
11203 /// many instructions are dead or constant).  Additionally, if we find a branch
11204 /// whose condition is a known constant, we only visit the reachable successors.
11205 ///
11206 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11207                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11208                                        InstCombiner &IC,
11209                                        const TargetData *TD) {
11210   std::vector<BasicBlock*> Worklist;
11211   Worklist.push_back(BB);
11212
11213   while (!Worklist.empty()) {
11214     BB = Worklist.back();
11215     Worklist.pop_back();
11216     
11217     // We have now visited this block!  If we've already been here, ignore it.
11218     if (!Visited.insert(BB)) continue;
11219     
11220     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11221       Instruction *Inst = BBI++;
11222       
11223       // DCE instruction if trivially dead.
11224       if (isInstructionTriviallyDead(Inst)) {
11225         ++NumDeadInst;
11226         DOUT << "IC: DCE: " << *Inst;
11227         Inst->eraseFromParent();
11228         continue;
11229       }
11230       
11231       // ConstantProp instruction if trivially constant.
11232       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11233         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11234         Inst->replaceAllUsesWith(C);
11235         ++NumConstProp;
11236         Inst->eraseFromParent();
11237         continue;
11238       }
11239      
11240       IC.AddToWorkList(Inst);
11241     }
11242
11243     // Recursively visit successors.  If this is a branch or switch on a
11244     // constant, only visit the reachable successor.
11245     TerminatorInst *TI = BB->getTerminator();
11246     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11247       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11248         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11249         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11250         Worklist.push_back(ReachableBB);
11251         continue;
11252       }
11253     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11254       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11255         // See if this is an explicit destination.
11256         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11257           if (SI->getCaseValue(i) == Cond) {
11258             BasicBlock *ReachableBB = SI->getSuccessor(i);
11259             Worklist.push_back(ReachableBB);
11260             continue;
11261           }
11262         
11263         // Otherwise it is the default destination.
11264         Worklist.push_back(SI->getSuccessor(0));
11265         continue;
11266       }
11267     }
11268     
11269     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11270       Worklist.push_back(TI->getSuccessor(i));
11271   }
11272 }
11273
11274 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11275   bool Changed = false;
11276   TD = &getAnalysis<TargetData>();
11277   
11278   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11279              << F.getNameStr() << "\n");
11280
11281   {
11282     // Do a depth-first traversal of the function, populate the worklist with
11283     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11284     // track of which blocks we visit.
11285     SmallPtrSet<BasicBlock*, 64> Visited;
11286     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11287
11288     // Do a quick scan over the function.  If we find any blocks that are
11289     // unreachable, remove any instructions inside of them.  This prevents
11290     // the instcombine code from having to deal with some bad special cases.
11291     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11292       if (!Visited.count(BB)) {
11293         Instruction *Term = BB->getTerminator();
11294         while (Term != BB->begin()) {   // Remove instrs bottom-up
11295           BasicBlock::iterator I = Term; --I;
11296
11297           DOUT << "IC: DCE: " << *I;
11298           ++NumDeadInst;
11299
11300           if (!I->use_empty())
11301             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11302           I->eraseFromParent();
11303         }
11304       }
11305   }
11306
11307   while (!Worklist.empty()) {
11308     Instruction *I = RemoveOneFromWorkList();
11309     if (I == 0) continue;  // skip null values.
11310
11311     // Check to see if we can DCE the instruction.
11312     if (isInstructionTriviallyDead(I)) {
11313       // Add operands to the worklist.
11314       if (I->getNumOperands() < 4)
11315         AddUsesToWorkList(*I);
11316       ++NumDeadInst;
11317
11318       DOUT << "IC: DCE: " << *I;
11319
11320       I->eraseFromParent();
11321       RemoveFromWorkList(I);
11322       continue;
11323     }
11324
11325     // Instruction isn't dead, see if we can constant propagate it.
11326     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11327       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11328
11329       // Add operands to the worklist.
11330       AddUsesToWorkList(*I);
11331       ReplaceInstUsesWith(*I, C);
11332
11333       ++NumConstProp;
11334       I->eraseFromParent();
11335       RemoveFromWorkList(I);
11336       continue;
11337     }
11338
11339     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11340       // See if we can constant fold its operands.
11341       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11342         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11343           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11344             i->set(NewC);
11345         }
11346       }
11347     }
11348
11349     // See if we can trivially sink this instruction to a successor basic block.
11350     // FIXME: Remove GetResultInst test when first class support for aggregates
11351     // is implemented.
11352     if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11353       BasicBlock *BB = I->getParent();
11354       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11355       if (UserParent != BB) {
11356         bool UserIsSuccessor = false;
11357         // See if the user is one of our successors.
11358         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11359           if (*SI == UserParent) {
11360             UserIsSuccessor = true;
11361             break;
11362           }
11363
11364         // If the user is one of our immediate successors, and if that successor
11365         // only has us as a predecessors (we'd have to split the critical edge
11366         // otherwise), we can keep going.
11367         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11368             next(pred_begin(UserParent)) == pred_end(UserParent))
11369           // Okay, the CFG is simple enough, try to sink this instruction.
11370           Changed |= TryToSinkInstruction(I, UserParent);
11371       }
11372     }
11373
11374     // Now that we have an instruction, try combining it to simplify it...
11375 #ifndef NDEBUG
11376     std::string OrigI;
11377 #endif
11378     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11379     if (Instruction *Result = visit(*I)) {
11380       ++NumCombined;
11381       // Should we replace the old instruction with a new one?
11382       if (Result != I) {
11383         DOUT << "IC: Old = " << *I
11384              << "    New = " << *Result;
11385
11386         // Everything uses the new instruction now.
11387         I->replaceAllUsesWith(Result);
11388
11389         // Push the new instruction and any users onto the worklist.
11390         AddToWorkList(Result);
11391         AddUsersToWorkList(*Result);
11392
11393         // Move the name to the new instruction first.
11394         Result->takeName(I);
11395
11396         // Insert the new instruction into the basic block...
11397         BasicBlock *InstParent = I->getParent();
11398         BasicBlock::iterator InsertPos = I;
11399
11400         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11401           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11402             ++InsertPos;
11403
11404         InstParent->getInstList().insert(InsertPos, Result);
11405
11406         // Make sure that we reprocess all operands now that we reduced their
11407         // use counts.
11408         AddUsesToWorkList(*I);
11409
11410         // Instructions can end up on the worklist more than once.  Make sure
11411         // we do not process an instruction that has been deleted.
11412         RemoveFromWorkList(I);
11413
11414         // Erase the old instruction.
11415         InstParent->getInstList().erase(I);
11416       } else {
11417 #ifndef NDEBUG
11418         DOUT << "IC: Mod = " << OrigI
11419              << "    New = " << *I;
11420 #endif
11421
11422         // If the instruction was modified, it's possible that it is now dead.
11423         // if so, remove it.
11424         if (isInstructionTriviallyDead(I)) {
11425           // Make sure we process all operands now that we are reducing their
11426           // use counts.
11427           AddUsesToWorkList(*I);
11428
11429           // Instructions may end up in the worklist more than once.  Erase all
11430           // occurrences of this instruction.
11431           RemoveFromWorkList(I);
11432           I->eraseFromParent();
11433         } else {
11434           AddToWorkList(I);
11435           AddUsersToWorkList(*I);
11436         }
11437       }
11438       Changed = true;
11439     }
11440   }
11441
11442   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11443     
11444   // Do an explicit clear, this shrinks the map if needed.
11445   WorklistMap.clear();
11446   return Changed;
11447 }
11448
11449
11450 bool InstCombiner::runOnFunction(Function &F) {
11451   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11452   
11453   bool EverMadeChange = false;
11454
11455   // Iterate while there is work to do.
11456   unsigned Iteration = 0;
11457   while (DoOneIteration(F, Iteration++))
11458     EverMadeChange = true;
11459   return EverMadeChange;
11460 }
11461
11462 FunctionPass *llvm::createInstructionCombiningPass() {
11463   return new InstCombiner();
11464 }
11465