Change these tests to use regular loads instead of llvm.x86.sse2.loadu.dq.
[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     SmallVector<Instruction*, 256> 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(&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(*i))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           *i = UndefValue::get(Op->getType());
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitSub(BinaryOperator &I);
171     Instruction *visitMul(BinaryOperator &I);
172     Instruction *visitURem(BinaryOperator &I);
173     Instruction *visitSRem(BinaryOperator &I);
174     Instruction *visitFRem(BinaryOperator &I);
175     bool SimplifyDivRemOfSelect(BinaryOperator &I);
176     Instruction *commonRemTransforms(BinaryOperator &I);
177     Instruction *commonIRemTransforms(BinaryOperator &I);
178     Instruction *commonDivTransforms(BinaryOperator &I);
179     Instruction *commonIDivTransforms(BinaryOperator &I);
180     Instruction *visitUDiv(BinaryOperator &I);
181     Instruction *visitSDiv(BinaryOperator &I);
182     Instruction *visitFDiv(BinaryOperator &I);
183     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
184     Instruction *visitAnd(BinaryOperator &I);
185     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
186     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
187                                      Value *A, Value *B, Value *C);
188     Instruction *visitOr (BinaryOperator &I);
189     Instruction *visitXor(BinaryOperator &I);
190     Instruction *visitShl(BinaryOperator &I);
191     Instruction *visitAShr(BinaryOperator &I);
192     Instruction *visitLShr(BinaryOperator &I);
193     Instruction *commonShiftTransforms(BinaryOperator &I);
194     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195                                       Constant *RHSC);
196     Instruction *visitFCmpInst(FCmpInst &I);
197     Instruction *visitICmpInst(ICmpInst &I);
198     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
199     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200                                                 Instruction *LHS,
201                                                 ConstantInt *RHS);
202     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203                                 ConstantInt *DivRHS);
204
205     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206                              ICmpInst::Predicate Cond, Instruction &I);
207     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
208                                      BinaryOperator &I);
209     Instruction *commonCastTransforms(CastInst &CI);
210     Instruction *commonIntCastTransforms(CastInst &CI);
211     Instruction *commonPointerCastTransforms(CastInst &CI);
212     Instruction *visitTrunc(TruncInst &CI);
213     Instruction *visitZExt(ZExtInst &CI);
214     Instruction *visitSExt(SExtInst &CI);
215     Instruction *visitFPTrunc(FPTruncInst &CI);
216     Instruction *visitFPExt(CastInst &CI);
217     Instruction *visitFPToUI(FPToUIInst &FI);
218     Instruction *visitFPToSI(FPToSIInst &FI);
219     Instruction *visitUIToFP(CastInst &CI);
220     Instruction *visitSIToFP(CastInst &CI);
221     Instruction *visitPtrToInt(CastInst &CI);
222     Instruction *visitIntToPtr(IntToPtrInst &CI);
223     Instruction *visitBitCast(BitCastInst &CI);
224     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225                                 Instruction *FI);
226     Instruction *visitSelectInst(SelectInst &SI);
227     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
228     Instruction *visitCallInst(CallInst &CI);
229     Instruction *visitInvokeInst(InvokeInst &II);
230     Instruction *visitPHINode(PHINode &PN);
231     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
232     Instruction *visitAllocationInst(AllocationInst &AI);
233     Instruction *visitFreeInst(FreeInst &FI);
234     Instruction *visitLoadInst(LoadInst &LI);
235     Instruction *visitStoreInst(StoreInst &SI);
236     Instruction *visitBranchInst(BranchInst &BI);
237     Instruction *visitSwitchInst(SwitchInst &SI);
238     Instruction *visitInsertElementInst(InsertElementInst &IE);
239     Instruction *visitExtractElementInst(ExtractElementInst &EI);
240     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
241     Instruction *visitExtractValueInst(ExtractValueInst &EV);
242
243     // visitInstruction - Specify what to return for unhandled instructions...
244     Instruction *visitInstruction(Instruction &I) { return 0; }
245
246   private:
247     Instruction *visitCallSite(CallSite CS);
248     bool transformConstExprCastCall(CallSite CS);
249     Instruction *transformCallThroughTrampoline(CallSite CS);
250     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251                                    bool DoXform = true);
252     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
253
254   public:
255     // InsertNewInstBefore - insert an instruction New before instruction Old
256     // in the program.  Add the new instruction to the worklist.
257     //
258     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
259       assert(New && New->getParent() == 0 &&
260              "New instruction already inserted into a basic block!");
261       BasicBlock *BB = Old.getParent();
262       BB->getInstList().insert(&Old, New);  // Insert inst
263       AddToWorkList(New);
264       return New;
265     }
266
267     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268     /// This also adds the cast to the worklist.  Finally, this returns the
269     /// cast.
270     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
271                             Instruction &Pos) {
272       if (V->getType() == Ty) return V;
273
274       if (Constant *CV = dyn_cast<Constant>(V))
275         return ConstantExpr::getCast(opc, CV, Ty);
276       
277       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
278       AddToWorkList(C);
279       return C;
280     }
281         
282     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
284     }
285
286
287     // ReplaceInstUsesWith - This method is to be used when an instruction is
288     // found to be dead, replacable with another preexisting expression.  Here
289     // we add all uses of I to the worklist, replace all uses of I with the new
290     // value, then return I, so that the inst combiner will know that I was
291     // modified.
292     //
293     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
294       AddUsersToWorkList(I);         // Add all modified instrs to worklist
295       if (&I != V) {
296         I.replaceAllUsesWith(V);
297         return &I;
298       } else {
299         // If we are replacing the instruction with itself, this must be in a
300         // segment of unreachable code, so just clobber the instruction.
301         I.replaceAllUsesWith(UndefValue::get(I.getType()));
302         return &I;
303       }
304     }
305
306     // EraseInstFromFunction - When dealing with an instruction that has side
307     // effects or produces a void value, we can't rely on DCE to delete the
308     // instruction.  Instead, visit methods should return the value returned by
309     // this function.
310     Instruction *EraseInstFromFunction(Instruction &I) {
311       assert(I.use_empty() && "Cannot erase instruction that is used!");
312       AddUsesToWorkList(I);
313       RemoveFromWorkList(&I);
314       I.eraseFromParent();
315       return 0;  // Don't do anything with FI
316     }
317         
318     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
319                            APInt &KnownOne, unsigned Depth = 0) const {
320       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
321     }
322     
323     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
324                            unsigned Depth = 0) const {
325       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
326     }
327     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
328       return llvm::ComputeNumSignBits(Op, TD, Depth);
329     }
330
331   private:
332
333     /// SimplifyCommutative - This performs a few simplifications for 
334     /// commutative operators.
335     bool SimplifyCommutative(BinaryOperator &I);
336
337     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338     /// most-complex to least-complex order.
339     bool SimplifyCompare(CmpInst &I);
340
341     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
342     /// based on the demanded bits.
343     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
344                                    APInt& KnownZero, APInt& KnownOne,
345                                    unsigned Depth);
346     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
347                               APInt& KnownZero, APInt& KnownOne,
348                               unsigned Depth=0);
349         
350     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
351     /// SimplifyDemandedBits knows about.  See if the instruction has any
352     /// properties that allow us to simplify its operands.
353     bool SimplifyDemandedInstructionBits(Instruction &Inst);
354         
355     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
356                                       APInt& UndefElts, unsigned Depth = 0);
357       
358     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
359     // PHI node as operand #0, see if we can fold the instruction into the PHI
360     // (which is only possible if all operands to the PHI are constants).
361     Instruction *FoldOpIntoPhi(Instruction &I);
362
363     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
364     // operator and they all are only used by the PHI, PHI together their
365     // inputs, and do the operation once, to the result of the PHI.
366     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
367     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
368     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
369
370     
371     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
372                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
373     
374     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
375                               bool isSub, Instruction &I);
376     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
377                                  bool isSigned, bool Inside, Instruction &IB);
378     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
379     Instruction *MatchBSwap(BinaryOperator &I);
380     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
381     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
382     Instruction *SimplifyMemSet(MemSetInst *MI);
383
384
385     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
386
387     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
388                                     unsigned CastOpc, int &NumCastsRemoved);
389     unsigned GetOrEnforceKnownAlignment(Value *V,
390                                         unsigned PrefAlign = 0);
391
392   };
393 }
394
395 char InstCombiner::ID = 0;
396 static RegisterPass<InstCombiner>
397 X("instcombine", "Combine redundant instructions");
398
399 // getComplexity:  Assign a complexity or rank value to LLVM Values...
400 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
401 static unsigned getComplexity(Value *V) {
402   if (isa<Instruction>(V)) {
403     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
404       return 3;
405     return 4;
406   }
407   if (isa<Argument>(V)) return 3;
408   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
409 }
410
411 // isOnlyUse - Return true if this instruction will be deleted if we stop using
412 // it.
413 static bool isOnlyUse(Value *V) {
414   return V->hasOneUse() || isa<Constant>(V);
415 }
416
417 // getPromotedType - Return the specified type promoted as it would be to pass
418 // though a va_arg area...
419 static const Type *getPromotedType(const Type *Ty) {
420   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
421     if (ITy->getBitWidth() < 32)
422       return Type::Int32Ty;
423   }
424   return Ty;
425 }
426
427 /// getBitCastOperand - If the specified operand is a CastInst, a constant
428 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
429 /// operand value, otherwise return null.
430 static Value *getBitCastOperand(Value *V) {
431   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
432     // BitCastInst?
433     return I->getOperand(0);
434   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
435     // GetElementPtrInst?
436     if (GEP->hasAllZeroIndices())
437       return GEP->getOperand(0);
438   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
439     if (CE->getOpcode() == Instruction::BitCast)
440       // BitCast ConstantExp?
441       return CE->getOperand(0);
442     else if (CE->getOpcode() == Instruction::GetElementPtr) {
443       // GetElementPtr ConstantExp?
444       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
445            I != E; ++I) {
446         ConstantInt *CI = dyn_cast<ConstantInt>(I);
447         if (!CI || !CI->isZero())
448           // Any non-zero indices? Not cast-like.
449           return 0;
450       }
451       // All-zero indices? This is just like casting.
452       return CE->getOperand(0);
453     }
454   }
455   return 0;
456 }
457
458 /// This function is a wrapper around CastInst::isEliminableCastPair. It
459 /// simply extracts arguments and returns what that function returns.
460 static Instruction::CastOps 
461 isEliminableCastPair(
462   const CastInst *CI, ///< The first cast instruction
463   unsigned opcode,       ///< The opcode of the second cast instruction
464   const Type *DstTy,     ///< The target type for the second cast instruction
465   TargetData *TD         ///< The target data for pointer size
466 ) {
467   
468   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
469   const Type *MidTy = CI->getType();                  // B from above
470
471   // Get the opcodes of the two Cast instructions
472   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
473   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
474
475   return Instruction::CastOps(
476       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
477                                      DstTy, TD->getIntPtrType()));
478 }
479
480 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
481 /// in any code being generated.  It does not require codegen if V is simple
482 /// enough or if the cast can be folded into other casts.
483 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
484                               const Type *Ty, TargetData *TD) {
485   if (V->getType() == Ty || isa<Constant>(V)) return false;
486   
487   // If this is another cast that can be eliminated, it isn't codegen either.
488   if (const CastInst *CI = dyn_cast<CastInst>(V))
489     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
490       return false;
491   return true;
492 }
493
494 // SimplifyCommutative - This performs a few simplifications for commutative
495 // operators:
496 //
497 //  1. Order operands such that they are listed from right (least complex) to
498 //     left (most complex).  This puts constants before unary operators before
499 //     binary operators.
500 //
501 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
502 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
503 //
504 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
505   bool Changed = false;
506   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
507     Changed = !I.swapOperands();
508
509   if (!I.isAssociative()) return Changed;
510   Instruction::BinaryOps Opcode = I.getOpcode();
511   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
512     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
513       if (isa<Constant>(I.getOperand(1))) {
514         Constant *Folded = ConstantExpr::get(I.getOpcode(),
515                                              cast<Constant>(I.getOperand(1)),
516                                              cast<Constant>(Op->getOperand(1)));
517         I.setOperand(0, Op->getOperand(0));
518         I.setOperand(1, Folded);
519         return true;
520       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
521         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
522             isOnlyUse(Op) && isOnlyUse(Op1)) {
523           Constant *C1 = cast<Constant>(Op->getOperand(1));
524           Constant *C2 = cast<Constant>(Op1->getOperand(1));
525
526           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
527           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
528           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
529                                                     Op1->getOperand(0),
530                                                     Op1->getName(), &I);
531           AddToWorkList(New);
532           I.setOperand(0, New);
533           I.setOperand(1, Folded);
534           return true;
535         }
536     }
537   return Changed;
538 }
539
540 /// SimplifyCompare - For a CmpInst this function just orders the operands
541 /// so that theyare listed from right (least complex) to left (most complex).
542 /// This puts constants before unary operators before binary operators.
543 bool InstCombiner::SimplifyCompare(CmpInst &I) {
544   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
545     return false;
546   I.swapOperands();
547   // Compare instructions are not associative so there's nothing else we can do.
548   return true;
549 }
550
551 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
552 // if the LHS is a constant zero (which is the 'negate' form).
553 //
554 static inline Value *dyn_castNegVal(Value *V) {
555   if (BinaryOperator::isNeg(V))
556     return BinaryOperator::getNegArgument(V);
557
558   // Constants can be considered to be negated values if they can be folded.
559   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
560     return ConstantExpr::getNeg(C);
561
562   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
563     if (C->getType()->getElementType()->isInteger())
564       return ConstantExpr::getNeg(C);
565
566   return 0;
567 }
568
569 static inline Value *dyn_castNotVal(Value *V) {
570   if (BinaryOperator::isNot(V))
571     return BinaryOperator::getNotArgument(V);
572
573   // Constants can be considered to be not'ed values...
574   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
575     return ConstantInt::get(~C->getValue());
576   return 0;
577 }
578
579 // dyn_castFoldableMul - If this value is a multiply that can be folded into
580 // other computations (because it has a constant operand), return the
581 // non-constant operand of the multiply, and set CST to point to the multiplier.
582 // Otherwise, return null.
583 //
584 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
585   if (V->hasOneUse() && V->getType()->isInteger())
586     if (Instruction *I = dyn_cast<Instruction>(V)) {
587       if (I->getOpcode() == Instruction::Mul)
588         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
589           return I->getOperand(0);
590       if (I->getOpcode() == Instruction::Shl)
591         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
592           // The multiplier is really 1 << CST.
593           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
594           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
595           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
596           return I->getOperand(0);
597         }
598     }
599   return 0;
600 }
601
602 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
603 /// expression, return it.
604 static User *dyn_castGetElementPtr(Value *V) {
605   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
606   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
607     if (CE->getOpcode() == Instruction::GetElementPtr)
608       return cast<User>(V);
609   return false;
610 }
611
612 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
613 /// opcode value. Otherwise return UserOp1.
614 static unsigned getOpcode(const Value *V) {
615   if (const Instruction *I = dyn_cast<Instruction>(V))
616     return I->getOpcode();
617   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
618     return CE->getOpcode();
619   // Use UserOp1 to mean there's no opcode.
620   return Instruction::UserOp1;
621 }
622
623 /// AddOne - Add one to a ConstantInt
624 static ConstantInt *AddOne(ConstantInt *C) {
625   APInt Val(C->getValue());
626   return ConstantInt::get(++Val);
627 }
628 /// SubOne - Subtract one from a ConstantInt
629 static ConstantInt *SubOne(ConstantInt *C) {
630   APInt Val(C->getValue());
631   return ConstantInt::get(--Val);
632 }
633 /// Add - Add two ConstantInts together
634 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
635   return ConstantInt::get(C1->getValue() + C2->getValue());
636 }
637 /// And - Bitwise AND two ConstantInts together
638 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
639   return ConstantInt::get(C1->getValue() & C2->getValue());
640 }
641 /// Subtract - Subtract one ConstantInt from another
642 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
643   return ConstantInt::get(C1->getValue() - C2->getValue());
644 }
645 /// Multiply - Multiply two ConstantInts together
646 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
647   return ConstantInt::get(C1->getValue() * C2->getValue());
648 }
649 /// MultiplyOverflows - True if the multiply can not be expressed in an int
650 /// this size.
651 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
652   uint32_t W = C1->getBitWidth();
653   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
654   if (sign) {
655     LHSExt.sext(W * 2);
656     RHSExt.sext(W * 2);
657   } else {
658     LHSExt.zext(W * 2);
659     RHSExt.zext(W * 2);
660   }
661
662   APInt MulExt = LHSExt * RHSExt;
663
664   if (sign) {
665     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667     return MulExt.slt(Min) || MulExt.sgt(Max);
668   } else 
669     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
670 }
671
672
673 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
674 /// specified instruction is a constant integer.  If so, check to see if there
675 /// are any bits set in the constant that are not demanded.  If so, shrink the
676 /// constant and return true.
677 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
678                                    APInt Demanded) {
679   assert(I && "No instruction?");
680   assert(OpNo < I->getNumOperands() && "Operand index too large");
681
682   // If the operand is not a constant integer, nothing to do.
683   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684   if (!OpC) return false;
685
686   // If there are no bits set that aren't demanded, nothing to do.
687   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688   if ((~Demanded & OpC->getValue()) == 0)
689     return false;
690
691   // This instruction is producing bits that are not demanded. Shrink the RHS.
692   Demanded &= OpC->getValue();
693   I->setOperand(OpNo, ConstantInt::get(Demanded));
694   return true;
695 }
696
697 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
698 // set of known zero and one bits, compute the maximum and minimum values that
699 // could have the specified known zero and known one bits, returning them in
700 // min/max.
701 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
702                                                    const APInt& KnownZero,
703                                                    const APInt& KnownOne,
704                                                    APInt& Min, APInt& Max) {
705   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
706   assert(KnownZero.getBitWidth() == BitWidth && 
707          KnownOne.getBitWidth() == BitWidth &&
708          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
709          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
710   APInt UnknownBits = ~(KnownZero|KnownOne);
711
712   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
713   // bit if it is unknown.
714   Min = KnownOne;
715   Max = KnownOne|UnknownBits;
716   
717   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
718     Min.set(BitWidth-1);
719     Max.clear(BitWidth-1);
720   }
721 }
722
723 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
724 // a set of known zero and one bits, compute the maximum and minimum values that
725 // could have the specified known zero and known one bits, returning them in
726 // min/max.
727 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
728                                                      const APInt &KnownZero,
729                                                      const APInt &KnownOne,
730                                                      APInt &Min, APInt &Max) {
731   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
732   assert(KnownZero.getBitWidth() == BitWidth && 
733          KnownOne.getBitWidth() == BitWidth &&
734          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
735          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
736   APInt UnknownBits = ~(KnownZero|KnownOne);
737   
738   // The minimum value is when the unknown bits are all zeros.
739   Min = KnownOne;
740   // The maximum value is when the unknown bits are all ones.
741   Max = KnownOne|UnknownBits;
742 }
743
744 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
745 /// SimplifyDemandedBits knows about.  See if the instruction has any
746 /// properties that allow us to simplify its operands.
747 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
748   unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
749   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
750   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
751   
752   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
753                                      KnownZero, KnownOne, 0);
754   if (V == 0) return false;
755   if (V == &Inst) return true;
756   ReplaceInstUsesWith(Inst, V);
757   return true;
758 }
759
760 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
761 /// specified instruction operand if possible, updating it in place.  It returns
762 /// true if it made any change and false otherwise.
763 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
764                                         APInt &KnownZero, APInt &KnownOne,
765                                         unsigned Depth) {
766   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
767                                           KnownZero, KnownOne, Depth);
768   if (NewVal == 0) return false;
769   U.set(NewVal);
770   return true;
771 }
772
773
774 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
775 /// value based on the demanded bits.  When this function is called, it is known
776 /// that only the bits set in DemandedMask of the result of V are ever used
777 /// downstream. Consequently, depending on the mask and V, it may be possible
778 /// to replace V with a constant or one of its operands. In such cases, this
779 /// function does the replacement and returns true. In all other cases, it
780 /// returns false after analyzing the expression and setting KnownOne and known
781 /// to be one in the expression.  KnownZero contains all the bits that are known
782 /// to be zero in the expression. These are provided to potentially allow the
783 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
784 /// the expression. KnownOne and KnownZero always follow the invariant that 
785 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
786 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
787 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
788 /// and KnownOne must all be the same.
789 ///
790 /// This returns null if it did not change anything and it permits no
791 /// simplification.  This returns V itself if it did some simplification of V's
792 /// operands based on the information about what bits are demanded. This returns
793 /// some other non-null value if it found out that V is equal to another value
794 /// in the context where the specified bits are demanded, but not for all users.
795 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
796                                              APInt &KnownZero, APInt &KnownOne,
797                                              unsigned Depth) {
798   assert(V != 0 && "Null pointer of Value???");
799   assert(Depth <= 6 && "Limit Search Depth");
800   uint32_t BitWidth = DemandedMask.getBitWidth();
801   const IntegerType *VTy = cast<IntegerType>(V->getType());
802   assert(VTy->getBitWidth() == BitWidth && 
803          KnownZero.getBitWidth() == BitWidth && 
804          KnownOne.getBitWidth() == BitWidth &&
805          "Value *V, DemandedMask, KnownZero and KnownOne \
806           must have same BitWidth");
807   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808     // We know all of the bits for a constant!
809     KnownOne = CI->getValue() & DemandedMask;
810     KnownZero = ~KnownOne & DemandedMask;
811     return 0;
812   }
813   
814   KnownZero.clear();
815   KnownOne.clear();
816   if (DemandedMask == 0) {   // Not demanding any bits from V.
817     if (isa<UndefValue>(V))
818       return 0;
819     return UndefValue::get(VTy);
820   }
821   
822   if (Depth == 6)        // Limit search depth.
823     return 0;
824   
825   Instruction *I = dyn_cast<Instruction>(V);
826   if (!I) return 0;        // Only analyze instructions.
827   
828   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
829   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
830
831   // If there are multiple uses of this value and we aren't at the root, then
832   // we can't do any simplifications of the operands, because DemandedMask
833   // only reflects the bits demanded by *one* of the users.
834   if (Depth != 0 && !I->hasOneUse()) {
835     // Despite the fact that we can't simplify this instruction in all User's
836     // context, we can at least compute the knownzero/knownone bits, and we can
837     // do simplifications that apply to *just* the one user if we know that
838     // this instruction has a simpler value in that context.
839     if (I->getOpcode() == Instruction::And) {
840       // If either the LHS or the RHS are Zero, the result is zero.
841       ComputeMaskedBits(I->getOperand(1), DemandedMask,
842                         RHSKnownZero, RHSKnownOne, Depth+1);
843       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
844                         LHSKnownZero, LHSKnownOne, Depth+1);
845       
846       // If all of the demanded bits are known 1 on one side, return the other.
847       // These bits cannot contribute to the result of the 'and' in this
848       // context.
849       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
850           (DemandedMask & ~LHSKnownZero))
851         return I->getOperand(0);
852       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
853           (DemandedMask & ~RHSKnownZero))
854         return I->getOperand(1);
855       
856       // If all of the demanded bits in the inputs are known zeros, return zero.
857       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
858         return Constant::getNullValue(VTy);
859       
860     } else if (I->getOpcode() == Instruction::Or) {
861       // We can simplify (X|Y) -> X or Y in the user's context if we know that
862       // only bits from X or Y are demanded.
863       
864       // If either the LHS or the RHS are One, the result is One.
865       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
866                         RHSKnownZero, RHSKnownOne, Depth+1);
867       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
868                         LHSKnownZero, LHSKnownOne, Depth+1);
869       
870       // If all of the demanded bits are known zero on one side, return the
871       // other.  These bits cannot contribute to the result of the 'or' in this
872       // context.
873       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
874           (DemandedMask & ~LHSKnownOne))
875         return I->getOperand(0);
876       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
877           (DemandedMask & ~RHSKnownOne))
878         return I->getOperand(1);
879       
880       // If all of the potentially set bits on one side are known to be set on
881       // the other side, just use the 'other' side.
882       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
883           (DemandedMask & (~RHSKnownZero)))
884         return I->getOperand(0);
885       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
886           (DemandedMask & (~LHSKnownZero)))
887         return I->getOperand(1);
888     }
889     
890     // Compute the KnownZero/KnownOne bits to simplify things downstream.
891     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
892     return 0;
893   }
894   
895   // If this is the root being simplified, allow it to have multiple uses,
896   // just set the DemandedMask to all bits so that we can try to simplify the
897   // operands.  This allows visitTruncInst (for example) to simplify the
898   // operand of a trunc without duplicating all the logic below.
899   if (Depth == 0 && !V->hasOneUse())
900     DemandedMask = APInt::getAllOnesValue(BitWidth);
901   
902   switch (I->getOpcode()) {
903   default:
904     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
905     break;
906   case Instruction::And:
907     // If either the LHS or the RHS are Zero, the result is zero.
908     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
909                              RHSKnownZero, RHSKnownOne, Depth+1) ||
910         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
911                              LHSKnownZero, LHSKnownOne, Depth+1))
912       return I;
913     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
914     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
915
916     // If all of the demanded bits are known 1 on one side, return the other.
917     // These bits cannot contribute to the result of the 'and'.
918     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
919         (DemandedMask & ~LHSKnownZero))
920       return I->getOperand(0);
921     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
922         (DemandedMask & ~RHSKnownZero))
923       return I->getOperand(1);
924     
925     // If all of the demanded bits in the inputs are known zeros, return zero.
926     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
927       return Constant::getNullValue(VTy);
928       
929     // If the RHS is a constant, see if we can simplify it.
930     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
931       return I;
932       
933     // Output known-1 bits are only known if set in both the LHS & RHS.
934     RHSKnownOne &= LHSKnownOne;
935     // Output known-0 are known to be clear if zero in either the LHS | RHS.
936     RHSKnownZero |= LHSKnownZero;
937     break;
938   case Instruction::Or:
939     // If either the LHS or the RHS are One, the result is One.
940     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
941                              RHSKnownZero, RHSKnownOne, Depth+1) ||
942         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
943                              LHSKnownZero, LHSKnownOne, Depth+1))
944       return I;
945     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
946     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
947     
948     // If all of the demanded bits are known zero on one side, return the other.
949     // These bits cannot contribute to the result of the 'or'.
950     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
951         (DemandedMask & ~LHSKnownOne))
952       return I->getOperand(0);
953     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
954         (DemandedMask & ~RHSKnownOne))
955       return I->getOperand(1);
956
957     // If all of the potentially set bits on one side are known to be set on
958     // the other side, just use the 'other' side.
959     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
960         (DemandedMask & (~RHSKnownZero)))
961       return I->getOperand(0);
962     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
963         (DemandedMask & (~LHSKnownZero)))
964       return I->getOperand(1);
965         
966     // If the RHS is a constant, see if we can simplify it.
967     if (ShrinkDemandedConstant(I, 1, DemandedMask))
968       return I;
969           
970     // Output known-0 bits are only known if clear in both the LHS & RHS.
971     RHSKnownZero &= LHSKnownZero;
972     // Output known-1 are known to be set if set in either the LHS | RHS.
973     RHSKnownOne |= LHSKnownOne;
974     break;
975   case Instruction::Xor: {
976     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
977                              RHSKnownZero, RHSKnownOne, Depth+1) ||
978         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
979                              LHSKnownZero, LHSKnownOne, Depth+1))
980       return I;
981     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
982     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
983     
984     // If all of the demanded bits are known zero on one side, return the other.
985     // These bits cannot contribute to the result of the 'xor'.
986     if ((DemandedMask & RHSKnownZero) == DemandedMask)
987       return I->getOperand(0);
988     if ((DemandedMask & LHSKnownZero) == DemandedMask)
989       return I->getOperand(1);
990     
991     // Output known-0 bits are known if clear or set in both the LHS & RHS.
992     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
993                          (RHSKnownOne & LHSKnownOne);
994     // Output known-1 are known to be set if set in only one of the LHS, RHS.
995     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
996                         (RHSKnownOne & LHSKnownZero);
997     
998     // If all of the demanded bits are known to be zero on one side or the
999     // other, turn this into an *inclusive* or.
1000     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1001     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1002       Instruction *Or =
1003         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1004                                  I->getName());
1005       return InsertNewInstBefore(Or, *I);
1006     }
1007     
1008     // If all of the demanded bits on one side are known, and all of the set
1009     // bits on that side are also known to be set on the other side, turn this
1010     // into an AND, as we know the bits will be cleared.
1011     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1012     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1013       // all known
1014       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1015         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1016         Instruction *And = 
1017           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1018         return InsertNewInstBefore(And, *I);
1019       }
1020     }
1021     
1022     // If the RHS is a constant, see if we can simplify it.
1023     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1024     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1025       return I;
1026     
1027     RHSKnownZero = KnownZeroOut;
1028     RHSKnownOne  = KnownOneOut;
1029     break;
1030   }
1031   case Instruction::Select:
1032     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1033                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1034         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1035                              LHSKnownZero, LHSKnownOne, Depth+1))
1036       return I;
1037     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1038     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1039     
1040     // If the operands are constants, see if we can simplify them.
1041     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1042         ShrinkDemandedConstant(I, 2, DemandedMask))
1043       return I;
1044     
1045     // Only known if known in both the LHS and RHS.
1046     RHSKnownOne &= LHSKnownOne;
1047     RHSKnownZero &= LHSKnownZero;
1048     break;
1049   case Instruction::Trunc: {
1050     unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1051     DemandedMask.zext(truncBf);
1052     RHSKnownZero.zext(truncBf);
1053     RHSKnownOne.zext(truncBf);
1054     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1055                              RHSKnownZero, RHSKnownOne, Depth+1))
1056       return I;
1057     DemandedMask.trunc(BitWidth);
1058     RHSKnownZero.trunc(BitWidth);
1059     RHSKnownOne.trunc(BitWidth);
1060     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1061     break;
1062   }
1063   case Instruction::BitCast:
1064     if (!I->getOperand(0)->getType()->isInteger())
1065       return false;  // vector->int or fp->int?
1066     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1067                              RHSKnownZero, RHSKnownOne, Depth+1))
1068       return I;
1069     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1070     break;
1071   case Instruction::ZExt: {
1072     // Compute the bits in the result that are not present in the input.
1073     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1074     
1075     DemandedMask.trunc(SrcBitWidth);
1076     RHSKnownZero.trunc(SrcBitWidth);
1077     RHSKnownOne.trunc(SrcBitWidth);
1078     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1079                              RHSKnownZero, RHSKnownOne, Depth+1))
1080       return I;
1081     DemandedMask.zext(BitWidth);
1082     RHSKnownZero.zext(BitWidth);
1083     RHSKnownOne.zext(BitWidth);
1084     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1085     // The top bits are known to be zero.
1086     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1087     break;
1088   }
1089   case Instruction::SExt: {
1090     // Compute the bits in the result that are not present in the input.
1091     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1092     
1093     APInt InputDemandedBits = DemandedMask & 
1094                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1095
1096     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1097     // If any of the sign extended bits are demanded, we know that the sign
1098     // bit is demanded.
1099     if ((NewBits & DemandedMask) != 0)
1100       InputDemandedBits.set(SrcBitWidth-1);
1101       
1102     InputDemandedBits.trunc(SrcBitWidth);
1103     RHSKnownZero.trunc(SrcBitWidth);
1104     RHSKnownOne.trunc(SrcBitWidth);
1105     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1106                              RHSKnownZero, RHSKnownOne, Depth+1))
1107       return I;
1108     InputDemandedBits.zext(BitWidth);
1109     RHSKnownZero.zext(BitWidth);
1110     RHSKnownOne.zext(BitWidth);
1111     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1112       
1113     // If the sign bit of the input is known set or clear, then we know the
1114     // top bits of the result.
1115
1116     // If the input sign bit is known zero, or if the NewBits are not demanded
1117     // convert this into a zero extension.
1118     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1119       // Convert to ZExt cast
1120       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1121       return InsertNewInstBefore(NewCast, *I);
1122     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1123       RHSKnownOne |= NewBits;
1124     }
1125     break;
1126   }
1127   case Instruction::Add: {
1128     // Figure out what the input bits are.  If the top bits of the and result
1129     // are not demanded, then the add doesn't demand them from its input
1130     // either.
1131     unsigned NLZ = DemandedMask.countLeadingZeros();
1132       
1133     // If there is a constant on the RHS, there are a variety of xformations
1134     // we can do.
1135     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1136       // If null, this should be simplified elsewhere.  Some of the xforms here
1137       // won't work if the RHS is zero.
1138       if (RHS->isZero())
1139         break;
1140       
1141       // If the top bit of the output is demanded, demand everything from the
1142       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1143       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1144
1145       // Find information about known zero/one bits in the input.
1146       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1147                                LHSKnownZero, LHSKnownOne, Depth+1))
1148         return I;
1149
1150       // If the RHS of the add has bits set that can't affect the input, reduce
1151       // the constant.
1152       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1153         return I;
1154       
1155       // Avoid excess work.
1156       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1157         break;
1158       
1159       // Turn it into OR if input bits are zero.
1160       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1161         Instruction *Or =
1162           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1163                                    I->getName());
1164         return InsertNewInstBefore(Or, *I);
1165       }
1166       
1167       // We can say something about the output known-zero and known-one bits,
1168       // depending on potential carries from the input constant and the
1169       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1170       // bits set and the RHS constant is 0x01001, then we know we have a known
1171       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1172       
1173       // To compute this, we first compute the potential carry bits.  These are
1174       // the bits which may be modified.  I'm not aware of a better way to do
1175       // this scan.
1176       const APInt &RHSVal = RHS->getValue();
1177       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1178       
1179       // Now that we know which bits have carries, compute the known-1/0 sets.
1180       
1181       // Bits are known one if they are known zero in one operand and one in the
1182       // other, and there is no input carry.
1183       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1184                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1185       
1186       // Bits are known zero if they are known zero in both operands and there
1187       // is no input carry.
1188       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1189     } else {
1190       // If the high-bits of this ADD are not demanded, then it does not demand
1191       // the high bits of its LHS or RHS.
1192       if (DemandedMask[BitWidth-1] == 0) {
1193         // Right fill the mask of bits for this ADD to demand the most
1194         // significant bit and all those below it.
1195         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1196         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1197                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1198             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1199                                  LHSKnownZero, LHSKnownOne, Depth+1))
1200           return I;
1201       }
1202     }
1203     break;
1204   }
1205   case Instruction::Sub:
1206     // If the high-bits of this SUB are not demanded, then it does not demand
1207     // the high bits of its LHS or RHS.
1208     if (DemandedMask[BitWidth-1] == 0) {
1209       // Right fill the mask of bits for this SUB to demand the most
1210       // significant bit and all those below it.
1211       uint32_t NLZ = DemandedMask.countLeadingZeros();
1212       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1213       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1214                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1215           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1216                                LHSKnownZero, LHSKnownOne, Depth+1))
1217         return I;
1218     }
1219     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1220     // the known zeros and ones.
1221     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1222     break;
1223   case Instruction::Shl:
1224     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1225       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1226       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1227       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1228                                RHSKnownZero, RHSKnownOne, Depth+1))
1229         return I;
1230       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1231       RHSKnownZero <<= ShiftAmt;
1232       RHSKnownOne  <<= ShiftAmt;
1233       // low bits known zero.
1234       if (ShiftAmt)
1235         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1236     }
1237     break;
1238   case Instruction::LShr:
1239     // For a logical shift right
1240     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1241       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1242       
1243       // Unsigned shift right.
1244       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1245       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1246                                RHSKnownZero, RHSKnownOne, Depth+1))
1247         return I;
1248       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1249       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1250       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1251       if (ShiftAmt) {
1252         // Compute the new bits that are at the top now.
1253         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1254         RHSKnownZero |= HighBits;  // high bits known zero.
1255       }
1256     }
1257     break;
1258   case Instruction::AShr:
1259     // If this is an arithmetic shift right and only the low-bit is set, we can
1260     // always convert this into a logical shr, even if the shift amount is
1261     // variable.  The low bit of the shift cannot be an input sign bit unless
1262     // the shift amount is >= the size of the datatype, which is undefined.
1263     if (DemandedMask == 1) {
1264       // Perform the logical shift right.
1265       Instruction *NewVal = BinaryOperator::CreateLShr(
1266                         I->getOperand(0), I->getOperand(1), I->getName());
1267       return InsertNewInstBefore(NewVal, *I);
1268     }    
1269
1270     // If the sign bit is the only bit demanded by this ashr, then there is no
1271     // need to do it, the shift doesn't change the high bit.
1272     if (DemandedMask.isSignBit())
1273       return I->getOperand(0);
1274     
1275     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1276       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1277       
1278       // Signed shift right.
1279       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1280       // If any of the "high bits" are demanded, we should set the sign bit as
1281       // demanded.
1282       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1283         DemandedMaskIn.set(BitWidth-1);
1284       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1285                                RHSKnownZero, RHSKnownOne, Depth+1))
1286         return I;
1287       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1288       // Compute the new bits that are at the top now.
1289       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1290       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1291       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1292         
1293       // Handle the sign bits.
1294       APInt SignBit(APInt::getSignBit(BitWidth));
1295       // Adjust to where it is now in the mask.
1296       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1297         
1298       // If the input sign bit is known to be zero, or if none of the top bits
1299       // are demanded, turn this into an unsigned shift right.
1300       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1301           (HighBits & ~DemandedMask) == HighBits) {
1302         // Perform the logical shift right.
1303         Instruction *NewVal = BinaryOperator::CreateLShr(
1304                           I->getOperand(0), SA, I->getName());
1305         return InsertNewInstBefore(NewVal, *I);
1306       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1307         RHSKnownOne |= HighBits;
1308       }
1309     }
1310     break;
1311   case Instruction::SRem:
1312     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1313       APInt RA = Rem->getValue().abs();
1314       if (RA.isPowerOf2()) {
1315         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1316           return I->getOperand(0);
1317
1318         APInt LowBits = RA - 1;
1319         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1320         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1321                                  LHSKnownZero, LHSKnownOne, Depth+1))
1322           return I;
1323
1324         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1325           LHSKnownZero |= ~LowBits;
1326
1327         KnownZero |= LHSKnownZero & DemandedMask;
1328
1329         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1330       }
1331     }
1332     break;
1333   case Instruction::URem: {
1334     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1335     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1336     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1337                              KnownZero2, KnownOne2, Depth+1) ||
1338         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1339                              KnownZero2, KnownOne2, Depth+1))
1340       return I;
1341
1342     unsigned Leaders = KnownZero2.countLeadingOnes();
1343     Leaders = std::max(Leaders,
1344                        KnownZero2.countLeadingOnes());
1345     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1346     break;
1347   }
1348   case Instruction::Call:
1349     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1350       switch (II->getIntrinsicID()) {
1351       default: break;
1352       case Intrinsic::bswap: {
1353         // If the only bits demanded come from one byte of the bswap result,
1354         // just shift the input byte into position to eliminate the bswap.
1355         unsigned NLZ = DemandedMask.countLeadingZeros();
1356         unsigned NTZ = DemandedMask.countTrailingZeros();
1357           
1358         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1359         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1360         // have 14 leading zeros, round to 8.
1361         NLZ &= ~7;
1362         NTZ &= ~7;
1363         // If we need exactly one byte, we can do this transformation.
1364         if (BitWidth-NLZ-NTZ == 8) {
1365           unsigned ResultBit = NTZ;
1366           unsigned InputBit = BitWidth-NTZ-8;
1367           
1368           // Replace this with either a left or right shift to get the byte into
1369           // the right place.
1370           Instruction *NewVal;
1371           if (InputBit > ResultBit)
1372             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1373                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1374           else
1375             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1376                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1377           NewVal->takeName(I);
1378           return InsertNewInstBefore(NewVal, *I);
1379         }
1380           
1381         // TODO: Could compute known zero/one bits based on the input.
1382         break;
1383       }
1384       }
1385     }
1386     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1387     break;
1388   }
1389   
1390   // If the client is only demanding bits that we know, return the known
1391   // constant.
1392   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1393     return ConstantInt::get(RHSKnownOne);
1394   return false;
1395 }
1396
1397
1398 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1399 /// any number of elements. DemandedElts contains the set of elements that are
1400 /// actually used by the caller.  This method analyzes which elements of the
1401 /// operand are undef and returns that information in UndefElts.
1402 ///
1403 /// If the information about demanded elements can be used to simplify the
1404 /// operation, the operation is simplified, then the resultant value is
1405 /// returned.  This returns null if no change was made.
1406 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1407                                                 APInt& UndefElts,
1408                                                 unsigned Depth) {
1409   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1410   APInt EltMask(APInt::getAllOnesValue(VWidth));
1411   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1412
1413   if (isa<UndefValue>(V)) {
1414     // If the entire vector is undefined, just return this info.
1415     UndefElts = EltMask;
1416     return 0;
1417   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1418     UndefElts = EltMask;
1419     return UndefValue::get(V->getType());
1420   }
1421
1422   UndefElts = 0;
1423   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1424     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1425     Constant *Undef = UndefValue::get(EltTy);
1426
1427     std::vector<Constant*> Elts;
1428     for (unsigned i = 0; i != VWidth; ++i)
1429       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1430         Elts.push_back(Undef);
1431         UndefElts.set(i);
1432       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1433         Elts.push_back(Undef);
1434         UndefElts.set(i);
1435       } else {                               // Otherwise, defined.
1436         Elts.push_back(CP->getOperand(i));
1437       }
1438
1439     // If we changed the constant, return it.
1440     Constant *NewCP = ConstantVector::get(Elts);
1441     return NewCP != CP ? NewCP : 0;
1442   } else if (isa<ConstantAggregateZero>(V)) {
1443     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1444     // set to undef.
1445     
1446     // Check if this is identity. If so, return 0 since we are not simplifying
1447     // anything.
1448     if (DemandedElts == ((1ULL << VWidth) -1))
1449       return 0;
1450     
1451     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1452     Constant *Zero = Constant::getNullValue(EltTy);
1453     Constant *Undef = UndefValue::get(EltTy);
1454     std::vector<Constant*> Elts;
1455     for (unsigned i = 0; i != VWidth; ++i) {
1456       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1457       Elts.push_back(Elt);
1458     }
1459     UndefElts = DemandedElts ^ EltMask;
1460     return ConstantVector::get(Elts);
1461   }
1462   
1463   // Limit search depth.
1464   if (Depth == 10)
1465     return false;
1466
1467   // If multiple users are using the root value, procede with
1468   // simplification conservatively assuming that all elements
1469   // are needed.
1470   if (!V->hasOneUse()) {
1471     // Quit if we find multiple users of a non-root value though.
1472     // They'll be handled when it's their turn to be visited by
1473     // the main instcombine process.
1474     if (Depth != 0)
1475       // TODO: Just compute the UndefElts information recursively.
1476       return false;
1477
1478     // Conservatively assume that all elements are needed.
1479     DemandedElts = EltMask;
1480   }
1481   
1482   Instruction *I = dyn_cast<Instruction>(V);
1483   if (!I) return false;        // Only analyze instructions.
1484   
1485   bool MadeChange = false;
1486   APInt UndefElts2(VWidth, 0);
1487   Value *TmpV;
1488   switch (I->getOpcode()) {
1489   default: break;
1490     
1491   case Instruction::InsertElement: {
1492     // If this is a variable index, we don't know which element it overwrites.
1493     // demand exactly the same input as we produce.
1494     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1495     if (Idx == 0) {
1496       // Note that we can't propagate undef elt info, because we don't know
1497       // which elt is getting updated.
1498       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1499                                         UndefElts2, Depth+1);
1500       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1501       break;
1502     }
1503     
1504     // If this is inserting an element that isn't demanded, remove this
1505     // insertelement.
1506     unsigned IdxNo = Idx->getZExtValue();
1507     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1508       return AddSoonDeadInstToWorklist(*I, 0);
1509     
1510     // Otherwise, the element inserted overwrites whatever was there, so the
1511     // input demanded set is simpler than the output set.
1512     APInt DemandedElts2 = DemandedElts;
1513     DemandedElts2.clear(IdxNo);
1514     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1515                                       UndefElts, Depth+1);
1516     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517
1518     // The inserted element is defined.
1519     UndefElts.clear(IdxNo);
1520     break;
1521   }
1522   case Instruction::ShuffleVector: {
1523     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1524     uint64_t LHSVWidth =
1525       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1526     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1527     for (unsigned i = 0; i < VWidth; i++) {
1528       if (DemandedElts[i]) {
1529         unsigned MaskVal = Shuffle->getMaskValue(i);
1530         if (MaskVal != -1u) {
1531           assert(MaskVal < LHSVWidth * 2 &&
1532                  "shufflevector mask index out of range!");
1533           if (MaskVal < LHSVWidth)
1534             LeftDemanded.set(MaskVal);
1535           else
1536             RightDemanded.set(MaskVal - LHSVWidth);
1537         }
1538       }
1539     }
1540
1541     APInt UndefElts4(LHSVWidth, 0);
1542     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1543                                       UndefElts4, Depth+1);
1544     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1545
1546     APInt UndefElts3(LHSVWidth, 0);
1547     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1548                                       UndefElts3, Depth+1);
1549     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1550
1551     bool NewUndefElts = false;
1552     for (unsigned i = 0; i < VWidth; i++) {
1553       unsigned MaskVal = Shuffle->getMaskValue(i);
1554       if (MaskVal == -1u) {
1555         UndefElts.set(i);
1556       } else if (MaskVal < LHSVWidth) {
1557         if (UndefElts4[MaskVal]) {
1558           NewUndefElts = true;
1559           UndefElts.set(i);
1560         }
1561       } else {
1562         if (UndefElts3[MaskVal - LHSVWidth]) {
1563           NewUndefElts = true;
1564           UndefElts.set(i);
1565         }
1566       }
1567     }
1568
1569     if (NewUndefElts) {
1570       // Add additional discovered undefs.
1571       std::vector<Constant*> Elts;
1572       for (unsigned i = 0; i < VWidth; ++i) {
1573         if (UndefElts[i])
1574           Elts.push_back(UndefValue::get(Type::Int32Ty));
1575         else
1576           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1577                                           Shuffle->getMaskValue(i)));
1578       }
1579       I->setOperand(2, ConstantVector::get(Elts));
1580       MadeChange = true;
1581     }
1582     break;
1583   }
1584   case Instruction::BitCast: {
1585     // Vector->vector casts only.
1586     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1587     if (!VTy) break;
1588     unsigned InVWidth = VTy->getNumElements();
1589     APInt InputDemandedElts(InVWidth, 0);
1590     unsigned Ratio;
1591
1592     if (VWidth == InVWidth) {
1593       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1594       // elements as are demanded of us.
1595       Ratio = 1;
1596       InputDemandedElts = DemandedElts;
1597     } else if (VWidth > InVWidth) {
1598       // Untested so far.
1599       break;
1600       
1601       // If there are more elements in the result than there are in the source,
1602       // then an input element is live if any of the corresponding output
1603       // elements are live.
1604       Ratio = VWidth/InVWidth;
1605       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1606         if (DemandedElts[OutIdx])
1607           InputDemandedElts.set(OutIdx/Ratio);
1608       }
1609     } else {
1610       // Untested so far.
1611       break;
1612       
1613       // If there are more elements in the source than there are in the result,
1614       // then an input element is live if the corresponding output element is
1615       // live.
1616       Ratio = InVWidth/VWidth;
1617       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1618         if (DemandedElts[InIdx/Ratio])
1619           InputDemandedElts.set(InIdx);
1620     }
1621     
1622     // div/rem demand all inputs, because they don't want divide by zero.
1623     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1624                                       UndefElts2, Depth+1);
1625     if (TmpV) {
1626       I->setOperand(0, TmpV);
1627       MadeChange = true;
1628     }
1629     
1630     UndefElts = UndefElts2;
1631     if (VWidth > InVWidth) {
1632       assert(0 && "Unimp");
1633       // If there are more elements in the result than there are in the source,
1634       // then an output element is undef if the corresponding input element is
1635       // undef.
1636       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1637         if (UndefElts2[OutIdx/Ratio])
1638           UndefElts.set(OutIdx);
1639     } else if (VWidth < InVWidth) {
1640       assert(0 && "Unimp");
1641       // If there are more elements in the source than there are in the result,
1642       // then a result element is undef if all of the corresponding input
1643       // elements are undef.
1644       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1645       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1646         if (!UndefElts2[InIdx])            // Not undef?
1647           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1648     }
1649     break;
1650   }
1651   case Instruction::And:
1652   case Instruction::Or:
1653   case Instruction::Xor:
1654   case Instruction::Add:
1655   case Instruction::Sub:
1656   case Instruction::Mul:
1657     // div/rem demand all inputs, because they don't want divide by zero.
1658     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1659                                       UndefElts, Depth+1);
1660     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1661     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1662                                       UndefElts2, Depth+1);
1663     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1664       
1665     // Output elements are undefined if both are undefined.  Consider things
1666     // like undef&0.  The result is known zero, not undef.
1667     UndefElts &= UndefElts2;
1668     break;
1669     
1670   case Instruction::Call: {
1671     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1672     if (!II) break;
1673     switch (II->getIntrinsicID()) {
1674     default: break;
1675       
1676     // Binary vector operations that work column-wise.  A dest element is a
1677     // function of the corresponding input elements from the two inputs.
1678     case Intrinsic::x86_sse_sub_ss:
1679     case Intrinsic::x86_sse_mul_ss:
1680     case Intrinsic::x86_sse_min_ss:
1681     case Intrinsic::x86_sse_max_ss:
1682     case Intrinsic::x86_sse2_sub_sd:
1683     case Intrinsic::x86_sse2_mul_sd:
1684     case Intrinsic::x86_sse2_min_sd:
1685     case Intrinsic::x86_sse2_max_sd:
1686       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1687                                         UndefElts, Depth+1);
1688       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1689       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1690                                         UndefElts2, Depth+1);
1691       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1692
1693       // If only the low elt is demanded and this is a scalarizable intrinsic,
1694       // scalarize it now.
1695       if (DemandedElts == 1) {
1696         switch (II->getIntrinsicID()) {
1697         default: break;
1698         case Intrinsic::x86_sse_sub_ss:
1699         case Intrinsic::x86_sse_mul_ss:
1700         case Intrinsic::x86_sse2_sub_sd:
1701         case Intrinsic::x86_sse2_mul_sd:
1702           // TODO: Lower MIN/MAX/ABS/etc
1703           Value *LHS = II->getOperand(1);
1704           Value *RHS = II->getOperand(2);
1705           // Extract the element as scalars.
1706           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1707           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1708           
1709           switch (II->getIntrinsicID()) {
1710           default: assert(0 && "Case stmts out of sync!");
1711           case Intrinsic::x86_sse_sub_ss:
1712           case Intrinsic::x86_sse2_sub_sd:
1713             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1714                                                         II->getName()), *II);
1715             break;
1716           case Intrinsic::x86_sse_mul_ss:
1717           case Intrinsic::x86_sse2_mul_sd:
1718             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1719                                                          II->getName()), *II);
1720             break;
1721           }
1722           
1723           Instruction *New =
1724             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1725                                       II->getName());
1726           InsertNewInstBefore(New, *II);
1727           AddSoonDeadInstToWorklist(*II, 0);
1728           return New;
1729         }            
1730       }
1731         
1732       // Output elements are undefined if both are undefined.  Consider things
1733       // like undef&0.  The result is known zero, not undef.
1734       UndefElts &= UndefElts2;
1735       break;
1736     }
1737     break;
1738   }
1739   }
1740   return MadeChange ? I : 0;
1741 }
1742
1743
1744 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1745 /// function is designed to check a chain of associative operators for a
1746 /// potential to apply a certain optimization.  Since the optimization may be
1747 /// applicable if the expression was reassociated, this checks the chain, then
1748 /// reassociates the expression as necessary to expose the optimization
1749 /// opportunity.  This makes use of a special Functor, which must define
1750 /// 'shouldApply' and 'apply' methods.
1751 ///
1752 template<typename Functor>
1753 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1754   unsigned Opcode = Root.getOpcode();
1755   Value *LHS = Root.getOperand(0);
1756
1757   // Quick check, see if the immediate LHS matches...
1758   if (F.shouldApply(LHS))
1759     return F.apply(Root);
1760
1761   // Otherwise, if the LHS is not of the same opcode as the root, return.
1762   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1763   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1764     // Should we apply this transform to the RHS?
1765     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1766
1767     // If not to the RHS, check to see if we should apply to the LHS...
1768     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1769       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1770       ShouldApply = true;
1771     }
1772
1773     // If the functor wants to apply the optimization to the RHS of LHSI,
1774     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1775     if (ShouldApply) {
1776       // Now all of the instructions are in the current basic block, go ahead
1777       // and perform the reassociation.
1778       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1779
1780       // First move the selected RHS to the LHS of the root...
1781       Root.setOperand(0, LHSI->getOperand(1));
1782
1783       // Make what used to be the LHS of the root be the user of the root...
1784       Value *ExtraOperand = TmpLHSI->getOperand(1);
1785       if (&Root == TmpLHSI) {
1786         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1787         return 0;
1788       }
1789       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1790       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1791       BasicBlock::iterator ARI = &Root; ++ARI;
1792       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1793       ARI = Root;
1794
1795       // Now propagate the ExtraOperand down the chain of instructions until we
1796       // get to LHSI.
1797       while (TmpLHSI != LHSI) {
1798         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1799         // Move the instruction to immediately before the chain we are
1800         // constructing to avoid breaking dominance properties.
1801         NextLHSI->moveBefore(ARI);
1802         ARI = NextLHSI;
1803
1804         Value *NextOp = NextLHSI->getOperand(1);
1805         NextLHSI->setOperand(1, ExtraOperand);
1806         TmpLHSI = NextLHSI;
1807         ExtraOperand = NextOp;
1808       }
1809
1810       // Now that the instructions are reassociated, have the functor perform
1811       // the transformation...
1812       return F.apply(Root);
1813     }
1814
1815     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1816   }
1817   return 0;
1818 }
1819
1820 namespace {
1821
1822 // AddRHS - Implements: X + X --> X << 1
1823 struct AddRHS {
1824   Value *RHS;
1825   AddRHS(Value *rhs) : RHS(rhs) {}
1826   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1827   Instruction *apply(BinaryOperator &Add) const {
1828     return BinaryOperator::CreateShl(Add.getOperand(0),
1829                                      ConstantInt::get(Add.getType(), 1));
1830   }
1831 };
1832
1833 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1834 //                 iff C1&C2 == 0
1835 struct AddMaskingAnd {
1836   Constant *C2;
1837   AddMaskingAnd(Constant *c) : C2(c) {}
1838   bool shouldApply(Value *LHS) const {
1839     ConstantInt *C1;
1840     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1841            ConstantExpr::getAnd(C1, C2)->isNullValue();
1842   }
1843   Instruction *apply(BinaryOperator &Add) const {
1844     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1845   }
1846 };
1847
1848 }
1849
1850 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1851                                              InstCombiner *IC) {
1852   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1853     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1854   }
1855
1856   // Figure out if the constant is the left or the right argument.
1857   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1858   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1859
1860   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1861     if (ConstIsRHS)
1862       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1863     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1864   }
1865
1866   Value *Op0 = SO, *Op1 = ConstOperand;
1867   if (!ConstIsRHS)
1868     std::swap(Op0, Op1);
1869   Instruction *New;
1870   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1871     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1872   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1873     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1874                           SO->getName()+".cmp");
1875   else {
1876     assert(0 && "Unknown binary instruction type!");
1877     abort();
1878   }
1879   return IC->InsertNewInstBefore(New, I);
1880 }
1881
1882 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1883 // constant as the other operand, try to fold the binary operator into the
1884 // select arguments.  This also works for Cast instructions, which obviously do
1885 // not have a second operand.
1886 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1887                                      InstCombiner *IC) {
1888   // Don't modify shared select instructions
1889   if (!SI->hasOneUse()) return 0;
1890   Value *TV = SI->getOperand(1);
1891   Value *FV = SI->getOperand(2);
1892
1893   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1894     // Bool selects with constant operands can be folded to logical ops.
1895     if (SI->getType() == Type::Int1Ty) return 0;
1896
1897     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1898     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1899
1900     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1901                               SelectFalseVal);
1902   }
1903   return 0;
1904 }
1905
1906
1907 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1908 /// node as operand #0, see if we can fold the instruction into the PHI (which
1909 /// is only possible if all operands to the PHI are constants).
1910 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1911   PHINode *PN = cast<PHINode>(I.getOperand(0));
1912   unsigned NumPHIValues = PN->getNumIncomingValues();
1913   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1914
1915   // Check to see if all of the operands of the PHI are constants.  If there is
1916   // one non-constant value, remember the BB it is.  If there is more than one
1917   // or if *it* is a PHI, bail out.
1918   BasicBlock *NonConstBB = 0;
1919   for (unsigned i = 0; i != NumPHIValues; ++i)
1920     if (!isa<Constant>(PN->getIncomingValue(i))) {
1921       if (NonConstBB) return 0;  // More than one non-const value.
1922       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1923       NonConstBB = PN->getIncomingBlock(i);
1924       
1925       // If the incoming non-constant value is in I's block, we have an infinite
1926       // loop.
1927       if (NonConstBB == I.getParent())
1928         return 0;
1929     }
1930   
1931   // If there is exactly one non-constant value, we can insert a copy of the
1932   // operation in that block.  However, if this is a critical edge, we would be
1933   // inserting the computation one some other paths (e.g. inside a loop).  Only
1934   // do this if the pred block is unconditionally branching into the phi block.
1935   if (NonConstBB) {
1936     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1937     if (!BI || !BI->isUnconditional()) return 0;
1938   }
1939
1940   // Okay, we can do the transformation: create the new PHI node.
1941   PHINode *NewPN = PHINode::Create(I.getType(), "");
1942   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1943   InsertNewInstBefore(NewPN, *PN);
1944   NewPN->takeName(PN);
1945
1946   // Next, add all of the operands to the PHI.
1947   if (I.getNumOperands() == 2) {
1948     Constant *C = cast<Constant>(I.getOperand(1));
1949     for (unsigned i = 0; i != NumPHIValues; ++i) {
1950       Value *InV = 0;
1951       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1952         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1953           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1954         else
1955           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1956       } else {
1957         assert(PN->getIncomingBlock(i) == NonConstBB);
1958         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1959           InV = BinaryOperator::Create(BO->getOpcode(),
1960                                        PN->getIncomingValue(i), C, "phitmp",
1961                                        NonConstBB->getTerminator());
1962         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1963           InV = CmpInst::Create(CI->getOpcode(), 
1964                                 CI->getPredicate(),
1965                                 PN->getIncomingValue(i), C, "phitmp",
1966                                 NonConstBB->getTerminator());
1967         else
1968           assert(0 && "Unknown binop!");
1969         
1970         AddToWorkList(cast<Instruction>(InV));
1971       }
1972       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1973     }
1974   } else { 
1975     CastInst *CI = cast<CastInst>(&I);
1976     const Type *RetTy = CI->getType();
1977     for (unsigned i = 0; i != NumPHIValues; ++i) {
1978       Value *InV;
1979       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1980         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1981       } else {
1982         assert(PN->getIncomingBlock(i) == NonConstBB);
1983         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1984                                I.getType(), "phitmp", 
1985                                NonConstBB->getTerminator());
1986         AddToWorkList(cast<Instruction>(InV));
1987       }
1988       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1989     }
1990   }
1991   return ReplaceInstUsesWith(I, NewPN);
1992 }
1993
1994
1995 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1996 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1997 /// This basically requires proving that the add in the original type would not
1998 /// overflow to change the sign bit or have a carry out.
1999 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2000   // There are different heuristics we can use for this.  Here are some simple
2001   // ones.
2002   
2003   // Add has the property that adding any two 2's complement numbers can only 
2004   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2005   // have at least two sign bits, we know that the addition of the two values will
2006   // sign extend fine.
2007   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2008     return true;
2009   
2010   
2011   // If one of the operands only has one non-zero bit, and if the other operand
2012   // has a known-zero bit in a more significant place than it (not including the
2013   // sign bit) the ripple may go up to and fill the zero, but won't change the
2014   // sign.  For example, (X & ~4) + 1.
2015   
2016   // TODO: Implement.
2017   
2018   return false;
2019 }
2020
2021
2022 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2023   bool Changed = SimplifyCommutative(I);
2024   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2025
2026   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2027     // X + undef -> undef
2028     if (isa<UndefValue>(RHS))
2029       return ReplaceInstUsesWith(I, RHS);
2030
2031     // X + 0 --> X
2032     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2033       if (RHSC->isNullValue())
2034         return ReplaceInstUsesWith(I, LHS);
2035     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2036       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2037                               (I.getType())->getValueAPF()))
2038         return ReplaceInstUsesWith(I, LHS);
2039     }
2040
2041     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2042       // X + (signbit) --> X ^ signbit
2043       const APInt& Val = CI->getValue();
2044       uint32_t BitWidth = Val.getBitWidth();
2045       if (Val == APInt::getSignBit(BitWidth))
2046         return BinaryOperator::CreateXor(LHS, RHS);
2047       
2048       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2049       // (X & 254)+1 -> (X&254)|1
2050       if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2051         return &I;
2052
2053       // zext(i1) - 1  ->  select i1, 0, -1
2054       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2055         if (CI->isAllOnesValue() &&
2056             ZI->getOperand(0)->getType() == Type::Int1Ty)
2057           return SelectInst::Create(ZI->getOperand(0),
2058                                     Constant::getNullValue(I.getType()),
2059                                     ConstantInt::getAllOnesValue(I.getType()));
2060     }
2061
2062     if (isa<PHINode>(LHS))
2063       if (Instruction *NV = FoldOpIntoPhi(I))
2064         return NV;
2065     
2066     ConstantInt *XorRHS = 0;
2067     Value *XorLHS = 0;
2068     if (isa<ConstantInt>(RHSC) &&
2069         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2070       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2071       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2072       
2073       uint32_t Size = TySizeBits / 2;
2074       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2075       APInt CFF80Val(-C0080Val);
2076       do {
2077         if (TySizeBits > Size) {
2078           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2079           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2080           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2081               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2082             // This is a sign extend if the top bits are known zero.
2083             if (!MaskedValueIsZero(XorLHS, 
2084                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2085               Size = 0;  // Not a sign ext, but can't be any others either.
2086             break;
2087           }
2088         }
2089         Size >>= 1;
2090         C0080Val = APIntOps::lshr(C0080Val, Size);
2091         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2092       } while (Size >= 1);
2093       
2094       // FIXME: This shouldn't be necessary. When the backends can handle types
2095       // with funny bit widths then this switch statement should be removed. It
2096       // is just here to get the size of the "middle" type back up to something
2097       // that the back ends can handle.
2098       const Type *MiddleType = 0;
2099       switch (Size) {
2100         default: break;
2101         case 32: MiddleType = Type::Int32Ty; break;
2102         case 16: MiddleType = Type::Int16Ty; break;
2103         case  8: MiddleType = Type::Int8Ty; break;
2104       }
2105       if (MiddleType) {
2106         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2107         InsertNewInstBefore(NewTrunc, I);
2108         return new SExtInst(NewTrunc, I.getType(), I.getName());
2109       }
2110     }
2111   }
2112
2113   if (I.getType() == Type::Int1Ty)
2114     return BinaryOperator::CreateXor(LHS, RHS);
2115
2116   // X + X --> X << 1
2117   if (I.getType()->isInteger()) {
2118     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2119
2120     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2121       if (RHSI->getOpcode() == Instruction::Sub)
2122         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2123           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2124     }
2125     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2126       if (LHSI->getOpcode() == Instruction::Sub)
2127         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2128           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2129     }
2130   }
2131
2132   // -A + B  -->  B - A
2133   // -A + -B  -->  -(A + B)
2134   if (Value *LHSV = dyn_castNegVal(LHS)) {
2135     if (LHS->getType()->isIntOrIntVector()) {
2136       if (Value *RHSV = dyn_castNegVal(RHS)) {
2137         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2138         InsertNewInstBefore(NewAdd, I);
2139         return BinaryOperator::CreateNeg(NewAdd);
2140       }
2141     }
2142     
2143     return BinaryOperator::CreateSub(RHS, LHSV);
2144   }
2145
2146   // A + -B  -->  A - B
2147   if (!isa<Constant>(RHS))
2148     if (Value *V = dyn_castNegVal(RHS))
2149       return BinaryOperator::CreateSub(LHS, V);
2150
2151
2152   ConstantInt *C2;
2153   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2154     if (X == RHS)   // X*C + X --> X * (C+1)
2155       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2156
2157     // X*C1 + X*C2 --> X * (C1+C2)
2158     ConstantInt *C1;
2159     if (X == dyn_castFoldableMul(RHS, C1))
2160       return BinaryOperator::CreateMul(X, Add(C1, C2));
2161   }
2162
2163   // X + X*C --> X * (C+1)
2164   if (dyn_castFoldableMul(RHS, C2) == LHS)
2165     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2166
2167   // X + ~X --> -1   since   ~X = -X-1
2168   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2169     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2170   
2171
2172   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2173   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2174     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2175       return R;
2176   
2177   // A+B --> A|B iff A and B have no bits set in common.
2178   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2179     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2180     APInt LHSKnownOne(IT->getBitWidth(), 0);
2181     APInt LHSKnownZero(IT->getBitWidth(), 0);
2182     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2183     if (LHSKnownZero != 0) {
2184       APInt RHSKnownOne(IT->getBitWidth(), 0);
2185       APInt RHSKnownZero(IT->getBitWidth(), 0);
2186       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2187       
2188       // No bits in common -> bitwise or.
2189       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2190         return BinaryOperator::CreateOr(LHS, RHS);
2191     }
2192   }
2193
2194   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2195   if (I.getType()->isIntOrIntVector()) {
2196     Value *W, *X, *Y, *Z;
2197     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2198         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2199       if (W != Y) {
2200         if (W == Z) {
2201           std::swap(Y, Z);
2202         } else if (Y == X) {
2203           std::swap(W, X);
2204         } else if (X == Z) {
2205           std::swap(Y, Z);
2206           std::swap(W, X);
2207         }
2208       }
2209
2210       if (W == Y) {
2211         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2212                                                             LHS->getName()), I);
2213         return BinaryOperator::CreateMul(W, NewAdd);
2214       }
2215     }
2216   }
2217
2218   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2219     Value *X = 0;
2220     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2221       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2222
2223     // (X & FF00) + xx00  -> (X+xx00) & FF00
2224     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2225       Constant *Anded = And(CRHS, C2);
2226       if (Anded == CRHS) {
2227         // See if all bits from the first bit set in the Add RHS up are included
2228         // in the mask.  First, get the rightmost bit.
2229         const APInt& AddRHSV = CRHS->getValue();
2230
2231         // Form a mask of all bits from the lowest bit added through the top.
2232         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2233
2234         // See if the and mask includes all of these bits.
2235         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2236
2237         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2238           // Okay, the xform is safe.  Insert the new add pronto.
2239           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2240                                                             LHS->getName()), I);
2241           return BinaryOperator::CreateAnd(NewAdd, C2);
2242         }
2243       }
2244     }
2245
2246     // Try to fold constant add into select arguments.
2247     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2248       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2249         return R;
2250   }
2251
2252   // add (cast *A to intptrtype) B -> 
2253   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2254   {
2255     CastInst *CI = dyn_cast<CastInst>(LHS);
2256     Value *Other = RHS;
2257     if (!CI) {
2258       CI = dyn_cast<CastInst>(RHS);
2259       Other = LHS;
2260     }
2261     if (CI && CI->getType()->isSized() && 
2262         (CI->getType()->getPrimitiveSizeInBits() == 
2263          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2264         && isa<PointerType>(CI->getOperand(0)->getType())) {
2265       unsigned AS =
2266         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2267       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2268                                       PointerType::get(Type::Int8Ty, AS), I);
2269       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2270       return new PtrToIntInst(I2, CI->getType());
2271     }
2272   }
2273   
2274   // add (select X 0 (sub n A)) A  -->  select X A n
2275   {
2276     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2277     Value *A = RHS;
2278     if (!SI) {
2279       SI = dyn_cast<SelectInst>(RHS);
2280       A = LHS;
2281     }
2282     if (SI && SI->hasOneUse()) {
2283       Value *TV = SI->getTrueValue();
2284       Value *FV = SI->getFalseValue();
2285       Value *N;
2286
2287       // Can we fold the add into the argument of the select?
2288       // We check both true and false select arguments for a matching subtract.
2289       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2290         // Fold the add into the true select value.
2291         return SelectInst::Create(SI->getCondition(), N, A);
2292       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2293         // Fold the add into the false select value.
2294         return SelectInst::Create(SI->getCondition(), A, N);
2295     }
2296   }
2297   
2298   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2299   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2300     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2301       return ReplaceInstUsesWith(I, LHS);
2302
2303   // Check for (add (sext x), y), see if we can merge this into an
2304   // integer add followed by a sext.
2305   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2306     // (add (sext x), cst) --> (sext (add x, cst'))
2307     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2308       Constant *CI = 
2309         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2310       if (LHSConv->hasOneUse() &&
2311           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2312           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2313         // Insert the new, smaller add.
2314         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2315                                                         CI, "addconv");
2316         InsertNewInstBefore(NewAdd, I);
2317         return new SExtInst(NewAdd, I.getType());
2318       }
2319     }
2320     
2321     // (add (sext x), (sext y)) --> (sext (add int x, y))
2322     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2323       // Only do this if x/y have the same type, if at last one of them has a
2324       // single use (so we don't increase the number of sexts), and if the
2325       // integer add will not overflow.
2326       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2327           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2328           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2329                                    RHSConv->getOperand(0))) {
2330         // Insert the new integer add.
2331         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2332                                                         RHSConv->getOperand(0),
2333                                                         "addconv");
2334         InsertNewInstBefore(NewAdd, I);
2335         return new SExtInst(NewAdd, I.getType());
2336       }
2337     }
2338   }
2339   
2340   // Check for (add double (sitofp x), y), see if we can merge this into an
2341   // integer add followed by a promotion.
2342   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2343     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2344     // ... if the constant fits in the integer value.  This is useful for things
2345     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2346     // requires a constant pool load, and generally allows the add to be better
2347     // instcombined.
2348     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2349       Constant *CI = 
2350       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2351       if (LHSConv->hasOneUse() &&
2352           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2353           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2354         // Insert the new integer add.
2355         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2356                                                         CI, "addconv");
2357         InsertNewInstBefore(NewAdd, I);
2358         return new SIToFPInst(NewAdd, I.getType());
2359       }
2360     }
2361     
2362     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2363     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2364       // Only do this if x/y have the same type, if at last one of them has a
2365       // single use (so we don't increase the number of int->fp conversions),
2366       // and if the integer add will not overflow.
2367       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2368           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2369           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2370                                    RHSConv->getOperand(0))) {
2371         // Insert the new integer add.
2372         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2373                                                         RHSConv->getOperand(0),
2374                                                         "addconv");
2375         InsertNewInstBefore(NewAdd, I);
2376         return new SIToFPInst(NewAdd, I.getType());
2377       }
2378     }
2379   }
2380   
2381   return Changed ? &I : 0;
2382 }
2383
2384 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2385   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2386
2387   if (Op0 == Op1 &&                        // sub X, X  -> 0
2388       !I.getType()->isFPOrFPVector())
2389     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2390
2391   // If this is a 'B = x-(-A)', change to B = x+A...
2392   if (Value *V = dyn_castNegVal(Op1))
2393     return BinaryOperator::CreateAdd(Op0, V);
2394
2395   if (isa<UndefValue>(Op0))
2396     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2397   if (isa<UndefValue>(Op1))
2398     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2399
2400   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2401     // Replace (-1 - A) with (~A)...
2402     if (C->isAllOnesValue())
2403       return BinaryOperator::CreateNot(Op1);
2404
2405     // C - ~X == X + (1+C)
2406     Value *X = 0;
2407     if (match(Op1, m_Not(m_Value(X))))
2408       return BinaryOperator::CreateAdd(X, AddOne(C));
2409
2410     // -(X >>u 31) -> (X >>s 31)
2411     // -(X >>s 31) -> (X >>u 31)
2412     if (C->isZero()) {
2413       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2414         if (SI->getOpcode() == Instruction::LShr) {
2415           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2416             // Check to see if we are shifting out everything but the sign bit.
2417             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2418                 SI->getType()->getPrimitiveSizeInBits()-1) {
2419               // Ok, the transformation is safe.  Insert AShr.
2420               return BinaryOperator::Create(Instruction::AShr, 
2421                                           SI->getOperand(0), CU, SI->getName());
2422             }
2423           }
2424         }
2425         else if (SI->getOpcode() == Instruction::AShr) {
2426           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2427             // Check to see if we are shifting out everything but the sign bit.
2428             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2429                 SI->getType()->getPrimitiveSizeInBits()-1) {
2430               // Ok, the transformation is safe.  Insert LShr. 
2431               return BinaryOperator::CreateLShr(
2432                                           SI->getOperand(0), CU, SI->getName());
2433             }
2434           }
2435         }
2436       }
2437     }
2438
2439     // Try to fold constant sub into select arguments.
2440     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2441       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2442         return R;
2443   }
2444
2445   if (I.getType() == Type::Int1Ty)
2446     return BinaryOperator::CreateXor(Op0, Op1);
2447
2448   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2449     if (Op1I->getOpcode() == Instruction::Add &&
2450         !Op0->getType()->isFPOrFPVector()) {
2451       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2452         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2453       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2454         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2455       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2456         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2457           // C1-(X+C2) --> (C1-C2)-X
2458           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2459                                            Op1I->getOperand(0));
2460       }
2461     }
2462
2463     if (Op1I->hasOneUse()) {
2464       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2465       // is not used by anyone else...
2466       //
2467       if (Op1I->getOpcode() == Instruction::Sub &&
2468           !Op1I->getType()->isFPOrFPVector()) {
2469         // Swap the two operands of the subexpr...
2470         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2471         Op1I->setOperand(0, IIOp1);
2472         Op1I->setOperand(1, IIOp0);
2473
2474         // Create the new top level add instruction...
2475         return BinaryOperator::CreateAdd(Op0, Op1);
2476       }
2477
2478       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2479       //
2480       if (Op1I->getOpcode() == Instruction::And &&
2481           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2482         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2483
2484         Value *NewNot =
2485           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2486         return BinaryOperator::CreateAnd(Op0, NewNot);
2487       }
2488
2489       // 0 - (X sdiv C)  -> (X sdiv -C)
2490       if (Op1I->getOpcode() == Instruction::SDiv)
2491         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2492           if (CSI->isZero())
2493             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2494               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2495                                                ConstantExpr::getNeg(DivRHS));
2496
2497       // X - X*C --> X * (1-C)
2498       ConstantInt *C2 = 0;
2499       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2500         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2501         return BinaryOperator::CreateMul(Op0, CP1);
2502       }
2503     }
2504   }
2505
2506   if (!Op0->getType()->isFPOrFPVector())
2507     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2508       if (Op0I->getOpcode() == Instruction::Add) {
2509         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2510           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2511         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2512           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2513       } else if (Op0I->getOpcode() == Instruction::Sub) {
2514         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2515           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2516       }
2517     }
2518
2519   ConstantInt *C1;
2520   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2521     if (X == Op1)  // X*C - X --> X * (C-1)
2522       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2523
2524     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2525     if (X == dyn_castFoldableMul(Op1, C2))
2526       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2527   }
2528   return 0;
2529 }
2530
2531 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2532 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2533 /// TrueIfSigned if the result of the comparison is true when the input value is
2534 /// signed.
2535 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2536                            bool &TrueIfSigned) {
2537   switch (pred) {
2538   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2539     TrueIfSigned = true;
2540     return RHS->isZero();
2541   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2542     TrueIfSigned = true;
2543     return RHS->isAllOnesValue();
2544   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2545     TrueIfSigned = false;
2546     return RHS->isAllOnesValue();
2547   case ICmpInst::ICMP_UGT:
2548     // True if LHS u> RHS and RHS == high-bit-mask - 1
2549     TrueIfSigned = true;
2550     return RHS->getValue() ==
2551       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2552   case ICmpInst::ICMP_UGE: 
2553     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2554     TrueIfSigned = true;
2555     return RHS->getValue().isSignBit();
2556   default:
2557     return false;
2558   }
2559 }
2560
2561 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2562   bool Changed = SimplifyCommutative(I);
2563   Value *Op0 = I.getOperand(0);
2564
2565   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2566     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2567
2568   // Simplify mul instructions with a constant RHS...
2569   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2570     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2571
2572       // ((X << C1)*C2) == (X * (C2 << C1))
2573       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2574         if (SI->getOpcode() == Instruction::Shl)
2575           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2576             return BinaryOperator::CreateMul(SI->getOperand(0),
2577                                              ConstantExpr::getShl(CI, ShOp));
2578
2579       if (CI->isZero())
2580         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2581       if (CI->equalsInt(1))                  // X * 1  == X
2582         return ReplaceInstUsesWith(I, Op0);
2583       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2584         return BinaryOperator::CreateNeg(Op0, I.getName());
2585
2586       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2587       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2588         return BinaryOperator::CreateShl(Op0,
2589                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2590       }
2591     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2592       if (Op1F->isNullValue())
2593         return ReplaceInstUsesWith(I, Op1);
2594
2595       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2596       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2597       if (Op1F->isExactlyValue(1.0))
2598         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2599     } else if (isa<VectorType>(Op1->getType())) {
2600       if (isa<ConstantAggregateZero>(Op1))
2601         return ReplaceInstUsesWith(I, Op1);
2602
2603       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2604         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2605           return BinaryOperator::CreateNeg(Op0, I.getName());
2606
2607         // As above, vector X*splat(1.0) -> X in all defined cases.
2608         if (Constant *Splat = Op1V->getSplatValue()) {
2609           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2610             if (F->isExactlyValue(1.0))
2611               return ReplaceInstUsesWith(I, Op0);
2612           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2613             if (CI->equalsInt(1))
2614               return ReplaceInstUsesWith(I, Op0);
2615         }
2616       }
2617     }
2618     
2619     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2620       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2621           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2622         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2623         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2624                                                      Op1, "tmp");
2625         InsertNewInstBefore(Add, I);
2626         Value *C1C2 = ConstantExpr::getMul(Op1, 
2627                                            cast<Constant>(Op0I->getOperand(1)));
2628         return BinaryOperator::CreateAdd(Add, C1C2);
2629         
2630       }
2631
2632     // Try to fold constant mul into select arguments.
2633     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2634       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2635         return R;
2636
2637     if (isa<PHINode>(Op0))
2638       if (Instruction *NV = FoldOpIntoPhi(I))
2639         return NV;
2640   }
2641
2642   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2643     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2644       return BinaryOperator::CreateMul(Op0v, Op1v);
2645
2646   // (X / Y) *  Y = X - (X % Y)
2647   // (X / Y) * -Y = (X % Y) - X
2648   {
2649     Value *Op1 = I.getOperand(1);
2650     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2651     if (!BO ||
2652         (BO->getOpcode() != Instruction::UDiv && 
2653          BO->getOpcode() != Instruction::SDiv)) {
2654       Op1 = Op0;
2655       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2656     }
2657     Value *Neg = dyn_castNegVal(Op1);
2658     if (BO && BO->hasOneUse() &&
2659         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2660         (BO->getOpcode() == Instruction::UDiv ||
2661          BO->getOpcode() == Instruction::SDiv)) {
2662       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2663
2664       Instruction *Rem;
2665       if (BO->getOpcode() == Instruction::UDiv)
2666         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2667       else
2668         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2669
2670       InsertNewInstBefore(Rem, I);
2671       Rem->takeName(BO);
2672
2673       if (Op1BO == Op1)
2674         return BinaryOperator::CreateSub(Op0BO, Rem);
2675       else
2676         return BinaryOperator::CreateSub(Rem, Op0BO);
2677     }
2678   }
2679
2680   if (I.getType() == Type::Int1Ty)
2681     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2682
2683   // If one of the operands of the multiply is a cast from a boolean value, then
2684   // we know the bool is either zero or one, so this is a 'masking' multiply.
2685   // See if we can simplify things based on how the boolean was originally
2686   // formed.
2687   CastInst *BoolCast = 0;
2688   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2689     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2690       BoolCast = CI;
2691   if (!BoolCast)
2692     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2693       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2694         BoolCast = CI;
2695   if (BoolCast) {
2696     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2697       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2698       const Type *SCOpTy = SCIOp0->getType();
2699       bool TIS = false;
2700       
2701       // If the icmp is true iff the sign bit of X is set, then convert this
2702       // multiply into a shift/and combination.
2703       if (isa<ConstantInt>(SCIOp1) &&
2704           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2705           TIS) {
2706         // Shift the X value right to turn it into "all signbits".
2707         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2708                                           SCOpTy->getPrimitiveSizeInBits()-1);
2709         Value *V =
2710           InsertNewInstBefore(
2711             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2712                                             BoolCast->getOperand(0)->getName()+
2713                                             ".mask"), I);
2714
2715         // If the multiply type is not the same as the source type, sign extend
2716         // or truncate to the multiply type.
2717         if (I.getType() != V->getType()) {
2718           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2719           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2720           Instruction::CastOps opcode = 
2721             (SrcBits == DstBits ? Instruction::BitCast : 
2722              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2723           V = InsertCastBefore(opcode, V, I.getType(), I);
2724         }
2725
2726         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2727         return BinaryOperator::CreateAnd(V, OtherOp);
2728       }
2729     }
2730   }
2731
2732   return Changed ? &I : 0;
2733 }
2734
2735 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2736 /// instruction.
2737 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2738   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2739   
2740   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2741   int NonNullOperand = -1;
2742   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2743     if (ST->isNullValue())
2744       NonNullOperand = 2;
2745   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2746   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2747     if (ST->isNullValue())
2748       NonNullOperand = 1;
2749   
2750   if (NonNullOperand == -1)
2751     return false;
2752   
2753   Value *SelectCond = SI->getOperand(0);
2754   
2755   // Change the div/rem to use 'Y' instead of the select.
2756   I.setOperand(1, SI->getOperand(NonNullOperand));
2757   
2758   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2759   // problem.  However, the select, or the condition of the select may have
2760   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2761   // propagate the known value for the select into other uses of it, and
2762   // propagate a known value of the condition into its other users.
2763   
2764   // If the select and condition only have a single use, don't bother with this,
2765   // early exit.
2766   if (SI->use_empty() && SelectCond->hasOneUse())
2767     return true;
2768   
2769   // Scan the current block backward, looking for other uses of SI.
2770   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2771   
2772   while (BBI != BBFront) {
2773     --BBI;
2774     // If we found a call to a function, we can't assume it will return, so
2775     // information from below it cannot be propagated above it.
2776     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2777       break;
2778     
2779     // Replace uses of the select or its condition with the known values.
2780     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2781          I != E; ++I) {
2782       if (*I == SI) {
2783         *I = SI->getOperand(NonNullOperand);
2784         AddToWorkList(BBI);
2785       } else if (*I == SelectCond) {
2786         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2787                                    ConstantInt::getFalse();
2788         AddToWorkList(BBI);
2789       }
2790     }
2791     
2792     // If we past the instruction, quit looking for it.
2793     if (&*BBI == SI)
2794       SI = 0;
2795     if (&*BBI == SelectCond)
2796       SelectCond = 0;
2797     
2798     // If we ran out of things to eliminate, break out of the loop.
2799     if (SelectCond == 0 && SI == 0)
2800       break;
2801     
2802   }
2803   return true;
2804 }
2805
2806
2807 /// This function implements the transforms on div instructions that work
2808 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2809 /// used by the visitors to those instructions.
2810 /// @brief Transforms common to all three div instructions
2811 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2812   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2813
2814   // undef / X -> 0        for integer.
2815   // undef / X -> undef    for FP (the undef could be a snan).
2816   if (isa<UndefValue>(Op0)) {
2817     if (Op0->getType()->isFPOrFPVector())
2818       return ReplaceInstUsesWith(I, Op0);
2819     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2820   }
2821
2822   // X / undef -> undef
2823   if (isa<UndefValue>(Op1))
2824     return ReplaceInstUsesWith(I, Op1);
2825
2826   return 0;
2827 }
2828
2829 /// This function implements the transforms common to both integer division
2830 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2831 /// division instructions.
2832 /// @brief Common integer divide transforms
2833 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2834   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2835
2836   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2837   if (Op0 == Op1) {
2838     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2839       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2840       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2841       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2842     }
2843
2844     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2845     return ReplaceInstUsesWith(I, CI);
2846   }
2847   
2848   if (Instruction *Common = commonDivTransforms(I))
2849     return Common;
2850   
2851   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2852   // This does not apply for fdiv.
2853   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2854     return &I;
2855
2856   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2857     // div X, 1 == X
2858     if (RHS->equalsInt(1))
2859       return ReplaceInstUsesWith(I, Op0);
2860
2861     // (X / C1) / C2  -> X / (C1*C2)
2862     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2863       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2864         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2865           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2866             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2867           else 
2868             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2869                                           Multiply(RHS, LHSRHS));
2870         }
2871
2872     if (!RHS->isZero()) { // avoid X udiv 0
2873       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2874         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2875           return R;
2876       if (isa<PHINode>(Op0))
2877         if (Instruction *NV = FoldOpIntoPhi(I))
2878           return NV;
2879     }
2880   }
2881
2882   // 0 / X == 0, we don't need to preserve faults!
2883   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2884     if (LHS->equalsInt(0))
2885       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2886
2887   // It can't be division by zero, hence it must be division by one.
2888   if (I.getType() == Type::Int1Ty)
2889     return ReplaceInstUsesWith(I, Op0);
2890
2891   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2892     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2893       // div X, 1 == X
2894       if (X->isOne())
2895         return ReplaceInstUsesWith(I, Op0);
2896   }
2897
2898   return 0;
2899 }
2900
2901 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2902   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2903
2904   // Handle the integer div common cases
2905   if (Instruction *Common = commonIDivTransforms(I))
2906     return Common;
2907
2908   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2909     // X udiv C^2 -> X >> C
2910     // Check to see if this is an unsigned division with an exact power of 2,
2911     // if so, convert to a right shift.
2912     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2913       return BinaryOperator::CreateLShr(Op0, 
2914                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2915
2916     // X udiv C, where C >= signbit
2917     if (C->getValue().isNegative()) {
2918       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2919                                       I);
2920       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2921                                 ConstantInt::get(I.getType(), 1));
2922     }
2923   }
2924
2925   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2926   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2927     if (RHSI->getOpcode() == Instruction::Shl &&
2928         isa<ConstantInt>(RHSI->getOperand(0))) {
2929       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2930       if (C1.isPowerOf2()) {
2931         Value *N = RHSI->getOperand(1);
2932         const Type *NTy = N->getType();
2933         if (uint32_t C2 = C1.logBase2()) {
2934           Constant *C2V = ConstantInt::get(NTy, C2);
2935           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2936         }
2937         return BinaryOperator::CreateLShr(Op0, N);
2938       }
2939     }
2940   }
2941   
2942   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2943   // where C1&C2 are powers of two.
2944   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2945     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2946       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2947         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2948         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2949           // Compute the shift amounts
2950           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2951           // Construct the "on true" case of the select
2952           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2953           Instruction *TSI = BinaryOperator::CreateLShr(
2954                                                  Op0, TC, SI->getName()+".t");
2955           TSI = InsertNewInstBefore(TSI, I);
2956   
2957           // Construct the "on false" case of the select
2958           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2959           Instruction *FSI = BinaryOperator::CreateLShr(
2960                                                  Op0, FC, SI->getName()+".f");
2961           FSI = InsertNewInstBefore(FSI, I);
2962
2963           // construct the select instruction and return it.
2964           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2965         }
2966       }
2967   return 0;
2968 }
2969
2970 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2971   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2972
2973   // Handle the integer div common cases
2974   if (Instruction *Common = commonIDivTransforms(I))
2975     return Common;
2976
2977   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2978     // sdiv X, -1 == -X
2979     if (RHS->isAllOnesValue())
2980       return BinaryOperator::CreateNeg(Op0);
2981   }
2982
2983   // If the sign bits of both operands are zero (i.e. we can prove they are
2984   // unsigned inputs), turn this into a udiv.
2985   if (I.getType()->isInteger()) {
2986     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2987     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2988       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2989       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2990     }
2991   }      
2992   
2993   return 0;
2994 }
2995
2996 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2997   return commonDivTransforms(I);
2998 }
2999
3000 /// This function implements the transforms on rem instructions that work
3001 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3002 /// is used by the visitors to those instructions.
3003 /// @brief Transforms common to all three rem instructions
3004 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3005   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3006
3007   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3008     if (I.getType()->isFPOrFPVector())
3009       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3010     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3011   }
3012   if (isa<UndefValue>(Op1))
3013     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3014
3015   // Handle cases involving: rem X, (select Cond, Y, Z)
3016   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3017     return &I;
3018
3019   return 0;
3020 }
3021
3022 /// This function implements the transforms common to both integer remainder
3023 /// instructions (urem and srem). It is called by the visitors to those integer
3024 /// remainder instructions.
3025 /// @brief Common integer remainder transforms
3026 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3027   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3028
3029   if (Instruction *common = commonRemTransforms(I))
3030     return common;
3031
3032   // 0 % X == 0 for integer, we don't need to preserve faults!
3033   if (Constant *LHS = dyn_cast<Constant>(Op0))
3034     if (LHS->isNullValue())
3035       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3036
3037   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3038     // X % 0 == undef, we don't need to preserve faults!
3039     if (RHS->equalsInt(0))
3040       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3041     
3042     if (RHS->equalsInt(1))  // X % 1 == 0
3043       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3044
3045     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3046       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3047         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3048           return R;
3049       } else if (isa<PHINode>(Op0I)) {
3050         if (Instruction *NV = FoldOpIntoPhi(I))
3051           return NV;
3052       }
3053
3054       // See if we can fold away this rem instruction.
3055       if (SimplifyDemandedInstructionBits(I))
3056         return &I;
3057     }
3058   }
3059
3060   return 0;
3061 }
3062
3063 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3064   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3065
3066   if (Instruction *common = commonIRemTransforms(I))
3067     return common;
3068   
3069   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3070     // X urem C^2 -> X and C
3071     // Check to see if this is an unsigned remainder with an exact power of 2,
3072     // if so, convert to a bitwise and.
3073     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3074       if (C->getValue().isPowerOf2())
3075         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3076   }
3077
3078   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3079     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3080     if (RHSI->getOpcode() == Instruction::Shl &&
3081         isa<ConstantInt>(RHSI->getOperand(0))) {
3082       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3083         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3084         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3085                                                                    "tmp"), I);
3086         return BinaryOperator::CreateAnd(Op0, Add);
3087       }
3088     }
3089   }
3090
3091   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3092   // where C1&C2 are powers of two.
3093   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3094     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3095       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3096         // STO == 0 and SFO == 0 handled above.
3097         if ((STO->getValue().isPowerOf2()) && 
3098             (SFO->getValue().isPowerOf2())) {
3099           Value *TrueAnd = InsertNewInstBefore(
3100             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3101           Value *FalseAnd = InsertNewInstBefore(
3102             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3103           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3104         }
3105       }
3106   }
3107   
3108   return 0;
3109 }
3110
3111 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3112   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3113
3114   // Handle the integer rem common cases
3115   if (Instruction *common = commonIRemTransforms(I))
3116     return common;
3117   
3118   if (Value *RHSNeg = dyn_castNegVal(Op1))
3119     if (!isa<Constant>(RHSNeg) ||
3120         (isa<ConstantInt>(RHSNeg) &&
3121          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3122       // X % -Y -> X % Y
3123       AddUsesToWorkList(I);
3124       I.setOperand(1, RHSNeg);
3125       return &I;
3126     }
3127
3128   // If the sign bits of both operands are zero (i.e. we can prove they are
3129   // unsigned inputs), turn this into a urem.
3130   if (I.getType()->isInteger()) {
3131     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3132     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3133       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3134       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3135     }
3136   }
3137
3138   // If it's a constant vector, flip any negative values positive.
3139   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3140     unsigned VWidth = RHSV->getNumOperands();
3141
3142     bool hasNegative = false;
3143     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3144       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3145         if (RHS->getValue().isNegative())
3146           hasNegative = true;
3147
3148     if (hasNegative) {
3149       std::vector<Constant *> Elts(VWidth);
3150       for (unsigned i = 0; i != VWidth; ++i) {
3151         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3152           if (RHS->getValue().isNegative())
3153             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3154           else
3155             Elts[i] = RHS;
3156         }
3157       }
3158
3159       Constant *NewRHSV = ConstantVector::get(Elts);
3160       if (NewRHSV != RHSV) {
3161         AddUsesToWorkList(I);
3162         I.setOperand(1, NewRHSV);
3163         return &I;
3164       }
3165     }
3166   }
3167
3168   return 0;
3169 }
3170
3171 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3172   return commonRemTransforms(I);
3173 }
3174
3175 // isOneBitSet - Return true if there is exactly one bit set in the specified
3176 // constant.
3177 static bool isOneBitSet(const ConstantInt *CI) {
3178   return CI->getValue().isPowerOf2();
3179 }
3180
3181 // isHighOnes - Return true if the constant is of the form 1+0+.
3182 // This is the same as lowones(~X).
3183 static bool isHighOnes(const ConstantInt *CI) {
3184   return (~CI->getValue() + 1).isPowerOf2();
3185 }
3186
3187 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3188 /// are carefully arranged to allow folding of expressions such as:
3189 ///
3190 ///      (A < B) | (A > B) --> (A != B)
3191 ///
3192 /// Note that this is only valid if the first and second predicates have the
3193 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3194 ///
3195 /// Three bits are used to represent the condition, as follows:
3196 ///   0  A > B
3197 ///   1  A == B
3198 ///   2  A < B
3199 ///
3200 /// <=>  Value  Definition
3201 /// 000     0   Always false
3202 /// 001     1   A >  B
3203 /// 010     2   A == B
3204 /// 011     3   A >= B
3205 /// 100     4   A <  B
3206 /// 101     5   A != B
3207 /// 110     6   A <= B
3208 /// 111     7   Always true
3209 ///  
3210 static unsigned getICmpCode(const ICmpInst *ICI) {
3211   switch (ICI->getPredicate()) {
3212     // False -> 0
3213   case ICmpInst::ICMP_UGT: return 1;  // 001
3214   case ICmpInst::ICMP_SGT: return 1;  // 001
3215   case ICmpInst::ICMP_EQ:  return 2;  // 010
3216   case ICmpInst::ICMP_UGE: return 3;  // 011
3217   case ICmpInst::ICMP_SGE: return 3;  // 011
3218   case ICmpInst::ICMP_ULT: return 4;  // 100
3219   case ICmpInst::ICMP_SLT: return 4;  // 100
3220   case ICmpInst::ICMP_NE:  return 5;  // 101
3221   case ICmpInst::ICMP_ULE: return 6;  // 110
3222   case ICmpInst::ICMP_SLE: return 6;  // 110
3223     // True -> 7
3224   default:
3225     assert(0 && "Invalid ICmp predicate!");
3226     return 0;
3227   }
3228 }
3229
3230 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3231 /// predicate into a three bit mask. It also returns whether it is an ordered
3232 /// predicate by reference.
3233 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3234   isOrdered = false;
3235   switch (CC) {
3236   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3237   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3238   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3239   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3240   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3241   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3242   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3243   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3244   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3245   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3246   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3247   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3248   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3249   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3250     // True -> 7
3251   default:
3252     // Not expecting FCMP_FALSE and FCMP_TRUE;
3253     assert(0 && "Unexpected FCmp predicate!");
3254     return 0;
3255   }
3256 }
3257
3258 /// getICmpValue - This is the complement of getICmpCode, which turns an
3259 /// opcode and two operands into either a constant true or false, or a brand 
3260 /// new ICmp instruction. The sign is passed in to determine which kind
3261 /// of predicate to use in the new icmp instruction.
3262 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3263   switch (code) {
3264   default: assert(0 && "Illegal ICmp code!");
3265   case  0: return ConstantInt::getFalse();
3266   case  1: 
3267     if (sign)
3268       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3269     else
3270       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3271   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3272   case  3: 
3273     if (sign)
3274       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3275     else
3276       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3277   case  4: 
3278     if (sign)
3279       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3280     else
3281       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3282   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3283   case  6: 
3284     if (sign)
3285       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3286     else
3287       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3288   case  7: return ConstantInt::getTrue();
3289   }
3290 }
3291
3292 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3293 /// opcode and two operands into either a FCmp instruction. isordered is passed
3294 /// in to determine which kind of predicate to use in the new fcmp instruction.
3295 static Value *getFCmpValue(bool isordered, unsigned code,
3296                            Value *LHS, Value *RHS) {
3297   switch (code) {
3298   default: assert(0 && "Illegal FCmp code!");
3299   case  0:
3300     if (isordered)
3301       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3302     else
3303       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3304   case  1: 
3305     if (isordered)
3306       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3307     else
3308       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3309   case  2: 
3310     if (isordered)
3311       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3312     else
3313       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3314   case  3: 
3315     if (isordered)
3316       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3317     else
3318       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3319   case  4: 
3320     if (isordered)
3321       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3322     else
3323       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3324   case  5: 
3325     if (isordered)
3326       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3327     else
3328       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3329   case  6: 
3330     if (isordered)
3331       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3332     else
3333       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3334   case  7: return ConstantInt::getTrue();
3335   }
3336 }
3337
3338 /// PredicatesFoldable - Return true if both predicates match sign or if at
3339 /// least one of them is an equality comparison (which is signless).
3340 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3341   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3342          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3343          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3344 }
3345
3346 namespace { 
3347 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3348 struct FoldICmpLogical {
3349   InstCombiner &IC;
3350   Value *LHS, *RHS;
3351   ICmpInst::Predicate pred;
3352   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3353     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3354       pred(ICI->getPredicate()) {}
3355   bool shouldApply(Value *V) const {
3356     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3357       if (PredicatesFoldable(pred, ICI->getPredicate()))
3358         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3359                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3360     return false;
3361   }
3362   Instruction *apply(Instruction &Log) const {
3363     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3364     if (ICI->getOperand(0) != LHS) {
3365       assert(ICI->getOperand(1) == LHS);
3366       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3367     }
3368
3369     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3370     unsigned LHSCode = getICmpCode(ICI);
3371     unsigned RHSCode = getICmpCode(RHSICI);
3372     unsigned Code;
3373     switch (Log.getOpcode()) {
3374     case Instruction::And: Code = LHSCode & RHSCode; break;
3375     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3376     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3377     default: assert(0 && "Illegal logical opcode!"); return 0;
3378     }
3379
3380     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3381                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3382       
3383     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3384     if (Instruction *I = dyn_cast<Instruction>(RV))
3385       return I;
3386     // Otherwise, it's a constant boolean value...
3387     return IC.ReplaceInstUsesWith(Log, RV);
3388   }
3389 };
3390 } // end anonymous namespace
3391
3392 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3393 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3394 // guaranteed to be a binary operator.
3395 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3396                                     ConstantInt *OpRHS,
3397                                     ConstantInt *AndRHS,
3398                                     BinaryOperator &TheAnd) {
3399   Value *X = Op->getOperand(0);
3400   Constant *Together = 0;
3401   if (!Op->isShift())
3402     Together = And(AndRHS, OpRHS);
3403
3404   switch (Op->getOpcode()) {
3405   case Instruction::Xor:
3406     if (Op->hasOneUse()) {
3407       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3408       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3409       InsertNewInstBefore(And, TheAnd);
3410       And->takeName(Op);
3411       return BinaryOperator::CreateXor(And, Together);
3412     }
3413     break;
3414   case Instruction::Or:
3415     if (Together == AndRHS) // (X | C) & C --> C
3416       return ReplaceInstUsesWith(TheAnd, AndRHS);
3417
3418     if (Op->hasOneUse() && Together != OpRHS) {
3419       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3420       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3421       InsertNewInstBefore(Or, TheAnd);
3422       Or->takeName(Op);
3423       return BinaryOperator::CreateAnd(Or, AndRHS);
3424     }
3425     break;
3426   case Instruction::Add:
3427     if (Op->hasOneUse()) {
3428       // Adding a one to a single bit bit-field should be turned into an XOR
3429       // of the bit.  First thing to check is to see if this AND is with a
3430       // single bit constant.
3431       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3432
3433       // If there is only one bit set...
3434       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3435         // Ok, at this point, we know that we are masking the result of the
3436         // ADD down to exactly one bit.  If the constant we are adding has
3437         // no bits set below this bit, then we can eliminate the ADD.
3438         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3439
3440         // Check to see if any bits below the one bit set in AndRHSV are set.
3441         if ((AddRHS & (AndRHSV-1)) == 0) {
3442           // If not, the only thing that can effect the output of the AND is
3443           // the bit specified by AndRHSV.  If that bit is set, the effect of
3444           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3445           // no effect.
3446           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3447             TheAnd.setOperand(0, X);
3448             return &TheAnd;
3449           } else {
3450             // Pull the XOR out of the AND.
3451             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3452             InsertNewInstBefore(NewAnd, TheAnd);
3453             NewAnd->takeName(Op);
3454             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3455           }
3456         }
3457       }
3458     }
3459     break;
3460
3461   case Instruction::Shl: {
3462     // We know that the AND will not produce any of the bits shifted in, so if
3463     // the anded constant includes them, clear them now!
3464     //
3465     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3466     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3467     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3468     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3469
3470     if (CI->getValue() == ShlMask) { 
3471     // Masking out bits that the shift already masks
3472       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3473     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3474       TheAnd.setOperand(1, CI);
3475       return &TheAnd;
3476     }
3477     break;
3478   }
3479   case Instruction::LShr:
3480   {
3481     // We know that the AND will not produce any of the bits shifted in, so if
3482     // the anded constant includes them, clear them now!  This only applies to
3483     // unsigned shifts, because a signed shr may bring in set bits!
3484     //
3485     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3486     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3487     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3488     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3489
3490     if (CI->getValue() == ShrMask) {   
3491     // Masking out bits that the shift already masks.
3492       return ReplaceInstUsesWith(TheAnd, Op);
3493     } else if (CI != AndRHS) {
3494       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3495       return &TheAnd;
3496     }
3497     break;
3498   }
3499   case Instruction::AShr:
3500     // Signed shr.
3501     // See if this is shifting in some sign extension, then masking it out
3502     // with an and.
3503     if (Op->hasOneUse()) {
3504       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3505       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3506       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3507       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3508       if (C == AndRHS) {          // Masking out bits shifted in.
3509         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3510         // Make the argument unsigned.
3511         Value *ShVal = Op->getOperand(0);
3512         ShVal = InsertNewInstBefore(
3513             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3514                                    Op->getName()), TheAnd);
3515         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3516       }
3517     }
3518     break;
3519   }
3520   return 0;
3521 }
3522
3523
3524 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3525 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3526 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3527 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3528 /// insert new instructions.
3529 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3530                                            bool isSigned, bool Inside, 
3531                                            Instruction &IB) {
3532   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3533             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3534          "Lo is not <= Hi in range emission code!");
3535     
3536   if (Inside) {
3537     if (Lo == Hi)  // Trivially false.
3538       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3539
3540     // V >= Min && V < Hi --> V < Hi
3541     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3542       ICmpInst::Predicate pred = (isSigned ? 
3543         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3544       return new ICmpInst(pred, V, Hi);
3545     }
3546
3547     // Emit V-Lo <u Hi-Lo
3548     Constant *NegLo = ConstantExpr::getNeg(Lo);
3549     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3550     InsertNewInstBefore(Add, IB);
3551     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3552     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3553   }
3554
3555   if (Lo == Hi)  // Trivially true.
3556     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3557
3558   // V < Min || V >= Hi -> V > Hi-1
3559   Hi = SubOne(cast<ConstantInt>(Hi));
3560   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3561     ICmpInst::Predicate pred = (isSigned ? 
3562         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3563     return new ICmpInst(pred, V, Hi);
3564   }
3565
3566   // Emit V-Lo >u Hi-1-Lo
3567   // Note that Hi has already had one subtracted from it, above.
3568   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3569   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3570   InsertNewInstBefore(Add, IB);
3571   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3572   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3573 }
3574
3575 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3576 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3577 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3578 // not, since all 1s are not contiguous.
3579 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3580   const APInt& V = Val->getValue();
3581   uint32_t BitWidth = Val->getType()->getBitWidth();
3582   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3583
3584   // look for the first zero bit after the run of ones
3585   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3586   // look for the first non-zero bit
3587   ME = V.getActiveBits(); 
3588   return true;
3589 }
3590
3591 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3592 /// where isSub determines whether the operator is a sub.  If we can fold one of
3593 /// the following xforms:
3594 /// 
3595 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3596 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3597 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3598 ///
3599 /// return (A +/- B).
3600 ///
3601 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3602                                         ConstantInt *Mask, bool isSub,
3603                                         Instruction &I) {
3604   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3605   if (!LHSI || LHSI->getNumOperands() != 2 ||
3606       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3607
3608   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3609
3610   switch (LHSI->getOpcode()) {
3611   default: return 0;
3612   case Instruction::And:
3613     if (And(N, Mask) == Mask) {
3614       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3615       if ((Mask->getValue().countLeadingZeros() + 
3616            Mask->getValue().countPopulation()) == 
3617           Mask->getValue().getBitWidth())
3618         break;
3619
3620       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3621       // part, we don't need any explicit masks to take them out of A.  If that
3622       // is all N is, ignore it.
3623       uint32_t MB = 0, ME = 0;
3624       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3625         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3626         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3627         if (MaskedValueIsZero(RHS, Mask))
3628           break;
3629       }
3630     }
3631     return 0;
3632   case Instruction::Or:
3633   case Instruction::Xor:
3634     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3635     if ((Mask->getValue().countLeadingZeros() + 
3636          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3637         && And(N, Mask)->isZero())
3638       break;
3639     return 0;
3640   }
3641   
3642   Instruction *New;
3643   if (isSub)
3644     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3645   else
3646     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3647   return InsertNewInstBefore(New, I);
3648 }
3649
3650 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3651 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3652                                           ICmpInst *LHS, ICmpInst *RHS) {
3653   Value *Val, *Val2;
3654   ConstantInt *LHSCst, *RHSCst;
3655   ICmpInst::Predicate LHSCC, RHSCC;
3656   
3657   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3658   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3659       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3660     return 0;
3661   
3662   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3663   // where C is a power of 2
3664   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3665       LHSCst->getValue().isPowerOf2()) {
3666     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3667     InsertNewInstBefore(NewOr, I);
3668     return new ICmpInst(LHSCC, NewOr, LHSCst);
3669   }
3670   
3671   // From here on, we only handle:
3672   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3673   if (Val != Val2) return 0;
3674   
3675   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3676   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3677       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3678       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3679       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3680     return 0;
3681   
3682   // We can't fold (ugt x, C) & (sgt x, C2).
3683   if (!PredicatesFoldable(LHSCC, RHSCC))
3684     return 0;
3685     
3686   // Ensure that the larger constant is on the RHS.
3687   bool ShouldSwap;
3688   if (ICmpInst::isSignedPredicate(LHSCC) ||
3689       (ICmpInst::isEquality(LHSCC) && 
3690        ICmpInst::isSignedPredicate(RHSCC)))
3691     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3692   else
3693     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3694     
3695   if (ShouldSwap) {
3696     std::swap(LHS, RHS);
3697     std::swap(LHSCst, RHSCst);
3698     std::swap(LHSCC, RHSCC);
3699   }
3700
3701   // At this point, we know we have have two icmp instructions
3702   // comparing a value against two constants and and'ing the result
3703   // together.  Because of the above check, we know that we only have
3704   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3705   // (from the FoldICmpLogical check above), that the two constants 
3706   // are not equal and that the larger constant is on the RHS
3707   assert(LHSCst != RHSCst && "Compares not folded above?");
3708
3709   switch (LHSCC) {
3710   default: assert(0 && "Unknown integer condition code!");
3711   case ICmpInst::ICMP_EQ:
3712     switch (RHSCC) {
3713     default: assert(0 && "Unknown integer condition code!");
3714     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3715     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3716     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3717       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3718     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3719     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3720     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3721       return ReplaceInstUsesWith(I, LHS);
3722     }
3723   case ICmpInst::ICMP_NE:
3724     switch (RHSCC) {
3725     default: assert(0 && "Unknown integer condition code!");
3726     case ICmpInst::ICMP_ULT:
3727       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3728         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3729       break;                        // (X != 13 & X u< 15) -> no change
3730     case ICmpInst::ICMP_SLT:
3731       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3732         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3733       break;                        // (X != 13 & X s< 15) -> no change
3734     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3735     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3736     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3737       return ReplaceInstUsesWith(I, RHS);
3738     case ICmpInst::ICMP_NE:
3739       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3740         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3741         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3742                                                      Val->getName()+".off");
3743         InsertNewInstBefore(Add, I);
3744         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3745                             ConstantInt::get(Add->getType(), 1));
3746       }
3747       break;                        // (X != 13 & X != 15) -> no change
3748     }
3749     break;
3750   case ICmpInst::ICMP_ULT:
3751     switch (RHSCC) {
3752     default: assert(0 && "Unknown integer condition code!");
3753     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3754     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3755       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3756     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3757       break;
3758     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3759     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3760       return ReplaceInstUsesWith(I, LHS);
3761     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3762       break;
3763     }
3764     break;
3765   case ICmpInst::ICMP_SLT:
3766     switch (RHSCC) {
3767     default: assert(0 && "Unknown integer condition code!");
3768     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3769     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3770       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3771     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3772       break;
3773     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3774     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3775       return ReplaceInstUsesWith(I, LHS);
3776     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3777       break;
3778     }
3779     break;
3780   case ICmpInst::ICMP_UGT:
3781     switch (RHSCC) {
3782     default: assert(0 && "Unknown integer condition code!");
3783     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3784     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3785       return ReplaceInstUsesWith(I, RHS);
3786     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3787       break;
3788     case ICmpInst::ICMP_NE:
3789       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3790         return new ICmpInst(LHSCC, Val, RHSCst);
3791       break;                        // (X u> 13 & X != 15) -> no change
3792     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3793       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3794     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3795       break;
3796     }
3797     break;
3798   case ICmpInst::ICMP_SGT:
3799     switch (RHSCC) {
3800     default: assert(0 && "Unknown integer condition code!");
3801     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3802     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3803       return ReplaceInstUsesWith(I, RHS);
3804     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3805       break;
3806     case ICmpInst::ICMP_NE:
3807       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3808         return new ICmpInst(LHSCC, Val, RHSCst);
3809       break;                        // (X s> 13 & X != 15) -> no change
3810     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3811       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3812     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3813       break;
3814     }
3815     break;
3816   }
3817  
3818   return 0;
3819 }
3820
3821
3822 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3823   bool Changed = SimplifyCommutative(I);
3824   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3825
3826   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3827     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3828
3829   // and X, X = X
3830   if (Op0 == Op1)
3831     return ReplaceInstUsesWith(I, Op1);
3832
3833   // See if we can simplify any instructions used by the instruction whose sole 
3834   // purpose is to compute bits we don't care about.
3835   if (!isa<VectorType>(I.getType())) {
3836     if (SimplifyDemandedInstructionBits(I))
3837       return &I;
3838   } else {
3839     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3840       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3841         return ReplaceInstUsesWith(I, I.getOperand(0));
3842     } else if (isa<ConstantAggregateZero>(Op1)) {
3843       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3844     }
3845   }
3846   
3847   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3848     const APInt& AndRHSMask = AndRHS->getValue();
3849     APInt NotAndRHS(~AndRHSMask);
3850
3851     // Optimize a variety of ((val OP C1) & C2) combinations...
3852     if (isa<BinaryOperator>(Op0)) {
3853       Instruction *Op0I = cast<Instruction>(Op0);
3854       Value *Op0LHS = Op0I->getOperand(0);
3855       Value *Op0RHS = Op0I->getOperand(1);
3856       switch (Op0I->getOpcode()) {
3857       case Instruction::Xor:
3858       case Instruction::Or:
3859         // If the mask is only needed on one incoming arm, push it up.
3860         if (Op0I->hasOneUse()) {
3861           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3862             // Not masking anything out for the LHS, move to RHS.
3863             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3864                                                    Op0RHS->getName()+".masked");
3865             InsertNewInstBefore(NewRHS, I);
3866             return BinaryOperator::Create(
3867                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3868           }
3869           if (!isa<Constant>(Op0RHS) &&
3870               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3871             // Not masking anything out for the RHS, move to LHS.
3872             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3873                                                    Op0LHS->getName()+".masked");
3874             InsertNewInstBefore(NewLHS, I);
3875             return BinaryOperator::Create(
3876                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3877           }
3878         }
3879
3880         break;
3881       case Instruction::Add:
3882         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3883         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3884         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3885         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3886           return BinaryOperator::CreateAnd(V, AndRHS);
3887         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3888           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3889         break;
3890
3891       case Instruction::Sub:
3892         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3893         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3894         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3895         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3896           return BinaryOperator::CreateAnd(V, AndRHS);
3897
3898         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3899         // has 1's for all bits that the subtraction with A might affect.
3900         if (Op0I->hasOneUse()) {
3901           uint32_t BitWidth = AndRHSMask.getBitWidth();
3902           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3903           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3904
3905           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3906           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3907               MaskedValueIsZero(Op0LHS, Mask)) {
3908             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3909             InsertNewInstBefore(NewNeg, I);
3910             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3911           }
3912         }
3913         break;
3914
3915       case Instruction::Shl:
3916       case Instruction::LShr:
3917         // (1 << x) & 1 --> zext(x == 0)
3918         // (1 >> x) & 1 --> zext(x == 0)
3919         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3920           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3921                                            Constant::getNullValue(I.getType()));
3922           InsertNewInstBefore(NewICmp, I);
3923           return new ZExtInst(NewICmp, I.getType());
3924         }
3925         break;
3926       }
3927
3928       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3929         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3930           return Res;
3931     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3932       // If this is an integer truncation or change from signed-to-unsigned, and
3933       // if the source is an and/or with immediate, transform it.  This
3934       // frequently occurs for bitfield accesses.
3935       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3936         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3937             CastOp->getNumOperands() == 2)
3938           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3939             if (CastOp->getOpcode() == Instruction::And) {
3940               // Change: and (cast (and X, C1) to T), C2
3941               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3942               // This will fold the two constants together, which may allow 
3943               // other simplifications.
3944               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3945                 CastOp->getOperand(0), I.getType(), 
3946                 CastOp->getName()+".shrunk");
3947               NewCast = InsertNewInstBefore(NewCast, I);
3948               // trunc_or_bitcast(C1)&C2
3949               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3950               C3 = ConstantExpr::getAnd(C3, AndRHS);
3951               return BinaryOperator::CreateAnd(NewCast, C3);
3952             } else if (CastOp->getOpcode() == Instruction::Or) {
3953               // Change: and (cast (or X, C1) to T), C2
3954               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3955               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3956               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3957                 return ReplaceInstUsesWith(I, AndRHS);
3958             }
3959           }
3960       }
3961     }
3962
3963     // Try to fold constant and into select arguments.
3964     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3965       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3966         return R;
3967     if (isa<PHINode>(Op0))
3968       if (Instruction *NV = FoldOpIntoPhi(I))
3969         return NV;
3970   }
3971
3972   Value *Op0NotVal = dyn_castNotVal(Op0);
3973   Value *Op1NotVal = dyn_castNotVal(Op1);
3974
3975   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3976     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3977
3978   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3979   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3980     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3981                                                I.getName()+".demorgan");
3982     InsertNewInstBefore(Or, I);
3983     return BinaryOperator::CreateNot(Or);
3984   }
3985   
3986   {
3987     Value *A = 0, *B = 0, *C = 0, *D = 0;
3988     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3989       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3990         return ReplaceInstUsesWith(I, Op1);
3991     
3992       // (A|B) & ~(A&B) -> A^B
3993       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3994         if ((A == C && B == D) || (A == D && B == C))
3995           return BinaryOperator::CreateXor(A, B);
3996       }
3997     }
3998     
3999     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4000       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4001         return ReplaceInstUsesWith(I, Op0);
4002
4003       // ~(A&B) & (A|B) -> A^B
4004       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4005         if ((A == C && B == D) || (A == D && B == C))
4006           return BinaryOperator::CreateXor(A, B);
4007       }
4008     }
4009     
4010     if (Op0->hasOneUse() &&
4011         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4012       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4013         I.swapOperands();     // Simplify below
4014         std::swap(Op0, Op1);
4015       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4016         cast<BinaryOperator>(Op0)->swapOperands();
4017         I.swapOperands();     // Simplify below
4018         std::swap(Op0, Op1);
4019       }
4020     }
4021
4022     if (Op1->hasOneUse() &&
4023         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4024       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4025         cast<BinaryOperator>(Op1)->swapOperands();
4026         std::swap(A, B);
4027       }
4028       if (A == Op0) {                                // A&(A^B) -> A & ~B
4029         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4030         InsertNewInstBefore(NotB, I);
4031         return BinaryOperator::CreateAnd(A, NotB);
4032       }
4033     }
4034
4035     // (A&((~A)|B)) -> A&B
4036     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4037         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4038       return BinaryOperator::CreateAnd(A, Op1);
4039     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4040         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4041       return BinaryOperator::CreateAnd(A, Op0);
4042   }
4043   
4044   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4045     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4046     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4047       return R;
4048
4049     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4050       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4051         return Res;
4052   }
4053
4054   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4055   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4056     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4057       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4058         const Type *SrcTy = Op0C->getOperand(0)->getType();
4059         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4060             // Only do this if the casts both really cause code to be generated.
4061             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4062                               I.getType(), TD) &&
4063             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4064                               I.getType(), TD)) {
4065           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4066                                                          Op1C->getOperand(0),
4067                                                          I.getName());
4068           InsertNewInstBefore(NewOp, I);
4069           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4070         }
4071       }
4072     
4073   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4074   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4075     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4076       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4077           SI0->getOperand(1) == SI1->getOperand(1) &&
4078           (SI0->hasOneUse() || SI1->hasOneUse())) {
4079         Instruction *NewOp =
4080           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4081                                                         SI1->getOperand(0),
4082                                                         SI0->getName()), I);
4083         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4084                                       SI1->getOperand(1));
4085       }
4086   }
4087
4088   // If and'ing two fcmp, try combine them into one.
4089   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4090     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4091       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4092           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4093         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4094         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4095           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4096             // If either of the constants are nans, then the whole thing returns
4097             // false.
4098             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4099               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4100             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4101                                 RHS->getOperand(0));
4102           }
4103       } else {
4104         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4105         FCmpInst::Predicate Op0CC, Op1CC;
4106         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4107             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4108           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4109             // Swap RHS operands to match LHS.
4110             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4111             std::swap(Op1LHS, Op1RHS);
4112           }
4113           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4114             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4115             if (Op0CC == Op1CC)
4116               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4117             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4118                      Op1CC == FCmpInst::FCMP_FALSE)
4119               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4120             else if (Op0CC == FCmpInst::FCMP_TRUE)
4121               return ReplaceInstUsesWith(I, Op1);
4122             else if (Op1CC == FCmpInst::FCMP_TRUE)
4123               return ReplaceInstUsesWith(I, Op0);
4124             bool Op0Ordered;
4125             bool Op1Ordered;
4126             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4127             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4128             if (Op1Pred == 0) {
4129               std::swap(Op0, Op1);
4130               std::swap(Op0Pred, Op1Pred);
4131               std::swap(Op0Ordered, Op1Ordered);
4132             }
4133             if (Op0Pred == 0) {
4134               // uno && ueq -> uno && (uno || eq) -> ueq
4135               // ord && olt -> ord && (ord && lt) -> olt
4136               if (Op0Ordered == Op1Ordered)
4137                 return ReplaceInstUsesWith(I, Op1);
4138               // uno && oeq -> uno && (ord && eq) -> false
4139               // uno && ord -> false
4140               if (!Op0Ordered)
4141                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4142               // ord && ueq -> ord && (uno || eq) -> oeq
4143               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4144                                                     Op0LHS, Op0RHS));
4145             }
4146           }
4147         }
4148       }
4149     }
4150   }
4151
4152   return Changed ? &I : 0;
4153 }
4154
4155 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4156 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4157 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4158 /// the expression came from the corresponding "byte swapped" byte in some other
4159 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4160 /// we know that the expression deposits the low byte of %X into the high byte
4161 /// of the bswap result and that all other bytes are zero.  This expression is
4162 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4163 /// match.
4164 ///
4165 /// This function returns true if the match was unsuccessful and false if so.
4166 /// On entry to the function the "OverallLeftShift" is a signed integer value
4167 /// indicating the number of bytes that the subexpression is later shifted.  For
4168 /// example, if the expression is later right shifted by 16 bits, the
4169 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4170 /// byte of ByteValues is actually being set.
4171 ///
4172 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4173 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4174 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4175 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4176 /// always in the local (OverallLeftShift) coordinate space.
4177 ///
4178 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4179                               SmallVector<Value*, 8> &ByteValues) {
4180   if (Instruction *I = dyn_cast<Instruction>(V)) {
4181     // If this is an or instruction, it may be an inner node of the bswap.
4182     if (I->getOpcode() == Instruction::Or) {
4183       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4184                                ByteValues) ||
4185              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4186                                ByteValues);
4187     }
4188   
4189     // If this is a logical shift by a constant multiple of 8, recurse with
4190     // OverallLeftShift and ByteMask adjusted.
4191     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4192       unsigned ShAmt = 
4193         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4194       // Ensure the shift amount is defined and of a byte value.
4195       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4196         return true;
4197
4198       unsigned ByteShift = ShAmt >> 3;
4199       if (I->getOpcode() == Instruction::Shl) {
4200         // X << 2 -> collect(X, +2)
4201         OverallLeftShift += ByteShift;
4202         ByteMask >>= ByteShift;
4203       } else {
4204         // X >>u 2 -> collect(X, -2)
4205         OverallLeftShift -= ByteShift;
4206         ByteMask <<= ByteShift;
4207         ByteMask &= (~0U >> (32-ByteValues.size()));
4208       }
4209
4210       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4211       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4212
4213       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4214                                ByteValues);
4215     }
4216
4217     // If this is a logical 'and' with a mask that clears bytes, clear the
4218     // corresponding bytes in ByteMask.
4219     if (I->getOpcode() == Instruction::And &&
4220         isa<ConstantInt>(I->getOperand(1))) {
4221       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4222       unsigned NumBytes = ByteValues.size();
4223       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4224       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4225       
4226       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4227         // If this byte is masked out by a later operation, we don't care what
4228         // the and mask is.
4229         if ((ByteMask & (1 << i)) == 0)
4230           continue;
4231         
4232         // If the AndMask is all zeros for this byte, clear the bit.
4233         APInt MaskB = AndMask & Byte;
4234         if (MaskB == 0) {
4235           ByteMask &= ~(1U << i);
4236           continue;
4237         }
4238         
4239         // If the AndMask is not all ones for this byte, it's not a bytezap.
4240         if (MaskB != Byte)
4241           return true;
4242
4243         // Otherwise, this byte is kept.
4244       }
4245
4246       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4247                                ByteValues);
4248     }
4249   }
4250   
4251   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4252   // the input value to the bswap.  Some observations: 1) if more than one byte
4253   // is demanded from this input, then it could not be successfully assembled
4254   // into a byteswap.  At least one of the two bytes would not be aligned with
4255   // their ultimate destination.
4256   if (!isPowerOf2_32(ByteMask)) return true;
4257   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4258   
4259   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4260   // is demanded, it needs to go into byte 0 of the result.  This means that the
4261   // byte needs to be shifted until it lands in the right byte bucket.  The
4262   // shift amount depends on the position: if the byte is coming from the high
4263   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4264   // low part, it must be shifted left.
4265   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4266   if (InputByteNo < ByteValues.size()/2) {
4267     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4268       return true;
4269   } else {
4270     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4271       return true;
4272   }
4273   
4274   // If the destination byte value is already defined, the values are or'd
4275   // together, which isn't a bswap (unless it's an or of the same bits).
4276   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4277     return true;
4278   ByteValues[DestByteNo] = V;
4279   return false;
4280 }
4281
4282 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4283 /// If so, insert the new bswap intrinsic and return it.
4284 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4285   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4286   if (!ITy || ITy->getBitWidth() % 16 || 
4287       // ByteMask only allows up to 32-byte values.
4288       ITy->getBitWidth() > 32*8) 
4289     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4290   
4291   /// ByteValues - For each byte of the result, we keep track of which value
4292   /// defines each byte.
4293   SmallVector<Value*, 8> ByteValues;
4294   ByteValues.resize(ITy->getBitWidth()/8);
4295     
4296   // Try to find all the pieces corresponding to the bswap.
4297   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4298   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4299     return 0;
4300   
4301   // Check to see if all of the bytes come from the same value.
4302   Value *V = ByteValues[0];
4303   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4304   
4305   // Check to make sure that all of the bytes come from the same value.
4306   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4307     if (ByteValues[i] != V)
4308       return 0;
4309   const Type *Tys[] = { ITy };
4310   Module *M = I.getParent()->getParent()->getParent();
4311   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4312   return CallInst::Create(F, V);
4313 }
4314
4315 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4316 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4317 /// we can simplify this expression to "cond ? C : D or B".
4318 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4319                                          Value *C, Value *D) {
4320   // If A is not a select of -1/0, this cannot match.
4321   Value *Cond = 0;
4322   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4323     return 0;
4324
4325   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4326   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4327     return SelectInst::Create(Cond, C, B);
4328   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4329     return SelectInst::Create(Cond, C, B);
4330   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4331   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4332     return SelectInst::Create(Cond, C, D);
4333   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4334     return SelectInst::Create(Cond, C, D);
4335   return 0;
4336 }
4337
4338 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4339 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4340                                          ICmpInst *LHS, ICmpInst *RHS) {
4341   Value *Val, *Val2;
4342   ConstantInt *LHSCst, *RHSCst;
4343   ICmpInst::Predicate LHSCC, RHSCC;
4344   
4345   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4346   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4347       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4348     return 0;
4349   
4350   // From here on, we only handle:
4351   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4352   if (Val != Val2) return 0;
4353   
4354   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4355   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4356       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4357       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4358       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4359     return 0;
4360   
4361   // We can't fold (ugt x, C) | (sgt x, C2).
4362   if (!PredicatesFoldable(LHSCC, RHSCC))
4363     return 0;
4364   
4365   // Ensure that the larger constant is on the RHS.
4366   bool ShouldSwap;
4367   if (ICmpInst::isSignedPredicate(LHSCC) ||
4368       (ICmpInst::isEquality(LHSCC) && 
4369        ICmpInst::isSignedPredicate(RHSCC)))
4370     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4371   else
4372     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4373   
4374   if (ShouldSwap) {
4375     std::swap(LHS, RHS);
4376     std::swap(LHSCst, RHSCst);
4377     std::swap(LHSCC, RHSCC);
4378   }
4379   
4380   // At this point, we know we have have two icmp instructions
4381   // comparing a value against two constants and or'ing the result
4382   // together.  Because of the above check, we know that we only have
4383   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4384   // FoldICmpLogical check above), that the two constants are not
4385   // equal.
4386   assert(LHSCst != RHSCst && "Compares not folded above?");
4387
4388   switch (LHSCC) {
4389   default: assert(0 && "Unknown integer condition code!");
4390   case ICmpInst::ICMP_EQ:
4391     switch (RHSCC) {
4392     default: assert(0 && "Unknown integer condition code!");
4393     case ICmpInst::ICMP_EQ:
4394       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4395         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4396         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4397                                                      Val->getName()+".off");
4398         InsertNewInstBefore(Add, I);
4399         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4400         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4401       }
4402       break;                         // (X == 13 | X == 15) -> no change
4403     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4404     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4405       break;
4406     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4407     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4408     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4409       return ReplaceInstUsesWith(I, RHS);
4410     }
4411     break;
4412   case ICmpInst::ICMP_NE:
4413     switch (RHSCC) {
4414     default: assert(0 && "Unknown integer condition code!");
4415     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4416     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4417     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4418       return ReplaceInstUsesWith(I, LHS);
4419     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4420     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4421     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4422       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4423     }
4424     break;
4425   case ICmpInst::ICMP_ULT:
4426     switch (RHSCC) {
4427     default: assert(0 && "Unknown integer condition code!");
4428     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4429       break;
4430     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4431       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4432       // this can cause overflow.
4433       if (RHSCst->isMaxValue(false))
4434         return ReplaceInstUsesWith(I, LHS);
4435       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4436     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4437       break;
4438     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4439     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4440       return ReplaceInstUsesWith(I, RHS);
4441     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4442       break;
4443     }
4444     break;
4445   case ICmpInst::ICMP_SLT:
4446     switch (RHSCC) {
4447     default: assert(0 && "Unknown integer condition code!");
4448     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4449       break;
4450     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4451       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4452       // this can cause overflow.
4453       if (RHSCst->isMaxValue(true))
4454         return ReplaceInstUsesWith(I, LHS);
4455       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4456     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4457       break;
4458     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4459     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4460       return ReplaceInstUsesWith(I, RHS);
4461     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4462       break;
4463     }
4464     break;
4465   case ICmpInst::ICMP_UGT:
4466     switch (RHSCC) {
4467     default: assert(0 && "Unknown integer condition code!");
4468     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4469     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4470       return ReplaceInstUsesWith(I, LHS);
4471     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4472       break;
4473     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4474     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4475       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4476     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4477       break;
4478     }
4479     break;
4480   case ICmpInst::ICMP_SGT:
4481     switch (RHSCC) {
4482     default: assert(0 && "Unknown integer condition code!");
4483     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4484     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4485       return ReplaceInstUsesWith(I, LHS);
4486     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4487       break;
4488     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4489     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4490       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4491     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4492       break;
4493     }
4494     break;
4495   }
4496   return 0;
4497 }
4498
4499 /// FoldOrWithConstants - This helper function folds:
4500 ///
4501 ///     ((A | B) & C1) | (B & C2)
4502 ///
4503 /// into:
4504 /// 
4505 ///     (A & C1) | B
4506 ///
4507 /// when the XOR of the two constants is "all ones" (-1).
4508 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4509                                                Value *A, Value *B, Value *C) {
4510   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4511   if (!CI1) return 0;
4512
4513   Value *V1 = 0;
4514   ConstantInt *CI2 = 0;
4515   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4516
4517   APInt Xor = CI1->getValue() ^ CI2->getValue();
4518   if (!Xor.isAllOnesValue()) return 0;
4519
4520   if (V1 == A || V1 == B) {
4521     Instruction *NewOp =
4522       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4523     return BinaryOperator::CreateOr(NewOp, V1);
4524   }
4525
4526   return 0;
4527 }
4528
4529 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4530   bool Changed = SimplifyCommutative(I);
4531   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4532
4533   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4534     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4535
4536   // or X, X = X
4537   if (Op0 == Op1)
4538     return ReplaceInstUsesWith(I, Op0);
4539
4540   // See if we can simplify any instructions used by the instruction whose sole 
4541   // purpose is to compute bits we don't care about.
4542   if (!isa<VectorType>(I.getType())) {
4543     if (SimplifyDemandedInstructionBits(I))
4544       return &I;
4545   } else if (isa<ConstantAggregateZero>(Op1)) {
4546     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4547   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4548     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4549       return ReplaceInstUsesWith(I, I.getOperand(1));
4550   }
4551     
4552
4553   
4554   // or X, -1 == -1
4555   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4556     ConstantInt *C1 = 0; Value *X = 0;
4557     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4558     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4559       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4560       InsertNewInstBefore(Or, I);
4561       Or->takeName(Op0);
4562       return BinaryOperator::CreateAnd(Or, 
4563                ConstantInt::get(RHS->getValue() | C1->getValue()));
4564     }
4565
4566     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4567     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4568       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4569       InsertNewInstBefore(Or, I);
4570       Or->takeName(Op0);
4571       return BinaryOperator::CreateXor(Or,
4572                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4573     }
4574
4575     // Try to fold constant and into select arguments.
4576     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4577       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4578         return R;
4579     if (isa<PHINode>(Op0))
4580       if (Instruction *NV = FoldOpIntoPhi(I))
4581         return NV;
4582   }
4583
4584   Value *A = 0, *B = 0;
4585   ConstantInt *C1 = 0, *C2 = 0;
4586
4587   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4588     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4589       return ReplaceInstUsesWith(I, Op1);
4590   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4591     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4592       return ReplaceInstUsesWith(I, Op0);
4593
4594   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4595   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4596   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4597       match(Op1, m_Or(m_Value(), m_Value())) ||
4598       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4599        match(Op1, m_Shift(m_Value(), m_Value())))) {
4600     if (Instruction *BSwap = MatchBSwap(I))
4601       return BSwap;
4602   }
4603   
4604   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4605   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4606       MaskedValueIsZero(Op1, C1->getValue())) {
4607     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4608     InsertNewInstBefore(NOr, I);
4609     NOr->takeName(Op0);
4610     return BinaryOperator::CreateXor(NOr, C1);
4611   }
4612
4613   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4614   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4615       MaskedValueIsZero(Op0, C1->getValue())) {
4616     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4617     InsertNewInstBefore(NOr, I);
4618     NOr->takeName(Op0);
4619     return BinaryOperator::CreateXor(NOr, C1);
4620   }
4621
4622   // (A & C)|(B & D)
4623   Value *C = 0, *D = 0;
4624   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4625       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4626     Value *V1 = 0, *V2 = 0, *V3 = 0;
4627     C1 = dyn_cast<ConstantInt>(C);
4628     C2 = dyn_cast<ConstantInt>(D);
4629     if (C1 && C2) {  // (A & C1)|(B & C2)
4630       // If we have: ((V + N) & C1) | (V & C2)
4631       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4632       // replace with V+N.
4633       if (C1->getValue() == ~C2->getValue()) {
4634         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4635             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4636           // Add commutes, try both ways.
4637           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4638             return ReplaceInstUsesWith(I, A);
4639           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4640             return ReplaceInstUsesWith(I, A);
4641         }
4642         // Or commutes, try both ways.
4643         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4644             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4645           // Add commutes, try both ways.
4646           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4647             return ReplaceInstUsesWith(I, B);
4648           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4649             return ReplaceInstUsesWith(I, B);
4650         }
4651       }
4652       V1 = 0; V2 = 0; V3 = 0;
4653     }
4654     
4655     // Check to see if we have any common things being and'ed.  If so, find the
4656     // terms for V1 & (V2|V3).
4657     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4658       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4659         V1 = A, V2 = C, V3 = D;
4660       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4661         V1 = A, V2 = B, V3 = C;
4662       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4663         V1 = C, V2 = A, V3 = D;
4664       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4665         V1 = C, V2 = A, V3 = B;
4666       
4667       if (V1) {
4668         Value *Or =
4669           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4670         return BinaryOperator::CreateAnd(V1, Or);
4671       }
4672     }
4673
4674     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4675     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4676       return Match;
4677     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4678       return Match;
4679     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4680       return Match;
4681     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4682       return Match;
4683
4684     // ((A&~B)|(~A&B)) -> A^B
4685     if ((match(C, m_Not(m_Specific(D))) &&
4686          match(B, m_Not(m_Specific(A)))))
4687       return BinaryOperator::CreateXor(A, D);
4688     // ((~B&A)|(~A&B)) -> A^B
4689     if ((match(A, m_Not(m_Specific(D))) &&
4690          match(B, m_Not(m_Specific(C)))))
4691       return BinaryOperator::CreateXor(C, D);
4692     // ((A&~B)|(B&~A)) -> A^B
4693     if ((match(C, m_Not(m_Specific(B))) &&
4694          match(D, m_Not(m_Specific(A)))))
4695       return BinaryOperator::CreateXor(A, B);
4696     // ((~B&A)|(B&~A)) -> A^B
4697     if ((match(A, m_Not(m_Specific(B))) &&
4698          match(D, m_Not(m_Specific(C)))))
4699       return BinaryOperator::CreateXor(C, B);
4700   }
4701   
4702   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4703   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4704     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4705       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4706           SI0->getOperand(1) == SI1->getOperand(1) &&
4707           (SI0->hasOneUse() || SI1->hasOneUse())) {
4708         Instruction *NewOp =
4709         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4710                                                      SI1->getOperand(0),
4711                                                      SI0->getName()), I);
4712         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4713                                       SI1->getOperand(1));
4714       }
4715   }
4716
4717   // ((A|B)&1)|(B&-2) -> (A&1) | B
4718   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4719       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4720     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4721     if (Ret) return Ret;
4722   }
4723   // (B&-2)|((A|B)&1) -> (A&1) | B
4724   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4725       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4726     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4727     if (Ret) return Ret;
4728   }
4729
4730   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4731     if (A == Op1)   // ~A | A == -1
4732       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4733   } else {
4734     A = 0;
4735   }
4736   // Note, A is still live here!
4737   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4738     if (Op0 == B)
4739       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4740
4741     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4742     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4743       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4744                                               I.getName()+".demorgan"), I);
4745       return BinaryOperator::CreateNot(And);
4746     }
4747   }
4748
4749   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4750   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4751     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4752       return R;
4753
4754     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4755       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4756         return Res;
4757   }
4758     
4759   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4760   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4761     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4762       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4763         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4764             !isa<ICmpInst>(Op1C->getOperand(0))) {
4765           const Type *SrcTy = Op0C->getOperand(0)->getType();
4766           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4767               // Only do this if the casts both really cause code to be
4768               // generated.
4769               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4770                                 I.getType(), TD) &&
4771               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4772                                 I.getType(), TD)) {
4773             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4774                                                           Op1C->getOperand(0),
4775                                                           I.getName());
4776             InsertNewInstBefore(NewOp, I);
4777             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4778           }
4779         }
4780       }
4781   }
4782   
4783     
4784   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4785   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4786     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4787       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4788           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4789           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4790         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4791           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4792             // If either of the constants are nans, then the whole thing returns
4793             // true.
4794             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4795               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4796             
4797             // Otherwise, no need to compare the two constants, compare the
4798             // rest.
4799             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4800                                 RHS->getOperand(0));
4801           }
4802       } else {
4803         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4804         FCmpInst::Predicate Op0CC, Op1CC;
4805         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4806             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4807           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4808             // Swap RHS operands to match LHS.
4809             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4810             std::swap(Op1LHS, Op1RHS);
4811           }
4812           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4813             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4814             if (Op0CC == Op1CC)
4815               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4816             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4817                      Op1CC == FCmpInst::FCMP_TRUE)
4818               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4819             else if (Op0CC == FCmpInst::FCMP_FALSE)
4820               return ReplaceInstUsesWith(I, Op1);
4821             else if (Op1CC == FCmpInst::FCMP_FALSE)
4822               return ReplaceInstUsesWith(I, Op0);
4823             bool Op0Ordered;
4824             bool Op1Ordered;
4825             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4826             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4827             if (Op0Ordered == Op1Ordered) {
4828               // If both are ordered or unordered, return a new fcmp with
4829               // or'ed predicates.
4830               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4831                                        Op0LHS, Op0RHS);
4832               if (Instruction *I = dyn_cast<Instruction>(RV))
4833                 return I;
4834               // Otherwise, it's a constant boolean value...
4835               return ReplaceInstUsesWith(I, RV);
4836             }
4837           }
4838         }
4839       }
4840     }
4841   }
4842
4843   return Changed ? &I : 0;
4844 }
4845
4846 namespace {
4847
4848 // XorSelf - Implements: X ^ X --> 0
4849 struct XorSelf {
4850   Value *RHS;
4851   XorSelf(Value *rhs) : RHS(rhs) {}
4852   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4853   Instruction *apply(BinaryOperator &Xor) const {
4854     return &Xor;
4855   }
4856 };
4857
4858 }
4859
4860 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4861   bool Changed = SimplifyCommutative(I);
4862   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4863
4864   if (isa<UndefValue>(Op1)) {
4865     if (isa<UndefValue>(Op0))
4866       // Handle undef ^ undef -> 0 special case. This is a common
4867       // idiom (misuse).
4868       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4869     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4870   }
4871
4872   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4873   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4874     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4875     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4876   }
4877   
4878   // See if we can simplify any instructions used by the instruction whose sole 
4879   // purpose is to compute bits we don't care about.
4880   if (!isa<VectorType>(I.getType())) {
4881     if (SimplifyDemandedInstructionBits(I))
4882       return &I;
4883   } else if (isa<ConstantAggregateZero>(Op1)) {
4884     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4885   }
4886
4887   // Is this a ~ operation?
4888   if (Value *NotOp = dyn_castNotVal(&I)) {
4889     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4890     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4891     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4892       if (Op0I->getOpcode() == Instruction::And || 
4893           Op0I->getOpcode() == Instruction::Or) {
4894         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4895         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4896           Instruction *NotY =
4897             BinaryOperator::CreateNot(Op0I->getOperand(1),
4898                                       Op0I->getOperand(1)->getName()+".not");
4899           InsertNewInstBefore(NotY, I);
4900           if (Op0I->getOpcode() == Instruction::And)
4901             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4902           else
4903             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4904         }
4905       }
4906     }
4907   }
4908   
4909   
4910   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4911     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4912       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4913       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4914         return new ICmpInst(ICI->getInversePredicate(),
4915                             ICI->getOperand(0), ICI->getOperand(1));
4916
4917       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4918         return new FCmpInst(FCI->getInversePredicate(),
4919                             FCI->getOperand(0), FCI->getOperand(1));
4920     }
4921
4922     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4923     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4924       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4925         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4926           Instruction::CastOps Opcode = Op0C->getOpcode();
4927           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4928             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4929                                              Op0C->getDestTy())) {
4930               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4931                                      CI->getOpcode(), CI->getInversePredicate(),
4932                                      CI->getOperand(0), CI->getOperand(1)), I);
4933               NewCI->takeName(CI);
4934               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4935             }
4936           }
4937         }
4938       }
4939     }
4940
4941     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4942       // ~(c-X) == X-c-1 == X+(-c-1)
4943       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4944         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4945           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4946           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4947                                               ConstantInt::get(I.getType(), 1));
4948           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4949         }
4950           
4951       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4952         if (Op0I->getOpcode() == Instruction::Add) {
4953           // ~(X-c) --> (-c-1)-X
4954           if (RHS->isAllOnesValue()) {
4955             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4956             return BinaryOperator::CreateSub(
4957                            ConstantExpr::getSub(NegOp0CI,
4958                                              ConstantInt::get(I.getType(), 1)),
4959                                           Op0I->getOperand(0));
4960           } else if (RHS->getValue().isSignBit()) {
4961             // (X + C) ^ signbit -> (X + C + signbit)
4962             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4963             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4964
4965           }
4966         } else if (Op0I->getOpcode() == Instruction::Or) {
4967           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4968           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4969             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4970             // Anything in both C1 and C2 is known to be zero, remove it from
4971             // NewRHS.
4972             Constant *CommonBits = And(Op0CI, RHS);
4973             NewRHS = ConstantExpr::getAnd(NewRHS, 
4974                                           ConstantExpr::getNot(CommonBits));
4975             AddToWorkList(Op0I);
4976             I.setOperand(0, Op0I->getOperand(0));
4977             I.setOperand(1, NewRHS);
4978             return &I;
4979           }
4980         }
4981       }
4982     }
4983
4984     // Try to fold constant and into select arguments.
4985     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4986       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4987         return R;
4988     if (isa<PHINode>(Op0))
4989       if (Instruction *NV = FoldOpIntoPhi(I))
4990         return NV;
4991   }
4992
4993   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4994     if (X == Op1)
4995       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4996
4997   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4998     if (X == Op0)
4999       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5000
5001   
5002   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5003   if (Op1I) {
5004     Value *A, *B;
5005     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5006       if (A == Op0) {              // B^(B|A) == (A|B)^B
5007         Op1I->swapOperands();
5008         I.swapOperands();
5009         std::swap(Op0, Op1);
5010       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5011         I.swapOperands();     // Simplified below.
5012         std::swap(Op0, Op1);
5013       }
5014     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5015       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5016     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5017       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5018     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5019       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5020         Op1I->swapOperands();
5021         std::swap(A, B);
5022       }
5023       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5024         I.swapOperands();     // Simplified below.
5025         std::swap(Op0, Op1);
5026       }
5027     }
5028   }
5029   
5030   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5031   if (Op0I) {
5032     Value *A, *B;
5033     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5034       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5035         std::swap(A, B);
5036       if (B == Op1) {                                // (A|B)^B == A & ~B
5037         Instruction *NotB =
5038           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5039         return BinaryOperator::CreateAnd(A, NotB);
5040       }
5041     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5042       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5043     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5044       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5045     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5046       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5047         std::swap(A, B);
5048       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5049           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5050         Instruction *N =
5051           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5052         return BinaryOperator::CreateAnd(N, Op1);
5053       }
5054     }
5055   }
5056   
5057   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5058   if (Op0I && Op1I && Op0I->isShift() && 
5059       Op0I->getOpcode() == Op1I->getOpcode() && 
5060       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5061       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5062     Instruction *NewOp =
5063       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5064                                                     Op1I->getOperand(0),
5065                                                     Op0I->getName()), I);
5066     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5067                                   Op1I->getOperand(1));
5068   }
5069     
5070   if (Op0I && Op1I) {
5071     Value *A, *B, *C, *D;
5072     // (A & B)^(A | B) -> A ^ B
5073     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5074         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5075       if ((A == C && B == D) || (A == D && B == C)) 
5076         return BinaryOperator::CreateXor(A, B);
5077     }
5078     // (A | B)^(A & B) -> A ^ B
5079     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5080         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5081       if ((A == C && B == D) || (A == D && B == C)) 
5082         return BinaryOperator::CreateXor(A, B);
5083     }
5084     
5085     // (A & B)^(C & D)
5086     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5087         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5088         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5089       // (X & Y)^(X & Y) -> (Y^Z) & X
5090       Value *X = 0, *Y = 0, *Z = 0;
5091       if (A == C)
5092         X = A, Y = B, Z = D;
5093       else if (A == D)
5094         X = A, Y = B, Z = C;
5095       else if (B == C)
5096         X = B, Y = A, Z = D;
5097       else if (B == D)
5098         X = B, Y = A, Z = C;
5099       
5100       if (X) {
5101         Instruction *NewOp =
5102         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5103         return BinaryOperator::CreateAnd(NewOp, X);
5104       }
5105     }
5106   }
5107     
5108   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5109   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5110     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5111       return R;
5112
5113   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5114   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5115     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5116       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5117         const Type *SrcTy = Op0C->getOperand(0)->getType();
5118         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5119             // Only do this if the casts both really cause code to be generated.
5120             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5121                               I.getType(), TD) &&
5122             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5123                               I.getType(), TD)) {
5124           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5125                                                          Op1C->getOperand(0),
5126                                                          I.getName());
5127           InsertNewInstBefore(NewOp, I);
5128           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5129         }
5130       }
5131   }
5132
5133   return Changed ? &I : 0;
5134 }
5135
5136 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5137 /// overflowed for this type.
5138 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5139                             ConstantInt *In2, bool IsSigned = false) {
5140   Result = cast<ConstantInt>(Add(In1, In2));
5141
5142   if (IsSigned)
5143     if (In2->getValue().isNegative())
5144       return Result->getValue().sgt(In1->getValue());
5145     else
5146       return Result->getValue().slt(In1->getValue());
5147   else
5148     return Result->getValue().ult(In1->getValue());
5149 }
5150
5151 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5152 /// overflowed for this type.
5153 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5154                             ConstantInt *In2, bool IsSigned = false) {
5155   Result = cast<ConstantInt>(Subtract(In1, In2));
5156
5157   if (IsSigned)
5158     if (In2->getValue().isNegative())
5159       return Result->getValue().slt(In1->getValue());
5160     else
5161       return Result->getValue().sgt(In1->getValue());
5162   else
5163     return Result->getValue().ugt(In1->getValue());
5164 }
5165
5166 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5167 /// code necessary to compute the offset from the base pointer (without adding
5168 /// in the base pointer).  Return the result as a signed integer of intptr size.
5169 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5170   TargetData &TD = IC.getTargetData();
5171   gep_type_iterator GTI = gep_type_begin(GEP);
5172   const Type *IntPtrTy = TD.getIntPtrType();
5173   Value *Result = Constant::getNullValue(IntPtrTy);
5174
5175   // Build a mask for high order bits.
5176   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5177   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5178
5179   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5180        ++i, ++GTI) {
5181     Value *Op = *i;
5182     uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
5183     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5184       if (OpC->isZero()) continue;
5185       
5186       // Handle a struct index, which adds its field offset to the pointer.
5187       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5188         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5189         
5190         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5191           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5192         else
5193           Result = IC.InsertNewInstBefore(
5194                    BinaryOperator::CreateAdd(Result,
5195                                              ConstantInt::get(IntPtrTy, Size),
5196                                              GEP->getName()+".offs"), I);
5197         continue;
5198       }
5199       
5200       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5201       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5202       Scale = ConstantExpr::getMul(OC, Scale);
5203       if (Constant *RC = dyn_cast<Constant>(Result))
5204         Result = ConstantExpr::getAdd(RC, Scale);
5205       else {
5206         // Emit an add instruction.
5207         Result = IC.InsertNewInstBefore(
5208            BinaryOperator::CreateAdd(Result, Scale,
5209                                      GEP->getName()+".offs"), I);
5210       }
5211       continue;
5212     }
5213     // Convert to correct type.
5214     if (Op->getType() != IntPtrTy) {
5215       if (Constant *OpC = dyn_cast<Constant>(Op))
5216         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5217       else
5218         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5219                                                  Op->getName()+".c"), I);
5220     }
5221     if (Size != 1) {
5222       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5223       if (Constant *OpC = dyn_cast<Constant>(Op))
5224         Op = ConstantExpr::getMul(OpC, Scale);
5225       else    // We'll let instcombine(mul) convert this to a shl if possible.
5226         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5227                                                   GEP->getName()+".idx"), I);
5228     }
5229
5230     // Emit an add instruction.
5231     if (isa<Constant>(Op) && isa<Constant>(Result))
5232       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5233                                     cast<Constant>(Result));
5234     else
5235       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5236                                                   GEP->getName()+".offs"), I);
5237   }
5238   return Result;
5239 }
5240
5241
5242 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5243 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5244 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5245 /// complex, and scales are involved.  The above expression would also be legal
5246 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5247 /// later form is less amenable to optimization though, and we are allowed to
5248 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5249 ///
5250 /// If we can't emit an optimized form for this expression, this returns null.
5251 /// 
5252 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5253                                           InstCombiner &IC) {
5254   TargetData &TD = IC.getTargetData();
5255   gep_type_iterator GTI = gep_type_begin(GEP);
5256
5257   // Check to see if this gep only has a single variable index.  If so, and if
5258   // any constant indices are a multiple of its scale, then we can compute this
5259   // in terms of the scale of the variable index.  For example, if the GEP
5260   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5261   // because the expression will cross zero at the same point.
5262   unsigned i, e = GEP->getNumOperands();
5263   int64_t Offset = 0;
5264   for (i = 1; i != e; ++i, ++GTI) {
5265     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5266       // Compute the aggregate offset of constant indices.
5267       if (CI->isZero()) continue;
5268
5269       // Handle a struct index, which adds its field offset to the pointer.
5270       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5271         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5272       } else {
5273         uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5274         Offset += Size*CI->getSExtValue();
5275       }
5276     } else {
5277       // Found our variable index.
5278       break;
5279     }
5280   }
5281   
5282   // If there are no variable indices, we must have a constant offset, just
5283   // evaluate it the general way.
5284   if (i == e) return 0;
5285   
5286   Value *VariableIdx = GEP->getOperand(i);
5287   // Determine the scale factor of the variable element.  For example, this is
5288   // 4 if the variable index is into an array of i32.
5289   uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
5290   
5291   // Verify that there are no other variable indices.  If so, emit the hard way.
5292   for (++i, ++GTI; i != e; ++i, ++GTI) {
5293     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5294     if (!CI) return 0;
5295    
5296     // Compute the aggregate offset of constant indices.
5297     if (CI->isZero()) continue;
5298     
5299     // Handle a struct index, which adds its field offset to the pointer.
5300     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5301       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5302     } else {
5303       uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5304       Offset += Size*CI->getSExtValue();
5305     }
5306   }
5307   
5308   // Okay, we know we have a single variable index, which must be a
5309   // pointer/array/vector index.  If there is no offset, life is simple, return
5310   // the index.
5311   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5312   if (Offset == 0) {
5313     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5314     // we don't need to bother extending: the extension won't affect where the
5315     // computation crosses zero.
5316     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5317       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5318                                   VariableIdx->getNameStart(), &I);
5319     return VariableIdx;
5320   }
5321   
5322   // Otherwise, there is an index.  The computation we will do will be modulo
5323   // the pointer size, so get it.
5324   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5325   
5326   Offset &= PtrSizeMask;
5327   VariableScale &= PtrSizeMask;
5328
5329   // To do this transformation, any constant index must be a multiple of the
5330   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5331   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5332   // multiple of the variable scale.
5333   int64_t NewOffs = Offset / (int64_t)VariableScale;
5334   if (Offset != NewOffs*(int64_t)VariableScale)
5335     return 0;
5336
5337   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5338   const Type *IntPtrTy = TD.getIntPtrType();
5339   if (VariableIdx->getType() != IntPtrTy)
5340     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5341                                               true /*SExt*/, 
5342                                               VariableIdx->getNameStart(), &I);
5343   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5344   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5345 }
5346
5347
5348 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5349 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5350 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5351                                        ICmpInst::Predicate Cond,
5352                                        Instruction &I) {
5353   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5354
5355   // Look through bitcasts.
5356   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5357     RHS = BCI->getOperand(0);
5358
5359   Value *PtrBase = GEPLHS->getOperand(0);
5360   if (PtrBase == RHS) {
5361     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5362     // This transformation (ignoring the base and scales) is valid because we
5363     // know pointers can't overflow.  See if we can output an optimized form.
5364     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5365     
5366     // If not, synthesize the offset the hard way.
5367     if (Offset == 0)
5368       Offset = EmitGEPOffset(GEPLHS, I, *this);
5369     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5370                         Constant::getNullValue(Offset->getType()));
5371   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5372     // If the base pointers are different, but the indices are the same, just
5373     // compare the base pointer.
5374     if (PtrBase != GEPRHS->getOperand(0)) {
5375       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5376       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5377                         GEPRHS->getOperand(0)->getType();
5378       if (IndicesTheSame)
5379         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5380           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5381             IndicesTheSame = false;
5382             break;
5383           }
5384
5385       // If all indices are the same, just compare the base pointers.
5386       if (IndicesTheSame)
5387         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5388                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5389
5390       // Otherwise, the base pointers are different and the indices are
5391       // different, bail out.
5392       return 0;
5393     }
5394
5395     // If one of the GEPs has all zero indices, recurse.
5396     bool AllZeros = true;
5397     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5398       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5399           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5400         AllZeros = false;
5401         break;
5402       }
5403     if (AllZeros)
5404       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5405                           ICmpInst::getSwappedPredicate(Cond), I);
5406
5407     // If the other GEP has all zero indices, recurse.
5408     AllZeros = true;
5409     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5410       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5411           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5412         AllZeros = false;
5413         break;
5414       }
5415     if (AllZeros)
5416       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5417
5418     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5419       // If the GEPs only differ by one index, compare it.
5420       unsigned NumDifferences = 0;  // Keep track of # differences.
5421       unsigned DiffOperand = 0;     // The operand that differs.
5422       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5423         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5424           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5425                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5426             // Irreconcilable differences.
5427             NumDifferences = 2;
5428             break;
5429           } else {
5430             if (NumDifferences++) break;
5431             DiffOperand = i;
5432           }
5433         }
5434
5435       if (NumDifferences == 0)   // SAME GEP?
5436         return ReplaceInstUsesWith(I, // No comparison is needed here.
5437                                    ConstantInt::get(Type::Int1Ty,
5438                                              ICmpInst::isTrueWhenEqual(Cond)));
5439
5440       else if (NumDifferences == 1) {
5441         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5442         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5443         // Make sure we do a signed comparison here.
5444         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5445       }
5446     }
5447
5448     // Only lower this if the icmp is the only user of the GEP or if we expect
5449     // the result to fold to a constant!
5450     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5451         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5452       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5453       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5454       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5455       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5456     }
5457   }
5458   return 0;
5459 }
5460
5461 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5462 ///
5463 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5464                                                 Instruction *LHSI,
5465                                                 Constant *RHSC) {
5466   if (!isa<ConstantFP>(RHSC)) return 0;
5467   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5468   
5469   // Get the width of the mantissa.  We don't want to hack on conversions that
5470   // might lose information from the integer, e.g. "i64 -> float"
5471   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5472   if (MantissaWidth == -1) return 0;  // Unknown.
5473   
5474   // Check to see that the input is converted from an integer type that is small
5475   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5476   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5477   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5478   
5479   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5480   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5481   if (LHSUnsigned)
5482     ++InputSize;
5483   
5484   // If the conversion would lose info, don't hack on this.
5485   if ((int)InputSize > MantissaWidth)
5486     return 0;
5487   
5488   // Otherwise, we can potentially simplify the comparison.  We know that it
5489   // will always come through as an integer value and we know the constant is
5490   // not a NAN (it would have been previously simplified).
5491   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5492   
5493   ICmpInst::Predicate Pred;
5494   switch (I.getPredicate()) {
5495   default: assert(0 && "Unexpected predicate!");
5496   case FCmpInst::FCMP_UEQ:
5497   case FCmpInst::FCMP_OEQ:
5498     Pred = ICmpInst::ICMP_EQ;
5499     break;
5500   case FCmpInst::FCMP_UGT:
5501   case FCmpInst::FCMP_OGT:
5502     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5503     break;
5504   case FCmpInst::FCMP_UGE:
5505   case FCmpInst::FCMP_OGE:
5506     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5507     break;
5508   case FCmpInst::FCMP_ULT:
5509   case FCmpInst::FCMP_OLT:
5510     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5511     break;
5512   case FCmpInst::FCMP_ULE:
5513   case FCmpInst::FCMP_OLE:
5514     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5515     break;
5516   case FCmpInst::FCMP_UNE:
5517   case FCmpInst::FCMP_ONE:
5518     Pred = ICmpInst::ICMP_NE;
5519     break;
5520   case FCmpInst::FCMP_ORD:
5521     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5522   case FCmpInst::FCMP_UNO:
5523     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5524   }
5525   
5526   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5527   
5528   // Now we know that the APFloat is a normal number, zero or inf.
5529   
5530   // See if the FP constant is too large for the integer.  For example,
5531   // comparing an i8 to 300.0.
5532   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5533   
5534   if (!LHSUnsigned) {
5535     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5536     // and large values.
5537     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5538     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5539                           APFloat::rmNearestTiesToEven);
5540     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5541       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5542           Pred == ICmpInst::ICMP_SLE)
5543         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5544       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5545     }
5546   } else {
5547     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5548     // +INF and large values.
5549     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5550     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5551                           APFloat::rmNearestTiesToEven);
5552     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5553       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5554           Pred == ICmpInst::ICMP_ULE)
5555         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5556       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5557     }
5558   }
5559   
5560   if (!LHSUnsigned) {
5561     // See if the RHS value is < SignedMin.
5562     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5563     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5564                           APFloat::rmNearestTiesToEven);
5565     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5566       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5567           Pred == ICmpInst::ICMP_SGE)
5568         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5569       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5570     }
5571   }
5572
5573   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5574   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5575   // casting the FP value to the integer value and back, checking for equality.
5576   // Don't do this for zero, because -0.0 is not fractional.
5577   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5578   if (!RHS.isZero() &&
5579       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5580     // If we had a comparison against a fractional value, we have to adjust the
5581     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5582     // at this point.
5583     switch (Pred) {
5584     default: assert(0 && "Unexpected integer comparison!");
5585     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5586       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5587     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5588       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5589     case ICmpInst::ICMP_ULE:
5590       // (float)int <= 4.4   --> int <= 4
5591       // (float)int <= -4.4  --> false
5592       if (RHS.isNegative())
5593         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5594       break;
5595     case ICmpInst::ICMP_SLE:
5596       // (float)int <= 4.4   --> int <= 4
5597       // (float)int <= -4.4  --> int < -4
5598       if (RHS.isNegative())
5599         Pred = ICmpInst::ICMP_SLT;
5600       break;
5601     case ICmpInst::ICMP_ULT:
5602       // (float)int < -4.4   --> false
5603       // (float)int < 4.4    --> int <= 4
5604       if (RHS.isNegative())
5605         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5606       Pred = ICmpInst::ICMP_ULE;
5607       break;
5608     case ICmpInst::ICMP_SLT:
5609       // (float)int < -4.4   --> int < -4
5610       // (float)int < 4.4    --> int <= 4
5611       if (!RHS.isNegative())
5612         Pred = ICmpInst::ICMP_SLE;
5613       break;
5614     case ICmpInst::ICMP_UGT:
5615       // (float)int > 4.4    --> int > 4
5616       // (float)int > -4.4   --> true
5617       if (RHS.isNegative())
5618         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5619       break;
5620     case ICmpInst::ICMP_SGT:
5621       // (float)int > 4.4    --> int > 4
5622       // (float)int > -4.4   --> int >= -4
5623       if (RHS.isNegative())
5624         Pred = ICmpInst::ICMP_SGE;
5625       break;
5626     case ICmpInst::ICMP_UGE:
5627       // (float)int >= -4.4   --> true
5628       // (float)int >= 4.4    --> int > 4
5629       if (!RHS.isNegative())
5630         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5631       Pred = ICmpInst::ICMP_UGT;
5632       break;
5633     case ICmpInst::ICMP_SGE:
5634       // (float)int >= -4.4   --> int >= -4
5635       // (float)int >= 4.4    --> int > 4
5636       if (!RHS.isNegative())
5637         Pred = ICmpInst::ICMP_SGT;
5638       break;
5639     }
5640   }
5641
5642   // Lower this FP comparison into an appropriate integer version of the
5643   // comparison.
5644   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5645 }
5646
5647 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5648   bool Changed = SimplifyCompare(I);
5649   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5650
5651   // Fold trivial predicates.
5652   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5653     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5654   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5655     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5656   
5657   // Simplify 'fcmp pred X, X'
5658   if (Op0 == Op1) {
5659     switch (I.getPredicate()) {
5660     default: assert(0 && "Unknown predicate!");
5661     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5662     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5663     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5664       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5665     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5666     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5667     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5668       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5669       
5670     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5671     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5672     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5673     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5674       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5675       I.setPredicate(FCmpInst::FCMP_UNO);
5676       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5677       return &I;
5678       
5679     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5680     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5681     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5682     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5683       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5684       I.setPredicate(FCmpInst::FCMP_ORD);
5685       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5686       return &I;
5687     }
5688   }
5689     
5690   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5691     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5692
5693   // Handle fcmp with constant RHS
5694   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5695     // If the constant is a nan, see if we can fold the comparison based on it.
5696     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5697       if (CFP->getValueAPF().isNaN()) {
5698         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5699           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5700         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5701                "Comparison must be either ordered or unordered!");
5702         // True if unordered.
5703         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5704       }
5705     }
5706     
5707     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5708       switch (LHSI->getOpcode()) {
5709       case Instruction::PHI:
5710         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5711         // block.  If in the same block, we're encouraging jump threading.  If
5712         // not, we are just pessimizing the code by making an i1 phi.
5713         if (LHSI->getParent() == I.getParent())
5714           if (Instruction *NV = FoldOpIntoPhi(I))
5715             return NV;
5716         break;
5717       case Instruction::SIToFP:
5718       case Instruction::UIToFP:
5719         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5720           return NV;
5721         break;
5722       case Instruction::Select:
5723         // If either operand of the select is a constant, we can fold the
5724         // comparison into the select arms, which will cause one to be
5725         // constant folded and the select turned into a bitwise or.
5726         Value *Op1 = 0, *Op2 = 0;
5727         if (LHSI->hasOneUse()) {
5728           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5729             // Fold the known value into the constant operand.
5730             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5731             // Insert a new FCmp of the other select operand.
5732             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5733                                                       LHSI->getOperand(2), RHSC,
5734                                                       I.getName()), I);
5735           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5736             // Fold the known value into the constant operand.
5737             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5738             // Insert a new FCmp of the other select operand.
5739             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5740                                                       LHSI->getOperand(1), RHSC,
5741                                                       I.getName()), I);
5742           }
5743         }
5744
5745         if (Op1)
5746           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5747         break;
5748       }
5749   }
5750
5751   return Changed ? &I : 0;
5752 }
5753
5754 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5755   bool Changed = SimplifyCompare(I);
5756   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5757   const Type *Ty = Op0->getType();
5758
5759   // icmp X, X
5760   if (Op0 == Op1)
5761     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5762                                                    I.isTrueWhenEqual()));
5763
5764   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5765     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5766   
5767   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5768   // addresses never equal each other!  We already know that Op0 != Op1.
5769   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5770        isa<ConstantPointerNull>(Op0)) &&
5771       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5772        isa<ConstantPointerNull>(Op1)))
5773     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5774                                                    !I.isTrueWhenEqual()));
5775
5776   // icmp's with boolean values can always be turned into bitwise operations
5777   if (Ty == Type::Int1Ty) {
5778     switch (I.getPredicate()) {
5779     default: assert(0 && "Invalid icmp instruction!");
5780     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5781       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5782       InsertNewInstBefore(Xor, I);
5783       return BinaryOperator::CreateNot(Xor);
5784     }
5785     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5786       return BinaryOperator::CreateXor(Op0, Op1);
5787
5788     case ICmpInst::ICMP_UGT:
5789       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5790       // FALL THROUGH
5791     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5792       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5793       InsertNewInstBefore(Not, I);
5794       return BinaryOperator::CreateAnd(Not, Op1);
5795     }
5796     case ICmpInst::ICMP_SGT:
5797       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5798       // FALL THROUGH
5799     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5800       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5801       InsertNewInstBefore(Not, I);
5802       return BinaryOperator::CreateAnd(Not, Op0);
5803     }
5804     case ICmpInst::ICMP_UGE:
5805       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5806       // FALL THROUGH
5807     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5808       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5809       InsertNewInstBefore(Not, I);
5810       return BinaryOperator::CreateOr(Not, Op1);
5811     }
5812     case ICmpInst::ICMP_SGE:
5813       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5814       // FALL THROUGH
5815     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5816       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5817       InsertNewInstBefore(Not, I);
5818       return BinaryOperator::CreateOr(Not, Op0);
5819     }
5820     }
5821   }
5822
5823   // See if we are doing a comparison with a constant.
5824   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5825     Value *A, *B;
5826     
5827     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5828     if (I.isEquality() && CI->isNullValue() &&
5829         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5830       // (icmp cond A B) if cond is equality
5831       return new ICmpInst(I.getPredicate(), A, B);
5832     }
5833     
5834     // If we have an icmp le or icmp ge instruction, turn it into the
5835     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5836     // them being folded in the code below.
5837     switch (I.getPredicate()) {
5838     default: break;
5839     case ICmpInst::ICMP_ULE:
5840       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5841         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5842       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5843     case ICmpInst::ICMP_SLE:
5844       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5845         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5846       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5847     case ICmpInst::ICMP_UGE:
5848       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5849         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5850       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5851     case ICmpInst::ICMP_SGE:
5852       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5853         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5854       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5855     }
5856     
5857     // See if we can fold the comparison based on range information we can get
5858     // by checking whether bits are known to be zero or one in the input.
5859     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5860     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5861     
5862     // If this comparison is a normal comparison, it demands all
5863     // bits, if it is a sign bit comparison, it only demands the sign bit.
5864     bool UnusedBit;
5865     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5866     
5867     if (SimplifyDemandedBits(I.getOperandUse(0), 
5868                              isSignBit ? APInt::getSignBit(BitWidth)
5869                                        : APInt::getAllOnesValue(BitWidth),
5870                              KnownZero, KnownOne, 0))
5871       return &I;
5872         
5873     // Given the known and unknown bits, compute a range that the LHS could be
5874     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5875     // EQ and NE we use unsigned values.
5876     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5877     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5878       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5879     else
5880       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5881     
5882     // If Min and Max are known to be the same, then SimplifyDemandedBits
5883     // figured out that the LHS is a constant.  Just constant fold this now so
5884     // that code below can assume that Min != Max.
5885     if (Min == Max)
5886       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5887                                                           ConstantInt::get(Min),
5888                                                           CI));
5889     
5890     // Based on the range information we know about the LHS, see if we can
5891     // simplify this comparison.  For example, (x&4) < 8  is always true.
5892     const APInt &RHSVal = CI->getValue();
5893     switch (I.getPredicate()) {  // LE/GE have been folded already.
5894     default: assert(0 && "Unknown icmp opcode!");
5895     case ICmpInst::ICMP_EQ:
5896       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5897         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5898       break;
5899     case ICmpInst::ICMP_NE:
5900       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5901         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5902       break;
5903     case ICmpInst::ICMP_ULT:
5904       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5905         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5906       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5907         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5908       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5909         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5910       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5911         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5912         
5913       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5914       if (CI->isMinValue(true))
5915         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5916                             ConstantInt::getAllOnesValue(Op0->getType()));
5917       break;
5918     case ICmpInst::ICMP_UGT:
5919       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5920         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5921       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5922         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5923         
5924       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5925         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5926       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5927         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5928       
5929       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5930       if (CI->isMaxValue(true))
5931         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5932                             ConstantInt::getNullValue(Op0->getType()));
5933       break;
5934     case ICmpInst::ICMP_SLT:
5935       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5936         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5937       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5938         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5939       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5940         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5941       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5942         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5943       break;
5944     case ICmpInst::ICMP_SGT: 
5945       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5946         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5947       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5948         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5949         
5950       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5951         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5952       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5953         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5954       break;
5955     }
5956   }
5957
5958   // Test if the ICmpInst instruction is used exclusively by a select as
5959   // part of a minimum or maximum operation. If so, refrain from doing
5960   // any other folding. This helps out other analyses which understand
5961   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5962   // and CodeGen. And in this case, at least one of the comparison
5963   // operands has at least one user besides the compare (the select),
5964   // which would often largely negate the benefit of folding anyway.
5965   if (I.hasOneUse())
5966     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5967       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5968           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5969         return 0;
5970
5971   // See if we are doing a comparison between a constant and an instruction that
5972   // can be folded into the comparison.
5973   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5974     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5975     // instruction, see if that instruction also has constants so that the 
5976     // instruction can be folded into the icmp 
5977     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5978       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5979         return Res;
5980   }
5981
5982   // Handle icmp with constant (but not simple integer constant) RHS
5983   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5984     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5985       switch (LHSI->getOpcode()) {
5986       case Instruction::GetElementPtr:
5987         if (RHSC->isNullValue()) {
5988           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5989           bool isAllZeros = true;
5990           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5991             if (!isa<Constant>(LHSI->getOperand(i)) ||
5992                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5993               isAllZeros = false;
5994               break;
5995             }
5996           if (isAllZeros)
5997             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5998                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5999         }
6000         break;
6001
6002       case Instruction::PHI:
6003         // Only fold icmp into the PHI if the phi and fcmp are in the same
6004         // block.  If in the same block, we're encouraging jump threading.  If
6005         // not, we are just pessimizing the code by making an i1 phi.
6006         if (LHSI->getParent() == I.getParent())
6007           if (Instruction *NV = FoldOpIntoPhi(I))
6008             return NV;
6009         break;
6010       case Instruction::Select: {
6011         // If either operand of the select is a constant, we can fold the
6012         // comparison into the select arms, which will cause one to be
6013         // constant folded and the select turned into a bitwise or.
6014         Value *Op1 = 0, *Op2 = 0;
6015         if (LHSI->hasOneUse()) {
6016           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6017             // Fold the known value into the constant operand.
6018             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6019             // Insert a new ICmp of the other select operand.
6020             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6021                                                    LHSI->getOperand(2), RHSC,
6022                                                    I.getName()), I);
6023           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6024             // Fold the known value into the constant operand.
6025             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6026             // Insert a new ICmp of the other select operand.
6027             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6028                                                    LHSI->getOperand(1), RHSC,
6029                                                    I.getName()), I);
6030           }
6031         }
6032
6033         if (Op1)
6034           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6035         break;
6036       }
6037       case Instruction::Malloc:
6038         // If we have (malloc != null), and if the malloc has a single use, we
6039         // can assume it is successful and remove the malloc.
6040         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6041           AddToWorkList(LHSI);
6042           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6043                                                          !I.isTrueWhenEqual()));
6044         }
6045         break;
6046       }
6047   }
6048
6049   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6050   if (User *GEP = dyn_castGetElementPtr(Op0))
6051     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6052       return NI;
6053   if (User *GEP = dyn_castGetElementPtr(Op1))
6054     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6055                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6056       return NI;
6057
6058   // Test to see if the operands of the icmp are casted versions of other
6059   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6060   // now.
6061   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6062     if (isa<PointerType>(Op0->getType()) && 
6063         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6064       // We keep moving the cast from the left operand over to the right
6065       // operand, where it can often be eliminated completely.
6066       Op0 = CI->getOperand(0);
6067
6068       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6069       // so eliminate it as well.
6070       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6071         Op1 = CI2->getOperand(0);
6072
6073       // If Op1 is a constant, we can fold the cast into the constant.
6074       if (Op0->getType() != Op1->getType()) {
6075         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6076           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6077         } else {
6078           // Otherwise, cast the RHS right before the icmp
6079           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6080         }
6081       }
6082       return new ICmpInst(I.getPredicate(), Op0, Op1);
6083     }
6084   }
6085   
6086   if (isa<CastInst>(Op0)) {
6087     // Handle the special case of: icmp (cast bool to X), <cst>
6088     // This comes up when you have code like
6089     //   int X = A < B;
6090     //   if (X) ...
6091     // For generality, we handle any zero-extension of any operand comparison
6092     // with a constant or another cast from the same type.
6093     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6094       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6095         return R;
6096   }
6097   
6098   // See if it's the same type of instruction on the left and right.
6099   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6100     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6101       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6102           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6103         switch (Op0I->getOpcode()) {
6104         default: break;
6105         case Instruction::Add:
6106         case Instruction::Sub:
6107         case Instruction::Xor:
6108           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6109             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6110                                 Op1I->getOperand(0));
6111           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6112           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6113             if (CI->getValue().isSignBit()) {
6114               ICmpInst::Predicate Pred = I.isSignedPredicate()
6115                                              ? I.getUnsignedPredicate()
6116                                              : I.getSignedPredicate();
6117               return new ICmpInst(Pred, Op0I->getOperand(0),
6118                                   Op1I->getOperand(0));
6119             }
6120             
6121             if (CI->getValue().isMaxSignedValue()) {
6122               ICmpInst::Predicate Pred = I.isSignedPredicate()
6123                                              ? I.getUnsignedPredicate()
6124                                              : I.getSignedPredicate();
6125               Pred = I.getSwappedPredicate(Pred);
6126               return new ICmpInst(Pred, Op0I->getOperand(0),
6127                                   Op1I->getOperand(0));
6128             }
6129           }
6130           break;
6131         case Instruction::Mul:
6132           if (!I.isEquality())
6133             break;
6134
6135           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6136             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6137             // Mask = -1 >> count-trailing-zeros(Cst).
6138             if (!CI->isZero() && !CI->isOne()) {
6139               const APInt &AP = CI->getValue();
6140               ConstantInt *Mask = ConstantInt::get(
6141                                       APInt::getLowBitsSet(AP.getBitWidth(),
6142                                                            AP.getBitWidth() -
6143                                                       AP.countTrailingZeros()));
6144               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6145                                                             Mask);
6146               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6147                                                             Mask);
6148               InsertNewInstBefore(And1, I);
6149               InsertNewInstBefore(And2, I);
6150               return new ICmpInst(I.getPredicate(), And1, And2);
6151             }
6152           }
6153           break;
6154         }
6155       }
6156     }
6157   }
6158   
6159   // ~x < ~y --> y < x
6160   { Value *A, *B;
6161     if (match(Op0, m_Not(m_Value(A))) &&
6162         match(Op1, m_Not(m_Value(B))))
6163       return new ICmpInst(I.getPredicate(), B, A);
6164   }
6165   
6166   if (I.isEquality()) {
6167     Value *A, *B, *C, *D;
6168     
6169     // -x == -y --> x == y
6170     if (match(Op0, m_Neg(m_Value(A))) &&
6171         match(Op1, m_Neg(m_Value(B))))
6172       return new ICmpInst(I.getPredicate(), A, B);
6173     
6174     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6175       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6176         Value *OtherVal = A == Op1 ? B : A;
6177         return new ICmpInst(I.getPredicate(), OtherVal,
6178                             Constant::getNullValue(A->getType()));
6179       }
6180
6181       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6182         // A^c1 == C^c2 --> A == C^(c1^c2)
6183         ConstantInt *C1, *C2;
6184         if (match(B, m_ConstantInt(C1)) &&
6185             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6186           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6187           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6188           return new ICmpInst(I.getPredicate(), A,
6189                               InsertNewInstBefore(Xor, I));
6190         }
6191         
6192         // A^B == A^D -> B == D
6193         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6194         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6195         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6196         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6197       }
6198     }
6199     
6200     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6201         (A == Op0 || B == Op0)) {
6202       // A == (A^B)  ->  B == 0
6203       Value *OtherVal = A == Op0 ? B : A;
6204       return new ICmpInst(I.getPredicate(), OtherVal,
6205                           Constant::getNullValue(A->getType()));
6206     }
6207
6208     // (A-B) == A  ->  B == 0
6209     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6210       return new ICmpInst(I.getPredicate(), B, 
6211                           Constant::getNullValue(B->getType()));
6212
6213     // A == (A-B)  ->  B == 0
6214     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6215       return new ICmpInst(I.getPredicate(), B,
6216                           Constant::getNullValue(B->getType()));
6217     
6218     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6219     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6220         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6221         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6222       Value *X = 0, *Y = 0, *Z = 0;
6223       
6224       if (A == C) {
6225         X = B; Y = D; Z = A;
6226       } else if (A == D) {
6227         X = B; Y = C; Z = A;
6228       } else if (B == C) {
6229         X = A; Y = D; Z = B;
6230       } else if (B == D) {
6231         X = A; Y = C; Z = B;
6232       }
6233       
6234       if (X) {   // Build (X^Y) & Z
6235         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6236         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6237         I.setOperand(0, Op1);
6238         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6239         return &I;
6240       }
6241     }
6242   }
6243   return Changed ? &I : 0;
6244 }
6245
6246
6247 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6248 /// and CmpRHS are both known to be integer constants.
6249 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6250                                           ConstantInt *DivRHS) {
6251   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6252   const APInt &CmpRHSV = CmpRHS->getValue();
6253   
6254   // FIXME: If the operand types don't match the type of the divide 
6255   // then don't attempt this transform. The code below doesn't have the
6256   // logic to deal with a signed divide and an unsigned compare (and
6257   // vice versa). This is because (x /s C1) <s C2  produces different 
6258   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6259   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6260   // work. :(  The if statement below tests that condition and bails 
6261   // if it finds it. 
6262   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6263   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6264     return 0;
6265   if (DivRHS->isZero())
6266     return 0; // The ProdOV computation fails on divide by zero.
6267   if (DivIsSigned && DivRHS->isAllOnesValue())
6268     return 0; // The overflow computation also screws up here
6269   if (DivRHS->isOne())
6270     return 0; // Not worth bothering, and eliminates some funny cases
6271               // with INT_MIN.
6272
6273   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6274   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6275   // C2 (CI). By solving for X we can turn this into a range check 
6276   // instead of computing a divide. 
6277   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6278
6279   // Determine if the product overflows by seeing if the product is
6280   // not equal to the divide. Make sure we do the same kind of divide
6281   // as in the LHS instruction that we're folding. 
6282   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6283                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6284
6285   // Get the ICmp opcode
6286   ICmpInst::Predicate Pred = ICI.getPredicate();
6287
6288   // Figure out the interval that is being checked.  For example, a comparison
6289   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6290   // Compute this interval based on the constants involved and the signedness of
6291   // the compare/divide.  This computes a half-open interval, keeping track of
6292   // whether either value in the interval overflows.  After analysis each
6293   // overflow variable is set to 0 if it's corresponding bound variable is valid
6294   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6295   int LoOverflow = 0, HiOverflow = 0;
6296   ConstantInt *LoBound = 0, *HiBound = 0;
6297   
6298   if (!DivIsSigned) {  // udiv
6299     // e.g. X/5 op 3  --> [15, 20)
6300     LoBound = Prod;
6301     HiOverflow = LoOverflow = ProdOV;
6302     if (!HiOverflow)
6303       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6304   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6305     if (CmpRHSV == 0) {       // (X / pos) op 0
6306       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6307       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6308       HiBound = DivRHS;
6309     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6310       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6311       HiOverflow = LoOverflow = ProdOV;
6312       if (!HiOverflow)
6313         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6314     } else {                       // (X / pos) op neg
6315       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6316       HiBound = AddOne(Prod);
6317       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6318       if (!LoOverflow) {
6319         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6320         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6321                                      true) ? -1 : 0;
6322        }
6323     }
6324   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6325     if (CmpRHSV == 0) {       // (X / neg) op 0
6326       // e.g. X/-5 op 0  --> [-4, 5)
6327       LoBound = AddOne(DivRHS);
6328       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6329       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6330         HiOverflow = 1;            // [INTMIN+1, overflow)
6331         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6332       }
6333     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6334       // e.g. X/-5 op 3  --> [-19, -14)
6335       HiBound = AddOne(Prod);
6336       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6337       if (!LoOverflow)
6338         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6339     } else {                       // (X / neg) op neg
6340       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6341       LoOverflow = HiOverflow = ProdOV;
6342       if (!HiOverflow)
6343         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6344     }
6345     
6346     // Dividing by a negative swaps the condition.  LT <-> GT
6347     Pred = ICmpInst::getSwappedPredicate(Pred);
6348   }
6349
6350   Value *X = DivI->getOperand(0);
6351   switch (Pred) {
6352   default: assert(0 && "Unhandled icmp opcode!");
6353   case ICmpInst::ICMP_EQ:
6354     if (LoOverflow && HiOverflow)
6355       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6356     else if (HiOverflow)
6357       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6358                           ICmpInst::ICMP_UGE, X, LoBound);
6359     else if (LoOverflow)
6360       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6361                           ICmpInst::ICMP_ULT, X, HiBound);
6362     else
6363       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6364   case ICmpInst::ICMP_NE:
6365     if (LoOverflow && HiOverflow)
6366       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6367     else if (HiOverflow)
6368       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6369                           ICmpInst::ICMP_ULT, X, LoBound);
6370     else if (LoOverflow)
6371       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6372                           ICmpInst::ICMP_UGE, X, HiBound);
6373     else
6374       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6375   case ICmpInst::ICMP_ULT:
6376   case ICmpInst::ICMP_SLT:
6377     if (LoOverflow == +1)   // Low bound is greater than input range.
6378       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6379     if (LoOverflow == -1)   // Low bound is less than input range.
6380       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6381     return new ICmpInst(Pred, X, LoBound);
6382   case ICmpInst::ICMP_UGT:
6383   case ICmpInst::ICMP_SGT:
6384     if (HiOverflow == +1)       // High bound greater than input range.
6385       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6386     else if (HiOverflow == -1)  // High bound less than input range.
6387       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6388     if (Pred == ICmpInst::ICMP_UGT)
6389       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6390     else
6391       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6392   }
6393 }
6394
6395
6396 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6397 ///
6398 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6399                                                           Instruction *LHSI,
6400                                                           ConstantInt *RHS) {
6401   const APInt &RHSV = RHS->getValue();
6402   
6403   switch (LHSI->getOpcode()) {
6404   case Instruction::Trunc:
6405     if (ICI.isEquality() && LHSI->hasOneUse()) {
6406       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6407       // of the high bits truncated out of x are known.
6408       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6409              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6410       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6411       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6412       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6413       
6414       // If all the high bits are known, we can do this xform.
6415       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6416         // Pull in the high bits from known-ones set.
6417         APInt NewRHS(RHS->getValue());
6418         NewRHS.zext(SrcBits);
6419         NewRHS |= KnownOne;
6420         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6421                             ConstantInt::get(NewRHS));
6422       }
6423     }
6424     break;
6425       
6426   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6427     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6428       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6429       // fold the xor.
6430       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6431           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6432         Value *CompareVal = LHSI->getOperand(0);
6433         
6434         // If the sign bit of the XorCST is not set, there is no change to
6435         // the operation, just stop using the Xor.
6436         if (!XorCST->getValue().isNegative()) {
6437           ICI.setOperand(0, CompareVal);
6438           AddToWorkList(LHSI);
6439           return &ICI;
6440         }
6441         
6442         // Was the old condition true if the operand is positive?
6443         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6444         
6445         // If so, the new one isn't.
6446         isTrueIfPositive ^= true;
6447         
6448         if (isTrueIfPositive)
6449           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6450         else
6451           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6452       }
6453
6454       if (LHSI->hasOneUse()) {
6455         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6456         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6457           const APInt &SignBit = XorCST->getValue();
6458           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6459                                          ? ICI.getUnsignedPredicate()
6460                                          : ICI.getSignedPredicate();
6461           return new ICmpInst(Pred, LHSI->getOperand(0),
6462                               ConstantInt::get(RHSV ^ SignBit));
6463         }
6464
6465         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6466         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6467           const APInt &NotSignBit = XorCST->getValue();
6468           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6469                                          ? ICI.getUnsignedPredicate()
6470                                          : ICI.getSignedPredicate();
6471           Pred = ICI.getSwappedPredicate(Pred);
6472           return new ICmpInst(Pred, LHSI->getOperand(0),
6473                               ConstantInt::get(RHSV ^ NotSignBit));
6474         }
6475       }
6476     }
6477     break;
6478   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6479     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6480         LHSI->getOperand(0)->hasOneUse()) {
6481       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6482       
6483       // If the LHS is an AND of a truncating cast, we can widen the
6484       // and/compare to be the input width without changing the value
6485       // produced, eliminating a cast.
6486       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6487         // We can do this transformation if either the AND constant does not
6488         // have its sign bit set or if it is an equality comparison. 
6489         // Extending a relational comparison when we're checking the sign
6490         // bit would not work.
6491         if (Cast->hasOneUse() &&
6492             (ICI.isEquality() ||
6493              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6494           uint32_t BitWidth = 
6495             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6496           APInt NewCST = AndCST->getValue();
6497           NewCST.zext(BitWidth);
6498           APInt NewCI = RHSV;
6499           NewCI.zext(BitWidth);
6500           Instruction *NewAnd = 
6501             BinaryOperator::CreateAnd(Cast->getOperand(0),
6502                                       ConstantInt::get(NewCST),LHSI->getName());
6503           InsertNewInstBefore(NewAnd, ICI);
6504           return new ICmpInst(ICI.getPredicate(), NewAnd,
6505                               ConstantInt::get(NewCI));
6506         }
6507       }
6508       
6509       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6510       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6511       // happens a LOT in code produced by the C front-end, for bitfield
6512       // access.
6513       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6514       if (Shift && !Shift->isShift())
6515         Shift = 0;
6516       
6517       ConstantInt *ShAmt;
6518       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6519       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6520       const Type *AndTy = AndCST->getType();          // Type of the and.
6521       
6522       // We can fold this as long as we can't shift unknown bits
6523       // into the mask.  This can only happen with signed shift
6524       // rights, as they sign-extend.
6525       if (ShAmt) {
6526         bool CanFold = Shift->isLogicalShift();
6527         if (!CanFold) {
6528           // To test for the bad case of the signed shr, see if any
6529           // of the bits shifted in could be tested after the mask.
6530           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6531           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6532           
6533           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6534           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6535                AndCST->getValue()) == 0)
6536             CanFold = true;
6537         }
6538         
6539         if (CanFold) {
6540           Constant *NewCst;
6541           if (Shift->getOpcode() == Instruction::Shl)
6542             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6543           else
6544             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6545           
6546           // Check to see if we are shifting out any of the bits being
6547           // compared.
6548           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6549             // If we shifted bits out, the fold is not going to work out.
6550             // As a special case, check to see if this means that the
6551             // result is always true or false now.
6552             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6553               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6554             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6555               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6556           } else {
6557             ICI.setOperand(1, NewCst);
6558             Constant *NewAndCST;
6559             if (Shift->getOpcode() == Instruction::Shl)
6560               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6561             else
6562               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6563             LHSI->setOperand(1, NewAndCST);
6564             LHSI->setOperand(0, Shift->getOperand(0));
6565             AddToWorkList(Shift); // Shift is dead.
6566             AddUsesToWorkList(ICI);
6567             return &ICI;
6568           }
6569         }
6570       }
6571       
6572       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6573       // preferable because it allows the C<<Y expression to be hoisted out
6574       // of a loop if Y is invariant and X is not.
6575       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6576           ICI.isEquality() && !Shift->isArithmeticShift() &&
6577           isa<Instruction>(Shift->getOperand(0))) {
6578         // Compute C << Y.
6579         Value *NS;
6580         if (Shift->getOpcode() == Instruction::LShr) {
6581           NS = BinaryOperator::CreateShl(AndCST, 
6582                                          Shift->getOperand(1), "tmp");
6583         } else {
6584           // Insert a logical shift.
6585           NS = BinaryOperator::CreateLShr(AndCST,
6586                                           Shift->getOperand(1), "tmp");
6587         }
6588         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6589         
6590         // Compute X & (C << Y).
6591         Instruction *NewAnd = 
6592           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6593         InsertNewInstBefore(NewAnd, ICI);
6594         
6595         ICI.setOperand(0, NewAnd);
6596         return &ICI;
6597       }
6598     }
6599     break;
6600     
6601   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6602     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6603     if (!ShAmt) break;
6604     
6605     uint32_t TypeBits = RHSV.getBitWidth();
6606     
6607     // Check that the shift amount is in range.  If not, don't perform
6608     // undefined shifts.  When the shift is visited it will be
6609     // simplified.
6610     if (ShAmt->uge(TypeBits))
6611       break;
6612     
6613     if (ICI.isEquality()) {
6614       // If we are comparing against bits always shifted out, the
6615       // comparison cannot succeed.
6616       Constant *Comp =
6617         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6618       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6619         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6620         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6621         return ReplaceInstUsesWith(ICI, Cst);
6622       }
6623       
6624       if (LHSI->hasOneUse()) {
6625         // Otherwise strength reduce the shift into an and.
6626         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6627         Constant *Mask =
6628           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6629         
6630         Instruction *AndI =
6631           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6632                                     Mask, LHSI->getName()+".mask");
6633         Value *And = InsertNewInstBefore(AndI, ICI);
6634         return new ICmpInst(ICI.getPredicate(), And,
6635                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6636       }
6637     }
6638     
6639     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6640     bool TrueIfSigned = false;
6641     if (LHSI->hasOneUse() &&
6642         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6643       // (X << 31) <s 0  --> (X&1) != 0
6644       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6645                                            (TypeBits-ShAmt->getZExtValue()-1));
6646       Instruction *AndI =
6647         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6648                                   Mask, LHSI->getName()+".mask");
6649       Value *And = InsertNewInstBefore(AndI, ICI);
6650       
6651       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6652                           And, Constant::getNullValue(And->getType()));
6653     }
6654     break;
6655   }
6656     
6657   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6658   case Instruction::AShr: {
6659     // Only handle equality comparisons of shift-by-constant.
6660     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6661     if (!ShAmt || !ICI.isEquality()) break;
6662
6663     // Check that the shift amount is in range.  If not, don't perform
6664     // undefined shifts.  When the shift is visited it will be
6665     // simplified.
6666     uint32_t TypeBits = RHSV.getBitWidth();
6667     if (ShAmt->uge(TypeBits))
6668       break;
6669     
6670     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6671       
6672     // If we are comparing against bits always shifted out, the
6673     // comparison cannot succeed.
6674     APInt Comp = RHSV << ShAmtVal;
6675     if (LHSI->getOpcode() == Instruction::LShr)
6676       Comp = Comp.lshr(ShAmtVal);
6677     else
6678       Comp = Comp.ashr(ShAmtVal);
6679     
6680     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6681       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6682       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6683       return ReplaceInstUsesWith(ICI, Cst);
6684     }
6685     
6686     // Otherwise, check to see if the bits shifted out are known to be zero.
6687     // If so, we can compare against the unshifted value:
6688     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6689     if (LHSI->hasOneUse() &&
6690         MaskedValueIsZero(LHSI->getOperand(0), 
6691                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6692       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6693                           ConstantExpr::getShl(RHS, ShAmt));
6694     }
6695       
6696     if (LHSI->hasOneUse()) {
6697       // Otherwise strength reduce the shift into an and.
6698       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6699       Constant *Mask = ConstantInt::get(Val);
6700       
6701       Instruction *AndI =
6702         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6703                                   Mask, LHSI->getName()+".mask");
6704       Value *And = InsertNewInstBefore(AndI, ICI);
6705       return new ICmpInst(ICI.getPredicate(), And,
6706                           ConstantExpr::getShl(RHS, ShAmt));
6707     }
6708     break;
6709   }
6710     
6711   case Instruction::SDiv:
6712   case Instruction::UDiv:
6713     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6714     // Fold this div into the comparison, producing a range check. 
6715     // Determine, based on the divide type, what the range is being 
6716     // checked.  If there is an overflow on the low or high side, remember 
6717     // it, otherwise compute the range [low, hi) bounding the new value.
6718     // See: InsertRangeTest above for the kinds of replacements possible.
6719     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6720       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6721                                           DivRHS))
6722         return R;
6723     break;
6724
6725   case Instruction::Add:
6726     // Fold: icmp pred (add, X, C1), C2
6727
6728     if (!ICI.isEquality()) {
6729       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6730       if (!LHSC) break;
6731       const APInt &LHSV = LHSC->getValue();
6732
6733       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6734                             .subtract(LHSV);
6735
6736       if (ICI.isSignedPredicate()) {
6737         if (CR.getLower().isSignBit()) {
6738           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6739                               ConstantInt::get(CR.getUpper()));
6740         } else if (CR.getUpper().isSignBit()) {
6741           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6742                               ConstantInt::get(CR.getLower()));
6743         }
6744       } else {
6745         if (CR.getLower().isMinValue()) {
6746           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6747                               ConstantInt::get(CR.getUpper()));
6748         } else if (CR.getUpper().isMinValue()) {
6749           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6750                               ConstantInt::get(CR.getLower()));
6751         }
6752       }
6753     }
6754     break;
6755   }
6756   
6757   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6758   if (ICI.isEquality()) {
6759     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6760     
6761     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6762     // the second operand is a constant, simplify a bit.
6763     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6764       switch (BO->getOpcode()) {
6765       case Instruction::SRem:
6766         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6767         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6768           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6769           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6770             Instruction *NewRem =
6771               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6772                                          BO->getName());
6773             InsertNewInstBefore(NewRem, ICI);
6774             return new ICmpInst(ICI.getPredicate(), NewRem, 
6775                                 Constant::getNullValue(BO->getType()));
6776           }
6777         }
6778         break;
6779       case Instruction::Add:
6780         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6781         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6782           if (BO->hasOneUse())
6783             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6784                                 Subtract(RHS, BOp1C));
6785         } else if (RHSV == 0) {
6786           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6787           // efficiently invertible, or if the add has just this one use.
6788           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6789           
6790           if (Value *NegVal = dyn_castNegVal(BOp1))
6791             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6792           else if (Value *NegVal = dyn_castNegVal(BOp0))
6793             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6794           else if (BO->hasOneUse()) {
6795             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6796             InsertNewInstBefore(Neg, ICI);
6797             Neg->takeName(BO);
6798             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6799           }
6800         }
6801         break;
6802       case Instruction::Xor:
6803         // For the xor case, we can xor two constants together, eliminating
6804         // the explicit xor.
6805         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6806           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6807                               ConstantExpr::getXor(RHS, BOC));
6808         
6809         // FALLTHROUGH
6810       case Instruction::Sub:
6811         // Replace (([sub|xor] A, B) != 0) with (A != B)
6812         if (RHSV == 0)
6813           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6814                               BO->getOperand(1));
6815         break;
6816         
6817       case Instruction::Or:
6818         // If bits are being or'd in that are not present in the constant we
6819         // are comparing against, then the comparison could never succeed!
6820         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6821           Constant *NotCI = ConstantExpr::getNot(RHS);
6822           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6823             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6824                                                              isICMP_NE));
6825         }
6826         break;
6827         
6828       case Instruction::And:
6829         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6830           // If bits are being compared against that are and'd out, then the
6831           // comparison can never succeed!
6832           if ((RHSV & ~BOC->getValue()) != 0)
6833             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6834                                                              isICMP_NE));
6835           
6836           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6837           if (RHS == BOC && RHSV.isPowerOf2())
6838             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6839                                 ICmpInst::ICMP_NE, LHSI,
6840                                 Constant::getNullValue(RHS->getType()));
6841           
6842           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6843           if (BOC->getValue().isSignBit()) {
6844             Value *X = BO->getOperand(0);
6845             Constant *Zero = Constant::getNullValue(X->getType());
6846             ICmpInst::Predicate pred = isICMP_NE ? 
6847               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6848             return new ICmpInst(pred, X, Zero);
6849           }
6850           
6851           // ((X & ~7) == 0) --> X < 8
6852           if (RHSV == 0 && isHighOnes(BOC)) {
6853             Value *X = BO->getOperand(0);
6854             Constant *NegX = ConstantExpr::getNeg(BOC);
6855             ICmpInst::Predicate pred = isICMP_NE ? 
6856               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6857             return new ICmpInst(pred, X, NegX);
6858           }
6859         }
6860       default: break;
6861       }
6862     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6863       // Handle icmp {eq|ne} <intrinsic>, intcst.
6864       if (II->getIntrinsicID() == Intrinsic::bswap) {
6865         AddToWorkList(II);
6866         ICI.setOperand(0, II->getOperand(1));
6867         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6868         return &ICI;
6869       }
6870     }
6871   }
6872   return 0;
6873 }
6874
6875 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6876 /// We only handle extending casts so far.
6877 ///
6878 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6879   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6880   Value *LHSCIOp        = LHSCI->getOperand(0);
6881   const Type *SrcTy     = LHSCIOp->getType();
6882   const Type *DestTy    = LHSCI->getType();
6883   Value *RHSCIOp;
6884
6885   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6886   // integer type is the same size as the pointer type.
6887   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6888       getTargetData().getPointerSizeInBits() == 
6889          cast<IntegerType>(DestTy)->getBitWidth()) {
6890     Value *RHSOp = 0;
6891     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6892       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6893     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6894       RHSOp = RHSC->getOperand(0);
6895       // If the pointer types don't match, insert a bitcast.
6896       if (LHSCIOp->getType() != RHSOp->getType())
6897         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6898     }
6899
6900     if (RHSOp)
6901       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6902   }
6903   
6904   // The code below only handles extension cast instructions, so far.
6905   // Enforce this.
6906   if (LHSCI->getOpcode() != Instruction::ZExt &&
6907       LHSCI->getOpcode() != Instruction::SExt)
6908     return 0;
6909
6910   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6911   bool isSignedCmp = ICI.isSignedPredicate();
6912
6913   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6914     // Not an extension from the same type?
6915     RHSCIOp = CI->getOperand(0);
6916     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6917       return 0;
6918     
6919     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6920     // and the other is a zext), then we can't handle this.
6921     if (CI->getOpcode() != LHSCI->getOpcode())
6922       return 0;
6923
6924     // Deal with equality cases early.
6925     if (ICI.isEquality())
6926       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6927
6928     // A signed comparison of sign extended values simplifies into a
6929     // signed comparison.
6930     if (isSignedCmp && isSignedExt)
6931       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6932
6933     // The other three cases all fold into an unsigned comparison.
6934     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6935   }
6936
6937   // If we aren't dealing with a constant on the RHS, exit early
6938   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6939   if (!CI)
6940     return 0;
6941
6942   // Compute the constant that would happen if we truncated to SrcTy then
6943   // reextended to DestTy.
6944   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6945   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6946
6947   // If the re-extended constant didn't change...
6948   if (Res2 == CI) {
6949     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6950     // For example, we might have:
6951     //    %A = sext short %X to uint
6952     //    %B = icmp ugt uint %A, 1330
6953     // It is incorrect to transform this into 
6954     //    %B = icmp ugt short %X, 1330 
6955     // because %A may have negative value. 
6956     //
6957     // However, we allow this when the compare is EQ/NE, because they are
6958     // signless.
6959     if (isSignedExt == isSignedCmp || ICI.isEquality())
6960       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6961     return 0;
6962   }
6963
6964   // The re-extended constant changed so the constant cannot be represented 
6965   // in the shorter type. Consequently, we cannot emit a simple comparison.
6966
6967   // First, handle some easy cases. We know the result cannot be equal at this
6968   // point so handle the ICI.isEquality() cases
6969   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6970     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6971   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6972     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6973
6974   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6975   // should have been folded away previously and not enter in here.
6976   Value *Result;
6977   if (isSignedCmp) {
6978     // We're performing a signed comparison.
6979     if (cast<ConstantInt>(CI)->getValue().isNegative())
6980       Result = ConstantInt::getFalse();          // X < (small) --> false
6981     else
6982       Result = ConstantInt::getTrue();           // X < (large) --> true
6983   } else {
6984     // We're performing an unsigned comparison.
6985     if (isSignedExt) {
6986       // We're performing an unsigned comp with a sign extended value.
6987       // This is true if the input is >= 0. [aka >s -1]
6988       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6989       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6990                                    NegOne, ICI.getName()), ICI);
6991     } else {
6992       // Unsigned extend & unsigned compare -> always true.
6993       Result = ConstantInt::getTrue();
6994     }
6995   }
6996
6997   // Finally, return the value computed.
6998   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6999       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7000     return ReplaceInstUsesWith(ICI, Result);
7001
7002   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7003           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7004          "ICmp should be folded!");
7005   if (Constant *CI = dyn_cast<Constant>(Result))
7006     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7007   return BinaryOperator::CreateNot(Result);
7008 }
7009
7010 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7011   return commonShiftTransforms(I);
7012 }
7013
7014 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7015   return commonShiftTransforms(I);
7016 }
7017
7018 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7019   if (Instruction *R = commonShiftTransforms(I))
7020     return R;
7021   
7022   Value *Op0 = I.getOperand(0);
7023   
7024   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7025   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7026     if (CSI->isAllOnesValue())
7027       return ReplaceInstUsesWith(I, CSI);
7028   
7029   // See if we can turn a signed shr into an unsigned shr.
7030   if (!isa<VectorType>(I.getType()) &&
7031       MaskedValueIsZero(Op0,
7032                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
7033     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7034   
7035   return 0;
7036 }
7037
7038 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7039   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7040   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7041
7042   // shl X, 0 == X and shr X, 0 == X
7043   // shl 0, X == 0 and shr 0, X == 0
7044   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7045       Op0 == Constant::getNullValue(Op0->getType()))
7046     return ReplaceInstUsesWith(I, Op0);
7047   
7048   if (isa<UndefValue>(Op0)) {            
7049     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7050       return ReplaceInstUsesWith(I, Op0);
7051     else                                    // undef << X -> 0, undef >>u X -> 0
7052       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7053   }
7054   if (isa<UndefValue>(Op1)) {
7055     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7056       return ReplaceInstUsesWith(I, Op0);          
7057     else                                     // X << undef, X >>u undef -> 0
7058       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7059   }
7060
7061   // Try to fold constant and into select arguments.
7062   if (isa<Constant>(Op0))
7063     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7064       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7065         return R;
7066
7067   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7068     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7069       return Res;
7070   return 0;
7071 }
7072
7073 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7074                                                BinaryOperator &I) {
7075   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7076
7077   // See if we can simplify any instructions used by the instruction whose sole 
7078   // purpose is to compute bits we don't care about.
7079   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7080   if (SimplifyDemandedInstructionBits(I))
7081     return &I;
7082   
7083   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7084   // of a signed value.
7085   //
7086   if (Op1->uge(TypeBits)) {
7087     if (I.getOpcode() != Instruction::AShr)
7088       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7089     else {
7090       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7091       return &I;
7092     }
7093   }
7094   
7095   // ((X*C1) << C2) == (X * (C1 << C2))
7096   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7097     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7098       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7099         return BinaryOperator::CreateMul(BO->getOperand(0),
7100                                          ConstantExpr::getShl(BOOp, Op1));
7101   
7102   // Try to fold constant and into select arguments.
7103   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7104     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7105       return R;
7106   if (isa<PHINode>(Op0))
7107     if (Instruction *NV = FoldOpIntoPhi(I))
7108       return NV;
7109   
7110   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7111   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7112     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7113     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7114     // place.  Don't try to do this transformation in this case.  Also, we
7115     // require that the input operand is a shift-by-constant so that we have
7116     // confidence that the shifts will get folded together.  We could do this
7117     // xform in more cases, but it is unlikely to be profitable.
7118     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7119         isa<ConstantInt>(TrOp->getOperand(1))) {
7120       // Okay, we'll do this xform.  Make the shift of shift.
7121       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7122       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7123                                                 I.getName());
7124       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7125
7126       // For logical shifts, the truncation has the effect of making the high
7127       // part of the register be zeros.  Emulate this by inserting an AND to
7128       // clear the top bits as needed.  This 'and' will usually be zapped by
7129       // other xforms later if dead.
7130       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7131       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7132       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7133       
7134       // The mask we constructed says what the trunc would do if occurring
7135       // between the shifts.  We want to know the effect *after* the second
7136       // shift.  We know that it is a logical shift by a constant, so adjust the
7137       // mask as appropriate.
7138       if (I.getOpcode() == Instruction::Shl)
7139         MaskV <<= Op1->getZExtValue();
7140       else {
7141         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7142         MaskV = MaskV.lshr(Op1->getZExtValue());
7143       }
7144
7145       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7146                                                    TI->getName());
7147       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7148
7149       // Return the value truncated to the interesting size.
7150       return new TruncInst(And, I.getType());
7151     }
7152   }
7153   
7154   if (Op0->hasOneUse()) {
7155     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7156       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7157       Value *V1, *V2;
7158       ConstantInt *CC;
7159       switch (Op0BO->getOpcode()) {
7160         default: break;
7161         case Instruction::Add:
7162         case Instruction::And:
7163         case Instruction::Or:
7164         case Instruction::Xor: {
7165           // These operators commute.
7166           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7167           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7168               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7169             Instruction *YS = BinaryOperator::CreateShl(
7170                                             Op0BO->getOperand(0), Op1,
7171                                             Op0BO->getName());
7172             InsertNewInstBefore(YS, I); // (Y << C)
7173             Instruction *X = 
7174               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7175                                      Op0BO->getOperand(1)->getName());
7176             InsertNewInstBefore(X, I);  // (X + (Y << C))
7177             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7178             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7179                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7180           }
7181           
7182           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7183           Value *Op0BOOp1 = Op0BO->getOperand(1);
7184           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7185               match(Op0BOOp1, 
7186                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7187                           m_ConstantInt(CC))) &&
7188               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7189             Instruction *YS = BinaryOperator::CreateShl(
7190                                                      Op0BO->getOperand(0), Op1,
7191                                                      Op0BO->getName());
7192             InsertNewInstBefore(YS, I); // (Y << C)
7193             Instruction *XM =
7194               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7195                                         V1->getName()+".mask");
7196             InsertNewInstBefore(XM, I); // X & (CC << C)
7197             
7198             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7199           }
7200         }
7201           
7202         // FALL THROUGH.
7203         case Instruction::Sub: {
7204           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7205           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7206               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7207             Instruction *YS = BinaryOperator::CreateShl(
7208                                                      Op0BO->getOperand(1), Op1,
7209                                                      Op0BO->getName());
7210             InsertNewInstBefore(YS, I); // (Y << C)
7211             Instruction *X =
7212               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7213                                      Op0BO->getOperand(0)->getName());
7214             InsertNewInstBefore(X, I);  // (X + (Y << C))
7215             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7216             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7217                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7218           }
7219           
7220           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7221           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7222               match(Op0BO->getOperand(0),
7223                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7224                           m_ConstantInt(CC))) && V2 == Op1 &&
7225               cast<BinaryOperator>(Op0BO->getOperand(0))
7226                   ->getOperand(0)->hasOneUse()) {
7227             Instruction *YS = BinaryOperator::CreateShl(
7228                                                      Op0BO->getOperand(1), Op1,
7229                                                      Op0BO->getName());
7230             InsertNewInstBefore(YS, I); // (Y << C)
7231             Instruction *XM =
7232               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7233                                         V1->getName()+".mask");
7234             InsertNewInstBefore(XM, I); // X & (CC << C)
7235             
7236             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7237           }
7238           
7239           break;
7240         }
7241       }
7242       
7243       
7244       // If the operand is an bitwise operator with a constant RHS, and the
7245       // shift is the only use, we can pull it out of the shift.
7246       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7247         bool isValid = true;     // Valid only for And, Or, Xor
7248         bool highBitSet = false; // Transform if high bit of constant set?
7249         
7250         switch (Op0BO->getOpcode()) {
7251           default: isValid = false; break;   // Do not perform transform!
7252           case Instruction::Add:
7253             isValid = isLeftShift;
7254             break;
7255           case Instruction::Or:
7256           case Instruction::Xor:
7257             highBitSet = false;
7258             break;
7259           case Instruction::And:
7260             highBitSet = true;
7261             break;
7262         }
7263         
7264         // If this is a signed shift right, and the high bit is modified
7265         // by the logical operation, do not perform the transformation.
7266         // The highBitSet boolean indicates the value of the high bit of
7267         // the constant which would cause it to be modified for this
7268         // operation.
7269         //
7270         if (isValid && I.getOpcode() == Instruction::AShr)
7271           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7272         
7273         if (isValid) {
7274           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7275           
7276           Instruction *NewShift =
7277             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7278           InsertNewInstBefore(NewShift, I);
7279           NewShift->takeName(Op0BO);
7280           
7281           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7282                                         NewRHS);
7283         }
7284       }
7285     }
7286   }
7287   
7288   // Find out if this is a shift of a shift by a constant.
7289   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7290   if (ShiftOp && !ShiftOp->isShift())
7291     ShiftOp = 0;
7292   
7293   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7294     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7295     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7296     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7297     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7298     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7299     Value *X = ShiftOp->getOperand(0);
7300     
7301     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7302     if (AmtSum > TypeBits)
7303       AmtSum = TypeBits;
7304     
7305     const IntegerType *Ty = cast<IntegerType>(I.getType());
7306     
7307     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7308     if (I.getOpcode() == ShiftOp->getOpcode()) {
7309       return BinaryOperator::Create(I.getOpcode(), X,
7310                                     ConstantInt::get(Ty, AmtSum));
7311     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7312                I.getOpcode() == Instruction::AShr) {
7313       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7314       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7315     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7316                I.getOpcode() == Instruction::LShr) {
7317       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7318       Instruction *Shift =
7319         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7320       InsertNewInstBefore(Shift, I);
7321
7322       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7323       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7324     }
7325     
7326     // Okay, if we get here, one shift must be left, and the other shift must be
7327     // right.  See if the amounts are equal.
7328     if (ShiftAmt1 == ShiftAmt2) {
7329       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7330       if (I.getOpcode() == Instruction::Shl) {
7331         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7332         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7333       }
7334       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7335       if (I.getOpcode() == Instruction::LShr) {
7336         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7337         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7338       }
7339       // We can simplify ((X << C) >>s C) into a trunc + sext.
7340       // NOTE: we could do this for any C, but that would make 'unusual' integer
7341       // types.  For now, just stick to ones well-supported by the code
7342       // generators.
7343       const Type *SExtType = 0;
7344       switch (Ty->getBitWidth() - ShiftAmt1) {
7345       case 1  :
7346       case 8  :
7347       case 16 :
7348       case 32 :
7349       case 64 :
7350       case 128:
7351         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7352         break;
7353       default: break;
7354       }
7355       if (SExtType) {
7356         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7357         InsertNewInstBefore(NewTrunc, I);
7358         return new SExtInst(NewTrunc, Ty);
7359       }
7360       // Otherwise, we can't handle it yet.
7361     } else if (ShiftAmt1 < ShiftAmt2) {
7362       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7363       
7364       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7365       if (I.getOpcode() == Instruction::Shl) {
7366         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7367                ShiftOp->getOpcode() == Instruction::AShr);
7368         Instruction *Shift =
7369           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7370         InsertNewInstBefore(Shift, I);
7371         
7372         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7373         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7374       }
7375       
7376       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7377       if (I.getOpcode() == Instruction::LShr) {
7378         assert(ShiftOp->getOpcode() == Instruction::Shl);
7379         Instruction *Shift =
7380           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7381         InsertNewInstBefore(Shift, I);
7382         
7383         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7384         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7385       }
7386       
7387       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7388     } else {
7389       assert(ShiftAmt2 < ShiftAmt1);
7390       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7391
7392       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7393       if (I.getOpcode() == Instruction::Shl) {
7394         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7395                ShiftOp->getOpcode() == Instruction::AShr);
7396         Instruction *Shift =
7397           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7398                                  ConstantInt::get(Ty, ShiftDiff));
7399         InsertNewInstBefore(Shift, I);
7400         
7401         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7402         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7403       }
7404       
7405       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7406       if (I.getOpcode() == Instruction::LShr) {
7407         assert(ShiftOp->getOpcode() == Instruction::Shl);
7408         Instruction *Shift =
7409           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7410         InsertNewInstBefore(Shift, I);
7411         
7412         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7413         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7414       }
7415       
7416       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7417     }
7418   }
7419   return 0;
7420 }
7421
7422
7423 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7424 /// expression.  If so, decompose it, returning some value X, such that Val is
7425 /// X*Scale+Offset.
7426 ///
7427 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7428                                         int &Offset) {
7429   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7430   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7431     Offset = CI->getZExtValue();
7432     Scale  = 0;
7433     return ConstantInt::get(Type::Int32Ty, 0);
7434   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7435     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7436       if (I->getOpcode() == Instruction::Shl) {
7437         // This is a value scaled by '1 << the shift amt'.
7438         Scale = 1U << RHS->getZExtValue();
7439         Offset = 0;
7440         return I->getOperand(0);
7441       } else if (I->getOpcode() == Instruction::Mul) {
7442         // This value is scaled by 'RHS'.
7443         Scale = RHS->getZExtValue();
7444         Offset = 0;
7445         return I->getOperand(0);
7446       } else if (I->getOpcode() == Instruction::Add) {
7447         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7448         // where C1 is divisible by C2.
7449         unsigned SubScale;
7450         Value *SubVal = 
7451           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7452         Offset += RHS->getZExtValue();
7453         Scale = SubScale;
7454         return SubVal;
7455       }
7456     }
7457   }
7458
7459   // Otherwise, we can't look past this.
7460   Scale = 1;
7461   Offset = 0;
7462   return Val;
7463 }
7464
7465
7466 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7467 /// try to eliminate the cast by moving the type information into the alloc.
7468 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7469                                                    AllocationInst &AI) {
7470   const PointerType *PTy = cast<PointerType>(CI.getType());
7471   
7472   // Remove any uses of AI that are dead.
7473   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7474   
7475   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7476     Instruction *User = cast<Instruction>(*UI++);
7477     if (isInstructionTriviallyDead(User)) {
7478       while (UI != E && *UI == User)
7479         ++UI; // If this instruction uses AI more than once, don't break UI.
7480       
7481       ++NumDeadInst;
7482       DOUT << "IC: DCE: " << *User;
7483       EraseInstFromFunction(*User);
7484     }
7485   }
7486   
7487   // Get the type really allocated and the type casted to.
7488   const Type *AllocElTy = AI.getAllocatedType();
7489   const Type *CastElTy = PTy->getElementType();
7490   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7491
7492   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7493   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7494   if (CastElTyAlign < AllocElTyAlign) return 0;
7495
7496   // If the allocation has multiple uses, only promote it if we are strictly
7497   // increasing the alignment of the resultant allocation.  If we keep it the
7498   // same, we open the door to infinite loops of various kinds.
7499   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7500
7501   uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7502   uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
7503   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7504
7505   // See if we can satisfy the modulus by pulling a scale out of the array
7506   // size argument.
7507   unsigned ArraySizeScale;
7508   int ArrayOffset;
7509   Value *NumElements = // See if the array size is a decomposable linear expr.
7510     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7511  
7512   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7513   // do the xform.
7514   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7515       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7516
7517   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7518   Value *Amt = 0;
7519   if (Scale == 1) {
7520     Amt = NumElements;
7521   } else {
7522     // If the allocation size is constant, form a constant mul expression
7523     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7524     if (isa<ConstantInt>(NumElements))
7525       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7526     // otherwise multiply the amount and the number of elements
7527     else if (Scale != 1) {
7528       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7529       Amt = InsertNewInstBefore(Tmp, AI);
7530     }
7531   }
7532   
7533   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7534     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7535     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7536     Amt = InsertNewInstBefore(Tmp, AI);
7537   }
7538   
7539   AllocationInst *New;
7540   if (isa<MallocInst>(AI))
7541     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7542   else
7543     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7544   InsertNewInstBefore(New, AI);
7545   New->takeName(&AI);
7546   
7547   // If the allocation has multiple uses, insert a cast and change all things
7548   // that used it to use the new cast.  This will also hack on CI, but it will
7549   // die soon.
7550   if (!AI.hasOneUse()) {
7551     AddUsesToWorkList(AI);
7552     // New is the allocation instruction, pointer typed. AI is the original
7553     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7554     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7555     InsertNewInstBefore(NewCast, AI);
7556     AI.replaceAllUsesWith(NewCast);
7557   }
7558   return ReplaceInstUsesWith(CI, New);
7559 }
7560
7561 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7562 /// and return it as type Ty without inserting any new casts and without
7563 /// changing the computed value.  This is used by code that tries to decide
7564 /// whether promoting or shrinking integer operations to wider or smaller types
7565 /// will allow us to eliminate a truncate or extend.
7566 ///
7567 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7568 /// extension operation if Ty is larger.
7569 ///
7570 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7571 /// should return true if trunc(V) can be computed by computing V in the smaller
7572 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7573 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7574 /// efficiently truncated.
7575 ///
7576 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7577 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7578 /// the final result.
7579 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7580                                               unsigned CastOpc,
7581                                               int &NumCastsRemoved){
7582   // We can always evaluate constants in another type.
7583   if (isa<ConstantInt>(V))
7584     return true;
7585   
7586   Instruction *I = dyn_cast<Instruction>(V);
7587   if (!I) return false;
7588   
7589   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7590   
7591   // If this is an extension or truncate, we can often eliminate it.
7592   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7593     // If this is a cast from the destination type, we can trivially eliminate
7594     // it, and this will remove a cast overall.
7595     if (I->getOperand(0)->getType() == Ty) {
7596       // If the first operand is itself a cast, and is eliminable, do not count
7597       // this as an eliminable cast.  We would prefer to eliminate those two
7598       // casts first.
7599       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7600         ++NumCastsRemoved;
7601       return true;
7602     }
7603   }
7604
7605   // We can't extend or shrink something that has multiple uses: doing so would
7606   // require duplicating the instruction in general, which isn't profitable.
7607   if (!I->hasOneUse()) return false;
7608
7609   unsigned Opc = I->getOpcode();
7610   switch (Opc) {
7611   case Instruction::Add:
7612   case Instruction::Sub:
7613   case Instruction::Mul:
7614   case Instruction::And:
7615   case Instruction::Or:
7616   case Instruction::Xor:
7617     // These operators can all arbitrarily be extended or truncated.
7618     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7619                                       NumCastsRemoved) &&
7620            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7621                                       NumCastsRemoved);
7622
7623   case Instruction::Shl:
7624     // If we are truncating the result of this SHL, and if it's a shift of a
7625     // constant amount, we can always perform a SHL in a smaller type.
7626     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7627       uint32_t BitWidth = Ty->getBitWidth();
7628       if (BitWidth < OrigTy->getBitWidth() && 
7629           CI->getLimitedValue(BitWidth) < BitWidth)
7630         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7631                                           NumCastsRemoved);
7632     }
7633     break;
7634   case Instruction::LShr:
7635     // If this is a truncate of a logical shr, we can truncate it to a smaller
7636     // lshr iff we know that the bits we would otherwise be shifting in are
7637     // already zeros.
7638     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7639       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7640       uint32_t BitWidth = Ty->getBitWidth();
7641       if (BitWidth < OrigBitWidth &&
7642           MaskedValueIsZero(I->getOperand(0),
7643             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7644           CI->getLimitedValue(BitWidth) < BitWidth) {
7645         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7646                                           NumCastsRemoved);
7647       }
7648     }
7649     break;
7650   case Instruction::ZExt:
7651   case Instruction::SExt:
7652   case Instruction::Trunc:
7653     // If this is the same kind of case as our original (e.g. zext+zext), we
7654     // can safely replace it.  Note that replacing it does not reduce the number
7655     // of casts in the input.
7656     if (Opc == CastOpc)
7657       return true;
7658
7659     // sext (zext ty1), ty2 -> zext ty2
7660     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7661       return true;
7662     break;
7663   case Instruction::Select: {
7664     SelectInst *SI = cast<SelectInst>(I);
7665     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7666                                       NumCastsRemoved) &&
7667            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7668                                       NumCastsRemoved);
7669   }
7670   case Instruction::PHI: {
7671     // We can change a phi if we can change all operands.
7672     PHINode *PN = cast<PHINode>(I);
7673     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7674       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7675                                       NumCastsRemoved))
7676         return false;
7677     return true;
7678   }
7679   default:
7680     // TODO: Can handle more cases here.
7681     break;
7682   }
7683   
7684   return false;
7685 }
7686
7687 /// EvaluateInDifferentType - Given an expression that 
7688 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7689 /// evaluate the expression.
7690 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7691                                              bool isSigned) {
7692   if (Constant *C = dyn_cast<Constant>(V))
7693     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7694
7695   // Otherwise, it must be an instruction.
7696   Instruction *I = cast<Instruction>(V);
7697   Instruction *Res = 0;
7698   unsigned Opc = I->getOpcode();
7699   switch (Opc) {
7700   case Instruction::Add:
7701   case Instruction::Sub:
7702   case Instruction::Mul:
7703   case Instruction::And:
7704   case Instruction::Or:
7705   case Instruction::Xor:
7706   case Instruction::AShr:
7707   case Instruction::LShr:
7708   case Instruction::Shl: {
7709     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7710     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7711     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7712     break;
7713   }    
7714   case Instruction::Trunc:
7715   case Instruction::ZExt:
7716   case Instruction::SExt:
7717     // If the source type of the cast is the type we're trying for then we can
7718     // just return the source.  There's no need to insert it because it is not
7719     // new.
7720     if (I->getOperand(0)->getType() == Ty)
7721       return I->getOperand(0);
7722     
7723     // Otherwise, must be the same type of cast, so just reinsert a new one.
7724     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7725                            Ty);
7726     break;
7727   case Instruction::Select: {
7728     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7729     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7730     Res = SelectInst::Create(I->getOperand(0), True, False);
7731     break;
7732   }
7733   case Instruction::PHI: {
7734     PHINode *OPN = cast<PHINode>(I);
7735     PHINode *NPN = PHINode::Create(Ty);
7736     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7737       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7738       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7739     }
7740     Res = NPN;
7741     break;
7742   }
7743   default: 
7744     // TODO: Can handle more cases here.
7745     assert(0 && "Unreachable!");
7746     break;
7747   }
7748   
7749   Res->takeName(I);
7750   return InsertNewInstBefore(Res, *I);
7751 }
7752
7753 /// @brief Implement the transforms common to all CastInst visitors.
7754 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7755   Value *Src = CI.getOperand(0);
7756
7757   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7758   // eliminate it now.
7759   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7760     if (Instruction::CastOps opc = 
7761         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7762       // The first cast (CSrc) is eliminable so we need to fix up or replace
7763       // the second cast (CI). CSrc will then have a good chance of being dead.
7764       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7765     }
7766   }
7767
7768   // If we are casting a select then fold the cast into the select
7769   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7770     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7771       return NV;
7772
7773   // If we are casting a PHI then fold the cast into the PHI
7774   if (isa<PHINode>(Src))
7775     if (Instruction *NV = FoldOpIntoPhi(CI))
7776       return NV;
7777   
7778   return 0;
7779 }
7780
7781 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7782 /// or not there is a sequence of GEP indices into the type that will land us at
7783 /// the specified offset.  If so, fill them into NewIndices and return the
7784 /// resultant element type, otherwise return null.
7785 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7786                                        SmallVectorImpl<Value*> &NewIndices,
7787                                        const TargetData *TD) {
7788   if (!Ty->isSized()) return 0;
7789   
7790   // Start with the index over the outer type.  Note that the type size
7791   // might be zero (even if the offset isn't zero) if the indexed type
7792   // is something like [0 x {int, int}]
7793   const Type *IntPtrTy = TD->getIntPtrType();
7794   int64_t FirstIdx = 0;
7795   if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
7796     FirstIdx = Offset/TySize;
7797     Offset -= FirstIdx*TySize;
7798     
7799     // Handle hosts where % returns negative instead of values [0..TySize).
7800     if (Offset < 0) {
7801       --FirstIdx;
7802       Offset += TySize;
7803       assert(Offset >= 0);
7804     }
7805     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7806   }
7807   
7808   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7809     
7810   // Index into the types.  If we fail, set OrigBase to null.
7811   while (Offset) {
7812     // Indexing into tail padding between struct/array elements.
7813     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
7814       return 0;
7815     
7816     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7817       const StructLayout *SL = TD->getStructLayout(STy);
7818       assert(Offset < (int64_t)SL->getSizeInBytes() &&
7819              "Offset must stay within the indexed type");
7820       
7821       unsigned Elt = SL->getElementContainingOffset(Offset);
7822       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7823       
7824       Offset -= SL->getElementOffset(Elt);
7825       Ty = STy->getElementType(Elt);
7826     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7827       uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
7828       assert(EltSize && "Cannot index into a zero-sized array");
7829       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7830       Offset %= EltSize;
7831       Ty = AT->getElementType();
7832     } else {
7833       // Otherwise, we can't index into the middle of this atomic type, bail.
7834       return 0;
7835     }
7836   }
7837   
7838   return Ty;
7839 }
7840
7841 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7842 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7843   Value *Src = CI.getOperand(0);
7844   
7845   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7846     // If casting the result of a getelementptr instruction with no offset, turn
7847     // this into a cast of the original pointer!
7848     if (GEP->hasAllZeroIndices()) {
7849       // Changing the cast operand is usually not a good idea but it is safe
7850       // here because the pointer operand is being replaced with another 
7851       // pointer operand so the opcode doesn't need to change.
7852       AddToWorkList(GEP);
7853       CI.setOperand(0, GEP->getOperand(0));
7854       return &CI;
7855     }
7856     
7857     // If the GEP has a single use, and the base pointer is a bitcast, and the
7858     // GEP computes a constant offset, see if we can convert these three
7859     // instructions into fewer.  This typically happens with unions and other
7860     // non-type-safe code.
7861     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7862       if (GEP->hasAllConstantIndices()) {
7863         // We are guaranteed to get a constant from EmitGEPOffset.
7864         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7865         int64_t Offset = OffsetV->getSExtValue();
7866         
7867         // Get the base pointer input of the bitcast, and the type it points to.
7868         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7869         const Type *GEPIdxTy =
7870           cast<PointerType>(OrigBase->getType())->getElementType();
7871         SmallVector<Value*, 8> NewIndices;
7872         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7873           // If we were able to index down into an element, create the GEP
7874           // and bitcast the result.  This eliminates one bitcast, potentially
7875           // two.
7876           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7877                                                         NewIndices.begin(),
7878                                                         NewIndices.end(), "");
7879           InsertNewInstBefore(NGEP, CI);
7880           NGEP->takeName(GEP);
7881           
7882           if (isa<BitCastInst>(CI))
7883             return new BitCastInst(NGEP, CI.getType());
7884           assert(isa<PtrToIntInst>(CI));
7885           return new PtrToIntInst(NGEP, CI.getType());
7886         }
7887       }      
7888     }
7889   }
7890     
7891   return commonCastTransforms(CI);
7892 }
7893
7894
7895 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7896 /// integer types. This function implements the common transforms for all those
7897 /// cases.
7898 /// @brief Implement the transforms common to CastInst with integer operands
7899 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7900   if (Instruction *Result = commonCastTransforms(CI))
7901     return Result;
7902
7903   Value *Src = CI.getOperand(0);
7904   const Type *SrcTy = Src->getType();
7905   const Type *DestTy = CI.getType();
7906   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7907   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7908
7909   // See if we can simplify any instructions used by the LHS whose sole 
7910   // purpose is to compute bits we don't care about.
7911   if (SimplifyDemandedInstructionBits(CI))
7912     return &CI;
7913
7914   // If the source isn't an instruction or has more than one use then we
7915   // can't do anything more. 
7916   Instruction *SrcI = dyn_cast<Instruction>(Src);
7917   if (!SrcI || !Src->hasOneUse())
7918     return 0;
7919
7920   // Attempt to propagate the cast into the instruction for int->int casts.
7921   int NumCastsRemoved = 0;
7922   if (!isa<BitCastInst>(CI) &&
7923       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7924                                  CI.getOpcode(), NumCastsRemoved)) {
7925     // If this cast is a truncate, evaluting in a different type always
7926     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7927     // we need to do an AND to maintain the clear top-part of the computation,
7928     // so we require that the input have eliminated at least one cast.  If this
7929     // is a sign extension, we insert two new casts (to do the extension) so we
7930     // require that two casts have been eliminated.
7931     bool DoXForm = false;
7932     bool JustReplace = false;
7933     switch (CI.getOpcode()) {
7934     default:
7935       // All the others use floating point so we shouldn't actually 
7936       // get here because of the check above.
7937       assert(0 && "Unknown cast type");
7938     case Instruction::Trunc:
7939       DoXForm = true;
7940       break;
7941     case Instruction::ZExt: {
7942       DoXForm = NumCastsRemoved >= 1;
7943       if (!DoXForm && 0) {
7944         // If it's unnecessary to issue an AND to clear the high bits, it's
7945         // always profitable to do this xform.
7946         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
7947         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7948         if (MaskedValueIsZero(TryRes, Mask))
7949           return ReplaceInstUsesWith(CI, TryRes);
7950         
7951         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7952           if (TryI->use_empty())
7953             EraseInstFromFunction(*TryI);
7954       }
7955       break;
7956     }
7957     case Instruction::SExt: {
7958       DoXForm = NumCastsRemoved >= 2;
7959       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
7960         // If we do not have to emit the truncate + sext pair, then it's always
7961         // profitable to do this xform.
7962         //
7963         // It's not safe to eliminate the trunc + sext pair if one of the
7964         // eliminated cast is a truncate. e.g.
7965         // t2 = trunc i32 t1 to i16
7966         // t3 = sext i16 t2 to i32
7967         // !=
7968         // i32 t1
7969         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
7970         unsigned NumSignBits = ComputeNumSignBits(TryRes);
7971         if (NumSignBits > (DestBitSize - SrcBitSize))
7972           return ReplaceInstUsesWith(CI, TryRes);
7973         
7974         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7975           if (TryI->use_empty())
7976             EraseInstFromFunction(*TryI);
7977       }
7978       break;
7979     }
7980     }
7981     
7982     if (DoXForm) {
7983       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
7984            << " cast: " << CI;
7985       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7986                                            CI.getOpcode() == Instruction::SExt);
7987       if (JustReplace)
7988         // Just replace this cast with the result.
7989         return ReplaceInstUsesWith(CI, Res);
7990
7991       assert(Res->getType() == DestTy);
7992       switch (CI.getOpcode()) {
7993       default: assert(0 && "Unknown cast type!");
7994       case Instruction::Trunc:
7995       case Instruction::BitCast:
7996         // Just replace this cast with the result.
7997         return ReplaceInstUsesWith(CI, Res);
7998       case Instruction::ZExt: {
7999         assert(SrcBitSize < DestBitSize && "Not a zext?");
8000
8001         // If the high bits are already zero, just replace this cast with the
8002         // result.
8003         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8004         if (MaskedValueIsZero(Res, Mask))
8005           return ReplaceInstUsesWith(CI, Res);
8006
8007         // We need to emit an AND to clear the high bits.
8008         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8009                                                             SrcBitSize));
8010         return BinaryOperator::CreateAnd(Res, C);
8011       }
8012       case Instruction::SExt: {
8013         // If the high bits are already filled with sign bit, just replace this
8014         // cast with the result.
8015         unsigned NumSignBits = ComputeNumSignBits(Res);
8016         if (NumSignBits > (DestBitSize - SrcBitSize))
8017           return ReplaceInstUsesWith(CI, Res);
8018
8019         // We need to emit a cast to truncate, then a cast to sext.
8020         return CastInst::Create(Instruction::SExt,
8021             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8022                              CI), DestTy);
8023       }
8024       }
8025     }
8026   }
8027   
8028   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8029   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8030
8031   switch (SrcI->getOpcode()) {
8032   case Instruction::Add:
8033   case Instruction::Mul:
8034   case Instruction::And:
8035   case Instruction::Or:
8036   case Instruction::Xor:
8037     // If we are discarding information, rewrite.
8038     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8039       // Don't insert two casts if they cannot be eliminated.  We allow 
8040       // two casts to be inserted if the sizes are the same.  This could 
8041       // only be converting signedness, which is a noop.
8042       if (DestBitSize == SrcBitSize || 
8043           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8044           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8045         Instruction::CastOps opcode = CI.getOpcode();
8046         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8047         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8048         return BinaryOperator::Create(
8049             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8050       }
8051     }
8052
8053     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8054     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8055         SrcI->getOpcode() == Instruction::Xor &&
8056         Op1 == ConstantInt::getTrue() &&
8057         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8058       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8059       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8060     }
8061     break;
8062   case Instruction::SDiv:
8063   case Instruction::UDiv:
8064   case Instruction::SRem:
8065   case Instruction::URem:
8066     // If we are just changing the sign, rewrite.
8067     if (DestBitSize == SrcBitSize) {
8068       // Don't insert two casts if they cannot be eliminated.  We allow 
8069       // two casts to be inserted if the sizes are the same.  This could 
8070       // only be converting signedness, which is a noop.
8071       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8072           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8073         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8074                                        Op0, DestTy, *SrcI);
8075         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8076                                        Op1, DestTy, *SrcI);
8077         return BinaryOperator::Create(
8078           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8079       }
8080     }
8081     break;
8082
8083   case Instruction::Shl:
8084     // Allow changing the sign of the source operand.  Do not allow 
8085     // changing the size of the shift, UNLESS the shift amount is a 
8086     // constant.  We must not change variable sized shifts to a smaller 
8087     // size, because it is undefined to shift more bits out than exist 
8088     // in the value.
8089     if (DestBitSize == SrcBitSize ||
8090         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8091       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8092           Instruction::BitCast : Instruction::Trunc);
8093       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8094       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8095       return BinaryOperator::CreateShl(Op0c, Op1c);
8096     }
8097     break;
8098   case Instruction::AShr:
8099     // If this is a signed shr, and if all bits shifted in are about to be
8100     // truncated off, turn it into an unsigned shr to allow greater
8101     // simplifications.
8102     if (DestBitSize < SrcBitSize &&
8103         isa<ConstantInt>(Op1)) {
8104       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8105       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8106         // Insert the new logical shift right.
8107         return BinaryOperator::CreateLShr(Op0, Op1);
8108       }
8109     }
8110     break;
8111   }
8112   return 0;
8113 }
8114
8115 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8116   if (Instruction *Result = commonIntCastTransforms(CI))
8117     return Result;
8118   
8119   Value *Src = CI.getOperand(0);
8120   const Type *Ty = CI.getType();
8121   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8122   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8123   
8124   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8125     switch (SrcI->getOpcode()) {
8126     default: break;
8127     case Instruction::LShr:
8128       // We can shrink lshr to something smaller if we know the bits shifted in
8129       // are already zeros.
8130       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
8131         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8132         
8133         // Get a mask for the bits shifting in.
8134         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8135         Value* SrcIOp0 = SrcI->getOperand(0);
8136         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
8137           if (ShAmt >= DestBitWidth)        // All zeros.
8138             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8139
8140           // Okay, we can shrink this.  Truncate the input, then return a new
8141           // shift.
8142           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8143           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8144                                        Ty, CI);
8145           return BinaryOperator::CreateLShr(V1, V2);
8146         }
8147       } else {     // This is a variable shr.
8148         
8149         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
8150         // more LLVM instructions, but allows '1 << Y' to be hoisted if
8151         // loop-invariant and CSE'd.
8152         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
8153           Value *One = ConstantInt::get(SrcI->getType(), 1);
8154
8155           Value *V = InsertNewInstBefore(
8156               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
8157                                      "tmp"), CI);
8158           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
8159                                                             SrcI->getOperand(0),
8160                                                             "tmp"), CI);
8161           Value *Zero = Constant::getNullValue(V->getType());
8162           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
8163         }
8164       }
8165       break;
8166     }
8167   }
8168   
8169   return 0;
8170 }
8171
8172 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8173 /// in order to eliminate the icmp.
8174 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8175                                              bool DoXform) {
8176   // If we are just checking for a icmp eq of a single bit and zext'ing it
8177   // to an integer, then shift the bit to the appropriate place and then
8178   // cast to integer to avoid the comparison.
8179   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8180     const APInt &Op1CV = Op1C->getValue();
8181       
8182     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8183     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8184     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8185         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8186       if (!DoXform) return ICI;
8187
8188       Value *In = ICI->getOperand(0);
8189       Value *Sh = ConstantInt::get(In->getType(),
8190                                    In->getType()->getPrimitiveSizeInBits()-1);
8191       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8192                                                         In->getName()+".lobit"),
8193                                CI);
8194       if (In->getType() != CI.getType())
8195         In = CastInst::CreateIntegerCast(In, CI.getType(),
8196                                          false/*ZExt*/, "tmp", &CI);
8197
8198       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8199         Constant *One = ConstantInt::get(In->getType(), 1);
8200         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8201                                                          In->getName()+".not"),
8202                                  CI);
8203       }
8204
8205       return ReplaceInstUsesWith(CI, In);
8206     }
8207       
8208       
8209       
8210     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8211     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8212     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8213     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8214     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8215     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8216     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8217     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8218     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8219         // This only works for EQ and NE
8220         ICI->isEquality()) {
8221       // If Op1C some other power of two, convert:
8222       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8223       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8224       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8225       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8226         
8227       APInt KnownZeroMask(~KnownZero);
8228       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8229         if (!DoXform) return ICI;
8230
8231         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8232         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8233           // (X&4) == 2 --> false
8234           // (X&4) != 2 --> true
8235           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8236           Res = ConstantExpr::getZExt(Res, CI.getType());
8237           return ReplaceInstUsesWith(CI, Res);
8238         }
8239           
8240         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8241         Value *In = ICI->getOperand(0);
8242         if (ShiftAmt) {
8243           // Perform a logical shr by shiftamt.
8244           // Insert the shift to put the result in the low bit.
8245           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8246                                   ConstantInt::get(In->getType(), ShiftAmt),
8247                                                    In->getName()+".lobit"), CI);
8248         }
8249           
8250         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8251           Constant *One = ConstantInt::get(In->getType(), 1);
8252           In = BinaryOperator::CreateXor(In, One, "tmp");
8253           InsertNewInstBefore(cast<Instruction>(In), CI);
8254         }
8255           
8256         if (CI.getType() == In->getType())
8257           return ReplaceInstUsesWith(CI, In);
8258         else
8259           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8260       }
8261     }
8262   }
8263
8264   return 0;
8265 }
8266
8267 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8268   // If one of the common conversion will work ..
8269   if (Instruction *Result = commonIntCastTransforms(CI))
8270     return Result;
8271
8272   Value *Src = CI.getOperand(0);
8273
8274   // If this is a cast of a cast
8275   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8276     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8277     // types and if the sizes are just right we can convert this into a logical
8278     // 'and' which will be much cheaper than the pair of casts.
8279     if (isa<TruncInst>(CSrc)) {
8280       // Get the sizes of the types involved
8281       Value *A = CSrc->getOperand(0);
8282       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8283       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8284       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8285       // If we're actually extending zero bits and the trunc is a no-op
8286       if (MidSize < DstSize && SrcSize == DstSize) {
8287         // Replace both of the casts with an And of the type mask.
8288         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8289         Constant *AndConst = ConstantInt::get(AndValue);
8290         Instruction *And = 
8291           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8292         // Unfortunately, if the type changed, we need to cast it back.
8293         if (And->getType() != CI.getType()) {
8294           And->setName(CSrc->getName()+".mask");
8295           InsertNewInstBefore(And, CI);
8296           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8297         }
8298         return And;
8299       }
8300     }
8301   }
8302
8303   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8304     return transformZExtICmp(ICI, CI);
8305
8306   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8307   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8308     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8309     // of the (zext icmp) will be transformed.
8310     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8311     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8312     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8313         (transformZExtICmp(LHS, CI, false) ||
8314          transformZExtICmp(RHS, CI, false))) {
8315       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8316       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8317       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8318     }
8319   }
8320
8321   return 0;
8322 }
8323
8324 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8325   if (Instruction *I = commonIntCastTransforms(CI))
8326     return I;
8327   
8328   Value *Src = CI.getOperand(0);
8329   
8330   // Canonicalize sign-extend from i1 to a select.
8331   if (Src->getType() == Type::Int1Ty)
8332     return SelectInst::Create(Src,
8333                               ConstantInt::getAllOnesValue(CI.getType()),
8334                               Constant::getNullValue(CI.getType()));
8335
8336   // See if the value being truncated is already sign extended.  If so, just
8337   // eliminate the trunc/sext pair.
8338   if (getOpcode(Src) == Instruction::Trunc) {
8339     Value *Op = cast<User>(Src)->getOperand(0);
8340     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8341     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8342     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8343     unsigned NumSignBits = ComputeNumSignBits(Op);
8344
8345     if (OpBits == DestBits) {
8346       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8347       // bits, it is already ready.
8348       if (NumSignBits > DestBits-MidBits)
8349         return ReplaceInstUsesWith(CI, Op);
8350     } else if (OpBits < DestBits) {
8351       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8352       // bits, just sext from i32.
8353       if (NumSignBits > OpBits-MidBits)
8354         return new SExtInst(Op, CI.getType(), "tmp");
8355     } else {
8356       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8357       // bits, just truncate to i32.
8358       if (NumSignBits > OpBits-MidBits)
8359         return new TruncInst(Op, CI.getType(), "tmp");
8360     }
8361   }
8362
8363   // If the input is a shl/ashr pair of a same constant, then this is a sign
8364   // extension from a smaller value.  If we could trust arbitrary bitwidth
8365   // integers, we could turn this into a truncate to the smaller bit and then
8366   // use a sext for the whole extension.  Since we don't, look deeper and check
8367   // for a truncate.  If the source and dest are the same type, eliminate the
8368   // trunc and extend and just do shifts.  For example, turn:
8369   //   %a = trunc i32 %i to i8
8370   //   %b = shl i8 %a, 6
8371   //   %c = ashr i8 %b, 6
8372   //   %d = sext i8 %c to i32
8373   // into:
8374   //   %a = shl i32 %i, 30
8375   //   %d = ashr i32 %a, 30
8376   Value *A = 0;
8377   ConstantInt *BA = 0, *CA = 0;
8378   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8379                         m_ConstantInt(CA))) &&
8380       BA == CA && isa<TruncInst>(A)) {
8381     Value *I = cast<TruncInst>(A)->getOperand(0);
8382     if (I->getType() == CI.getType()) {
8383       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8384       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8385       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8386       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8387       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8388                                                         CI.getName()), CI);
8389       return BinaryOperator::CreateAShr(I, ShAmtV);
8390     }
8391   }
8392   
8393   return 0;
8394 }
8395
8396 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8397 /// in the specified FP type without changing its value.
8398 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8399   bool losesInfo;
8400   APFloat F = CFP->getValueAPF();
8401   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8402   if (!losesInfo)
8403     return ConstantFP::get(F);
8404   return 0;
8405 }
8406
8407 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8408 /// through it until we get the source value.
8409 static Value *LookThroughFPExtensions(Value *V) {
8410   if (Instruction *I = dyn_cast<Instruction>(V))
8411     if (I->getOpcode() == Instruction::FPExt)
8412       return LookThroughFPExtensions(I->getOperand(0));
8413   
8414   // If this value is a constant, return the constant in the smallest FP type
8415   // that can accurately represent it.  This allows us to turn
8416   // (float)((double)X+2.0) into x+2.0f.
8417   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8418     if (CFP->getType() == Type::PPC_FP128Ty)
8419       return V;  // No constant folding of this.
8420     // See if the value can be truncated to float and then reextended.
8421     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8422       return V;
8423     if (CFP->getType() == Type::DoubleTy)
8424       return V;  // Won't shrink.
8425     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8426       return V;
8427     // Don't try to shrink to various long double types.
8428   }
8429   
8430   return V;
8431 }
8432
8433 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8434   if (Instruction *I = commonCastTransforms(CI))
8435     return I;
8436   
8437   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8438   // smaller than the destination type, we can eliminate the truncate by doing
8439   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8440   // many builtins (sqrt, etc).
8441   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8442   if (OpI && OpI->hasOneUse()) {
8443     switch (OpI->getOpcode()) {
8444     default: break;
8445     case Instruction::Add:
8446     case Instruction::Sub:
8447     case Instruction::Mul:
8448     case Instruction::FDiv:
8449     case Instruction::FRem:
8450       const Type *SrcTy = OpI->getType();
8451       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8452       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8453       if (LHSTrunc->getType() != SrcTy && 
8454           RHSTrunc->getType() != SrcTy) {
8455         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8456         // If the source types were both smaller than the destination type of
8457         // the cast, do this xform.
8458         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8459             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8460           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8461                                       CI.getType(), CI);
8462           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8463                                       CI.getType(), CI);
8464           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8465         }
8466       }
8467       break;  
8468     }
8469   }
8470   return 0;
8471 }
8472
8473 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8474   return commonCastTransforms(CI);
8475 }
8476
8477 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8478   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8479   if (OpI == 0)
8480     return commonCastTransforms(FI);
8481
8482   // fptoui(uitofp(X)) --> X
8483   // fptoui(sitofp(X)) --> X
8484   // This is safe if the intermediate type has enough bits in its mantissa to
8485   // accurately represent all values of X.  For example, do not do this with
8486   // i64->float->i64.  This is also safe for sitofp case, because any negative
8487   // 'X' value would cause an undefined result for the fptoui. 
8488   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8489       OpI->getOperand(0)->getType() == FI.getType() &&
8490       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8491                     OpI->getType()->getFPMantissaWidth())
8492     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8493
8494   return commonCastTransforms(FI);
8495 }
8496
8497 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8498   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8499   if (OpI == 0)
8500     return commonCastTransforms(FI);
8501   
8502   // fptosi(sitofp(X)) --> X
8503   // fptosi(uitofp(X)) --> X
8504   // This is safe if the intermediate type has enough bits in its mantissa to
8505   // accurately represent all values of X.  For example, do not do this with
8506   // i64->float->i64.  This is also safe for sitofp case, because any negative
8507   // 'X' value would cause an undefined result for the fptoui. 
8508   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8509       OpI->getOperand(0)->getType() == FI.getType() &&
8510       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8511                     OpI->getType()->getFPMantissaWidth())
8512     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8513   
8514   return commonCastTransforms(FI);
8515 }
8516
8517 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8518   return commonCastTransforms(CI);
8519 }
8520
8521 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8522   return commonCastTransforms(CI);
8523 }
8524
8525 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8526   return commonPointerCastTransforms(CI);
8527 }
8528
8529 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8530   if (Instruction *I = commonCastTransforms(CI))
8531     return I;
8532   
8533   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8534   if (!DestPointee->isSized()) return 0;
8535
8536   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8537   ConstantInt *Cst;
8538   Value *X;
8539   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8540                                     m_ConstantInt(Cst)))) {
8541     // If the source and destination operands have the same type, see if this
8542     // is a single-index GEP.
8543     if (X->getType() == CI.getType()) {
8544       // Get the size of the pointee type.
8545       uint64_t Size = TD->getTypePaddedSize(DestPointee);
8546
8547       // Convert the constant to intptr type.
8548       APInt Offset = Cst->getValue();
8549       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8550
8551       // If Offset is evenly divisible by Size, we can do this xform.
8552       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8553         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8554         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8555       }
8556     }
8557     // TODO: Could handle other cases, e.g. where add is indexing into field of
8558     // struct etc.
8559   } else if (CI.getOperand(0)->hasOneUse() &&
8560              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8561     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8562     // "inttoptr+GEP" instead of "add+intptr".
8563     
8564     // Get the size of the pointee type.
8565     uint64_t Size = TD->getTypePaddedSize(DestPointee);
8566     
8567     // Convert the constant to intptr type.
8568     APInt Offset = Cst->getValue();
8569     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8570     
8571     // If Offset is evenly divisible by Size, we can do this xform.
8572     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8573       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8574       
8575       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8576                                                             "tmp"), CI);
8577       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8578     }
8579   }
8580   return 0;
8581 }
8582
8583 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8584   // If the operands are integer typed then apply the integer transforms,
8585   // otherwise just apply the common ones.
8586   Value *Src = CI.getOperand(0);
8587   const Type *SrcTy = Src->getType();
8588   const Type *DestTy = CI.getType();
8589
8590   if (SrcTy->isInteger() && DestTy->isInteger()) {
8591     if (Instruction *Result = commonIntCastTransforms(CI))
8592       return Result;
8593   } else if (isa<PointerType>(SrcTy)) {
8594     if (Instruction *I = commonPointerCastTransforms(CI))
8595       return I;
8596   } else {
8597     if (Instruction *Result = commonCastTransforms(CI))
8598       return Result;
8599   }
8600
8601
8602   // Get rid of casts from one type to the same type. These are useless and can
8603   // be replaced by the operand.
8604   if (DestTy == Src->getType())
8605     return ReplaceInstUsesWith(CI, Src);
8606
8607   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8608     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8609     const Type *DstElTy = DstPTy->getElementType();
8610     const Type *SrcElTy = SrcPTy->getElementType();
8611     
8612     // If the address spaces don't match, don't eliminate the bitcast, which is
8613     // required for changing types.
8614     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8615       return 0;
8616     
8617     // If we are casting a malloc or alloca to a pointer to a type of the same
8618     // size, rewrite the allocation instruction to allocate the "right" type.
8619     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8620       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8621         return V;
8622     
8623     // If the source and destination are pointers, and this cast is equivalent
8624     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8625     // This can enhance SROA and other transforms that want type-safe pointers.
8626     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8627     unsigned NumZeros = 0;
8628     while (SrcElTy != DstElTy && 
8629            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8630            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8631       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8632       ++NumZeros;
8633     }
8634
8635     // If we found a path from the src to dest, create the getelementptr now.
8636     if (SrcElTy == DstElTy) {
8637       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8638       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8639                                        ((Instruction*) NULL));
8640     }
8641   }
8642
8643   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8644     if (SVI->hasOneUse()) {
8645       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8646       // a bitconvert to a vector with the same # elts.
8647       if (isa<VectorType>(DestTy) && 
8648           cast<VectorType>(DestTy)->getNumElements() ==
8649                 SVI->getType()->getNumElements() &&
8650           SVI->getType()->getNumElements() ==
8651             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8652         CastInst *Tmp;
8653         // If either of the operands is a cast from CI.getType(), then
8654         // evaluating the shuffle in the casted destination's type will allow
8655         // us to eliminate at least one cast.
8656         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8657              Tmp->getOperand(0)->getType() == DestTy) ||
8658             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8659              Tmp->getOperand(0)->getType() == DestTy)) {
8660           Value *LHS = InsertCastBefore(Instruction::BitCast,
8661                                         SVI->getOperand(0), DestTy, CI);
8662           Value *RHS = InsertCastBefore(Instruction::BitCast,
8663                                         SVI->getOperand(1), DestTy, CI);
8664           // Return a new shuffle vector.  Use the same element ID's, as we
8665           // know the vector types match #elts.
8666           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8667         }
8668       }
8669     }
8670   }
8671   return 0;
8672 }
8673
8674 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8675 ///   %C = or %A, %B
8676 ///   %D = select %cond, %C, %A
8677 /// into:
8678 ///   %C = select %cond, %B, 0
8679 ///   %D = or %A, %C
8680 ///
8681 /// Assuming that the specified instruction is an operand to the select, return
8682 /// a bitmask indicating which operands of this instruction are foldable if they
8683 /// equal the other incoming value of the select.
8684 ///
8685 static unsigned GetSelectFoldableOperands(Instruction *I) {
8686   switch (I->getOpcode()) {
8687   case Instruction::Add:
8688   case Instruction::Mul:
8689   case Instruction::And:
8690   case Instruction::Or:
8691   case Instruction::Xor:
8692     return 3;              // Can fold through either operand.
8693   case Instruction::Sub:   // Can only fold on the amount subtracted.
8694   case Instruction::Shl:   // Can only fold on the shift amount.
8695   case Instruction::LShr:
8696   case Instruction::AShr:
8697     return 1;
8698   default:
8699     return 0;              // Cannot fold
8700   }
8701 }
8702
8703 /// GetSelectFoldableConstant - For the same transformation as the previous
8704 /// function, return the identity constant that goes into the select.
8705 static Constant *GetSelectFoldableConstant(Instruction *I) {
8706   switch (I->getOpcode()) {
8707   default: assert(0 && "This cannot happen!"); abort();
8708   case Instruction::Add:
8709   case Instruction::Sub:
8710   case Instruction::Or:
8711   case Instruction::Xor:
8712   case Instruction::Shl:
8713   case Instruction::LShr:
8714   case Instruction::AShr:
8715     return Constant::getNullValue(I->getType());
8716   case Instruction::And:
8717     return Constant::getAllOnesValue(I->getType());
8718   case Instruction::Mul:
8719     return ConstantInt::get(I->getType(), 1);
8720   }
8721 }
8722
8723 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8724 /// have the same opcode and only one use each.  Try to simplify this.
8725 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8726                                           Instruction *FI) {
8727   if (TI->getNumOperands() == 1) {
8728     // If this is a non-volatile load or a cast from the same type,
8729     // merge.
8730     if (TI->isCast()) {
8731       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8732         return 0;
8733     } else {
8734       return 0;  // unknown unary op.
8735     }
8736
8737     // Fold this by inserting a select from the input values.
8738     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8739                                            FI->getOperand(0), SI.getName()+".v");
8740     InsertNewInstBefore(NewSI, SI);
8741     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8742                             TI->getType());
8743   }
8744
8745   // Only handle binary operators here.
8746   if (!isa<BinaryOperator>(TI))
8747     return 0;
8748
8749   // Figure out if the operations have any operands in common.
8750   Value *MatchOp, *OtherOpT, *OtherOpF;
8751   bool MatchIsOpZero;
8752   if (TI->getOperand(0) == FI->getOperand(0)) {
8753     MatchOp  = TI->getOperand(0);
8754     OtherOpT = TI->getOperand(1);
8755     OtherOpF = FI->getOperand(1);
8756     MatchIsOpZero = true;
8757   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8758     MatchOp  = TI->getOperand(1);
8759     OtherOpT = TI->getOperand(0);
8760     OtherOpF = FI->getOperand(0);
8761     MatchIsOpZero = false;
8762   } else if (!TI->isCommutative()) {
8763     return 0;
8764   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8765     MatchOp  = TI->getOperand(0);
8766     OtherOpT = TI->getOperand(1);
8767     OtherOpF = FI->getOperand(0);
8768     MatchIsOpZero = true;
8769   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8770     MatchOp  = TI->getOperand(1);
8771     OtherOpT = TI->getOperand(0);
8772     OtherOpF = FI->getOperand(1);
8773     MatchIsOpZero = true;
8774   } else {
8775     return 0;
8776   }
8777
8778   // If we reach here, they do have operations in common.
8779   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8780                                          OtherOpF, SI.getName()+".v");
8781   InsertNewInstBefore(NewSI, SI);
8782
8783   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8784     if (MatchIsOpZero)
8785       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8786     else
8787       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8788   }
8789   assert(0 && "Shouldn't get here");
8790   return 0;
8791 }
8792
8793 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8794 /// ICmpInst as its first operand.
8795 ///
8796 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8797                                                    ICmpInst *ICI) {
8798   bool Changed = false;
8799   ICmpInst::Predicate Pred = ICI->getPredicate();
8800   Value *CmpLHS = ICI->getOperand(0);
8801   Value *CmpRHS = ICI->getOperand(1);
8802   Value *TrueVal = SI.getTrueValue();
8803   Value *FalseVal = SI.getFalseValue();
8804
8805   // Check cases where the comparison is with a constant that
8806   // can be adjusted to fit the min/max idiom. We may edit ICI in
8807   // place here, so make sure the select is the only user.
8808   if (ICI->hasOneUse())
8809     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8810       switch (Pred) {
8811       default: break;
8812       case ICmpInst::ICMP_ULT:
8813       case ICmpInst::ICMP_SLT: {
8814         // X < MIN ? T : F  -->  F
8815         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8816           return ReplaceInstUsesWith(SI, FalseVal);
8817         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8818         Constant *AdjustedRHS = SubOne(CI);
8819         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8820             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8821           Pred = ICmpInst::getSwappedPredicate(Pred);
8822           CmpRHS = AdjustedRHS;
8823           std::swap(FalseVal, TrueVal);
8824           ICI->setPredicate(Pred);
8825           ICI->setOperand(1, CmpRHS);
8826           SI.setOperand(1, TrueVal);
8827           SI.setOperand(2, FalseVal);
8828           Changed = true;
8829         }
8830         break;
8831       }
8832       case ICmpInst::ICMP_UGT:
8833       case ICmpInst::ICMP_SGT: {
8834         // X > MAX ? T : F  -->  F
8835         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8836           return ReplaceInstUsesWith(SI, FalseVal);
8837         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8838         Constant *AdjustedRHS = AddOne(CI);
8839         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8840             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8841           Pred = ICmpInst::getSwappedPredicate(Pred);
8842           CmpRHS = AdjustedRHS;
8843           std::swap(FalseVal, TrueVal);
8844           ICI->setPredicate(Pred);
8845           ICI->setOperand(1, CmpRHS);
8846           SI.setOperand(1, TrueVal);
8847           SI.setOperand(2, FalseVal);
8848           Changed = true;
8849         }
8850         break;
8851       }
8852       }
8853
8854       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8855       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8856       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8857       if (match(TrueVal, m_ConstantInt<-1>()) &&
8858           match(FalseVal, m_ConstantInt<0>()))
8859         Pred = ICI->getPredicate();
8860       else if (match(TrueVal, m_ConstantInt<0>()) &&
8861                match(FalseVal, m_ConstantInt<-1>()))
8862         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8863       
8864       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8865         // If we are just checking for a icmp eq of a single bit and zext'ing it
8866         // to an integer, then shift the bit to the appropriate place and then
8867         // cast to integer to avoid the comparison.
8868         const APInt &Op1CV = CI->getValue();
8869     
8870         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8871         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8872         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8873             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8874           Value *In = ICI->getOperand(0);
8875           Value *Sh = ConstantInt::get(In->getType(),
8876                                        In->getType()->getPrimitiveSizeInBits()-1);
8877           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8878                                                           In->getName()+".lobit"),
8879                                    *ICI);
8880           if (In->getType() != SI.getType())
8881             In = CastInst::CreateIntegerCast(In, SI.getType(),
8882                                              true/*SExt*/, "tmp", ICI);
8883     
8884           if (Pred == ICmpInst::ICMP_SGT)
8885             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8886                                        In->getName()+".not"), *ICI);
8887     
8888           return ReplaceInstUsesWith(SI, In);
8889         }
8890       }
8891     }
8892
8893   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8894     // Transform (X == Y) ? X : Y  -> Y
8895     if (Pred == ICmpInst::ICMP_EQ)
8896       return ReplaceInstUsesWith(SI, FalseVal);
8897     // Transform (X != Y) ? X : Y  -> X
8898     if (Pred == ICmpInst::ICMP_NE)
8899       return ReplaceInstUsesWith(SI, TrueVal);
8900     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8901
8902   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8903     // Transform (X == Y) ? Y : X  -> X
8904     if (Pred == ICmpInst::ICMP_EQ)
8905       return ReplaceInstUsesWith(SI, FalseVal);
8906     // Transform (X != Y) ? Y : X  -> Y
8907     if (Pred == ICmpInst::ICMP_NE)
8908       return ReplaceInstUsesWith(SI, TrueVal);
8909     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8910   }
8911
8912   /// NOTE: if we wanted to, this is where to detect integer ABS
8913
8914   return Changed ? &SI : 0;
8915 }
8916
8917 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8918   Value *CondVal = SI.getCondition();
8919   Value *TrueVal = SI.getTrueValue();
8920   Value *FalseVal = SI.getFalseValue();
8921
8922   // select true, X, Y  -> X
8923   // select false, X, Y -> Y
8924   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8925     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8926
8927   // select C, X, X -> X
8928   if (TrueVal == FalseVal)
8929     return ReplaceInstUsesWith(SI, TrueVal);
8930
8931   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8932     return ReplaceInstUsesWith(SI, FalseVal);
8933   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8934     return ReplaceInstUsesWith(SI, TrueVal);
8935   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8936     if (isa<Constant>(TrueVal))
8937       return ReplaceInstUsesWith(SI, TrueVal);
8938     else
8939       return ReplaceInstUsesWith(SI, FalseVal);
8940   }
8941
8942   if (SI.getType() == Type::Int1Ty) {
8943     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8944       if (C->getZExtValue()) {
8945         // Change: A = select B, true, C --> A = or B, C
8946         return BinaryOperator::CreateOr(CondVal, FalseVal);
8947       } else {
8948         // Change: A = select B, false, C --> A = and !B, C
8949         Value *NotCond =
8950           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8951                                              "not."+CondVal->getName()), SI);
8952         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8953       }
8954     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8955       if (C->getZExtValue() == false) {
8956         // Change: A = select B, C, false --> A = and B, C
8957         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8958       } else {
8959         // Change: A = select B, C, true --> A = or !B, C
8960         Value *NotCond =
8961           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8962                                              "not."+CondVal->getName()), SI);
8963         return BinaryOperator::CreateOr(NotCond, TrueVal);
8964       }
8965     }
8966     
8967     // select a, b, a  -> a&b
8968     // select a, a, b  -> a|b
8969     if (CondVal == TrueVal)
8970       return BinaryOperator::CreateOr(CondVal, FalseVal);
8971     else if (CondVal == FalseVal)
8972       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8973   }
8974
8975   // Selecting between two integer constants?
8976   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8977     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8978       // select C, 1, 0 -> zext C to int
8979       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8980         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8981       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8982         // select C, 0, 1 -> zext !C to int
8983         Value *NotCond =
8984           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8985                                                "not."+CondVal->getName()), SI);
8986         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8987       }
8988
8989       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8990
8991         // (x <s 0) ? -1 : 0 -> ashr x, 31
8992         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8993           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8994             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8995               // The comparison constant and the result are not neccessarily the
8996               // same width. Make an all-ones value by inserting a AShr.
8997               Value *X = IC->getOperand(0);
8998               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8999               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
9000               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9001                                                         ShAmt, "ones");
9002               InsertNewInstBefore(SRA, SI);
9003
9004               // Then cast to the appropriate width.
9005               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9006             }
9007           }
9008
9009
9010         // If one of the constants is zero (we know they can't both be) and we
9011         // have an icmp instruction with zero, and we have an 'and' with the
9012         // non-constant value, eliminate this whole mess.  This corresponds to
9013         // cases like this: ((X & 27) ? 27 : 0)
9014         if (TrueValC->isZero() || FalseValC->isZero())
9015           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9016               cast<Constant>(IC->getOperand(1))->isNullValue())
9017             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9018               if (ICA->getOpcode() == Instruction::And &&
9019                   isa<ConstantInt>(ICA->getOperand(1)) &&
9020                   (ICA->getOperand(1) == TrueValC ||
9021                    ICA->getOperand(1) == FalseValC) &&
9022                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9023                 // Okay, now we know that everything is set up, we just don't
9024                 // know whether we have a icmp_ne or icmp_eq and whether the 
9025                 // true or false val is the zero.
9026                 bool ShouldNotVal = !TrueValC->isZero();
9027                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9028                 Value *V = ICA;
9029                 if (ShouldNotVal)
9030                   V = InsertNewInstBefore(BinaryOperator::Create(
9031                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9032                 return ReplaceInstUsesWith(SI, V);
9033               }
9034       }
9035     }
9036
9037   // See if we are selecting two values based on a comparison of the two values.
9038   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9039     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9040       // Transform (X == Y) ? X : Y  -> Y
9041       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9042         // This is not safe in general for floating point:  
9043         // consider X== -0, Y== +0.
9044         // It becomes safe if either operand is a nonzero constant.
9045         ConstantFP *CFPt, *CFPf;
9046         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9047               !CFPt->getValueAPF().isZero()) ||
9048             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9049              !CFPf->getValueAPF().isZero()))
9050         return ReplaceInstUsesWith(SI, FalseVal);
9051       }
9052       // Transform (X != Y) ? X : Y  -> X
9053       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9054         return ReplaceInstUsesWith(SI, TrueVal);
9055       // NOTE: if we wanted to, this is where to detect MIN/MAX
9056
9057     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9058       // Transform (X == Y) ? Y : X  -> X
9059       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9060         // This is not safe in general for floating point:  
9061         // consider X== -0, Y== +0.
9062         // It becomes safe if either operand is a nonzero constant.
9063         ConstantFP *CFPt, *CFPf;
9064         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9065               !CFPt->getValueAPF().isZero()) ||
9066             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9067              !CFPf->getValueAPF().isZero()))
9068           return ReplaceInstUsesWith(SI, FalseVal);
9069       }
9070       // Transform (X != Y) ? Y : X  -> Y
9071       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9072         return ReplaceInstUsesWith(SI, TrueVal);
9073       // NOTE: if we wanted to, this is where to detect MIN/MAX
9074     }
9075     // NOTE: if we wanted to, this is where to detect ABS
9076   }
9077
9078   // See if we are selecting two values based on a comparison of the two values.
9079   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9080     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9081       return Result;
9082
9083   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9084     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9085       if (TI->hasOneUse() && FI->hasOneUse()) {
9086         Instruction *AddOp = 0, *SubOp = 0;
9087
9088         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9089         if (TI->getOpcode() == FI->getOpcode())
9090           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9091             return IV;
9092
9093         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9094         // even legal for FP.
9095         if (TI->getOpcode() == Instruction::Sub &&
9096             FI->getOpcode() == Instruction::Add) {
9097           AddOp = FI; SubOp = TI;
9098         } else if (FI->getOpcode() == Instruction::Sub &&
9099                    TI->getOpcode() == Instruction::Add) {
9100           AddOp = TI; SubOp = FI;
9101         }
9102
9103         if (AddOp) {
9104           Value *OtherAddOp = 0;
9105           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9106             OtherAddOp = AddOp->getOperand(1);
9107           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9108             OtherAddOp = AddOp->getOperand(0);
9109           }
9110
9111           if (OtherAddOp) {
9112             // So at this point we know we have (Y -> OtherAddOp):
9113             //        select C, (add X, Y), (sub X, Z)
9114             Value *NegVal;  // Compute -Z
9115             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9116               NegVal = ConstantExpr::getNeg(C);
9117             } else {
9118               NegVal = InsertNewInstBefore(
9119                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9120             }
9121
9122             Value *NewTrueOp = OtherAddOp;
9123             Value *NewFalseOp = NegVal;
9124             if (AddOp != TI)
9125               std::swap(NewTrueOp, NewFalseOp);
9126             Instruction *NewSel =
9127               SelectInst::Create(CondVal, NewTrueOp,
9128                                  NewFalseOp, SI.getName() + ".p");
9129
9130             NewSel = InsertNewInstBefore(NewSel, SI);
9131             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9132           }
9133         }
9134       }
9135
9136   // See if we can fold the select into one of our operands.
9137   if (SI.getType()->isInteger()) {
9138     // See the comment above GetSelectFoldableOperands for a description of the
9139     // transformation we are doing here.
9140     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9141       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9142           !isa<Constant>(FalseVal))
9143         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9144           unsigned OpToFold = 0;
9145           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9146             OpToFold = 1;
9147           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9148             OpToFold = 2;
9149           }
9150
9151           if (OpToFold) {
9152             Constant *C = GetSelectFoldableConstant(TVI);
9153             Instruction *NewSel =
9154               SelectInst::Create(SI.getCondition(),
9155                                  TVI->getOperand(2-OpToFold), C);
9156             InsertNewInstBefore(NewSel, SI);
9157             NewSel->takeName(TVI);
9158             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9159               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9160             else {
9161               assert(0 && "Unknown instruction!!");
9162             }
9163           }
9164         }
9165
9166     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9167       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9168           !isa<Constant>(TrueVal))
9169         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9170           unsigned OpToFold = 0;
9171           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9172             OpToFold = 1;
9173           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9174             OpToFold = 2;
9175           }
9176
9177           if (OpToFold) {
9178             Constant *C = GetSelectFoldableConstant(FVI);
9179             Instruction *NewSel =
9180               SelectInst::Create(SI.getCondition(), C,
9181                                  FVI->getOperand(2-OpToFold));
9182             InsertNewInstBefore(NewSel, SI);
9183             NewSel->takeName(FVI);
9184             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9185               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9186             else
9187               assert(0 && "Unknown instruction!!");
9188           }
9189         }
9190   }
9191
9192   if (BinaryOperator::isNot(CondVal)) {
9193     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9194     SI.setOperand(1, FalseVal);
9195     SI.setOperand(2, TrueVal);
9196     return &SI;
9197   }
9198
9199   return 0;
9200 }
9201
9202 /// EnforceKnownAlignment - If the specified pointer points to an object that
9203 /// we control, modify the object's alignment to PrefAlign. This isn't
9204 /// often possible though. If alignment is important, a more reliable approach
9205 /// is to simply align all global variables and allocation instructions to
9206 /// their preferred alignment from the beginning.
9207 ///
9208 static unsigned EnforceKnownAlignment(Value *V,
9209                                       unsigned Align, unsigned PrefAlign) {
9210
9211   User *U = dyn_cast<User>(V);
9212   if (!U) return Align;
9213
9214   switch (getOpcode(U)) {
9215   default: break;
9216   case Instruction::BitCast:
9217     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9218   case Instruction::GetElementPtr: {
9219     // If all indexes are zero, it is just the alignment of the base pointer.
9220     bool AllZeroOperands = true;
9221     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9222       if (!isa<Constant>(*i) ||
9223           !cast<Constant>(*i)->isNullValue()) {
9224         AllZeroOperands = false;
9225         break;
9226       }
9227
9228     if (AllZeroOperands) {
9229       // Treat this like a bitcast.
9230       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9231     }
9232     break;
9233   }
9234   }
9235
9236   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9237     // If there is a large requested alignment and we can, bump up the alignment
9238     // of the global.
9239     if (!GV->isDeclaration()) {
9240       GV->setAlignment(PrefAlign);
9241       Align = PrefAlign;
9242     }
9243   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9244     // If there is a requested alignment and if this is an alloca, round up.  We
9245     // don't do this for malloc, because some systems can't respect the request.
9246     if (isa<AllocaInst>(AI)) {
9247       AI->setAlignment(PrefAlign);
9248       Align = PrefAlign;
9249     }
9250   }
9251
9252   return Align;
9253 }
9254
9255 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9256 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9257 /// and it is more than the alignment of the ultimate object, see if we can
9258 /// increase the alignment of the ultimate object, making this check succeed.
9259 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9260                                                   unsigned PrefAlign) {
9261   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9262                       sizeof(PrefAlign) * CHAR_BIT;
9263   APInt Mask = APInt::getAllOnesValue(BitWidth);
9264   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9265   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9266   unsigned TrailZ = KnownZero.countTrailingOnes();
9267   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9268
9269   if (PrefAlign > Align)
9270     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9271   
9272     // We don't need to make any adjustment.
9273   return Align;
9274 }
9275
9276 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9277   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9278   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), DstAlign);
9279   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9280   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9281
9282   if (CopyAlign < MinAlign) {
9283     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9284     return MI;
9285   }
9286   
9287   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9288   // load/store.
9289   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9290   if (MemOpLength == 0) return 0;
9291   
9292   // Source and destination pointer types are always "i8*" for intrinsic.  See
9293   // if the size is something we can handle with a single primitive load/store.
9294   // A single load+store correctly handles overlapping memory in the memmove
9295   // case.
9296   unsigned Size = MemOpLength->getZExtValue();
9297   if (Size == 0) return MI;  // Delete this mem transfer.
9298   
9299   if (Size > 8 || (Size&(Size-1)))
9300     return 0;  // If not 1/2/4/8 bytes, exit.
9301   
9302   // Use an integer load+store unless we can find something better.
9303   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9304   
9305   // Memcpy forces the use of i8* for the source and destination.  That means
9306   // that if you're using memcpy to move one double around, you'll get a cast
9307   // from double* to i8*.  We'd much rather use a double load+store rather than
9308   // an i64 load+store, here because this improves the odds that the source or
9309   // dest address will be promotable.  See if we can find a better type than the
9310   // integer datatype.
9311   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9312     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9313     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9314       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9315       // down through these levels if so.
9316       while (!SrcETy->isSingleValueType()) {
9317         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9318           if (STy->getNumElements() == 1)
9319             SrcETy = STy->getElementType(0);
9320           else
9321             break;
9322         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9323           if (ATy->getNumElements() == 1)
9324             SrcETy = ATy->getElementType();
9325           else
9326             break;
9327         } else
9328           break;
9329       }
9330       
9331       if (SrcETy->isSingleValueType())
9332         NewPtrTy = PointerType::getUnqual(SrcETy);
9333     }
9334   }
9335   
9336   
9337   // If the memcpy/memmove provides better alignment info than we can
9338   // infer, use it.
9339   SrcAlign = std::max(SrcAlign, CopyAlign);
9340   DstAlign = std::max(DstAlign, CopyAlign);
9341   
9342   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9343   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9344   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9345   InsertNewInstBefore(L, *MI);
9346   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9347
9348   // Set the size of the copy to 0, it will be deleted on the next iteration.
9349   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9350   return MI;
9351 }
9352
9353 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9354   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9355   if (MI->getAlignment()->getZExtValue() < Alignment) {
9356     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9357     return MI;
9358   }
9359   
9360   // Extract the length and alignment and fill if they are constant.
9361   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9362   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9363   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9364     return 0;
9365   uint64_t Len = LenC->getZExtValue();
9366   Alignment = MI->getAlignment()->getZExtValue();
9367   
9368   // If the length is zero, this is a no-op
9369   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9370   
9371   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9372   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9373     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9374     
9375     Value *Dest = MI->getDest();
9376     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9377
9378     // Alignment 0 is identity for alignment 1 for memset, but not store.
9379     if (Alignment == 0) Alignment = 1;
9380     
9381     // Extract the fill value and store.
9382     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9383     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9384                                       Alignment), *MI);
9385     
9386     // Set the size of the copy to 0, it will be deleted on the next iteration.
9387     MI->setLength(Constant::getNullValue(LenC->getType()));
9388     return MI;
9389   }
9390
9391   return 0;
9392 }
9393
9394
9395 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9396 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9397 /// the heavy lifting.
9398 ///
9399 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9400   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9401   if (!II) return visitCallSite(&CI);
9402   
9403   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9404   // visitCallSite.
9405   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9406     bool Changed = false;
9407
9408     // memmove/cpy/set of zero bytes is a noop.
9409     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9410       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9411
9412       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9413         if (CI->getZExtValue() == 1) {
9414           // Replace the instruction with just byte operations.  We would
9415           // transform other cases to loads/stores, but we don't know if
9416           // alignment is sufficient.
9417         }
9418     }
9419
9420     // If we have a memmove and the source operation is a constant global,
9421     // then the source and dest pointers can't alias, so we can change this
9422     // into a call to memcpy.
9423     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9424       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9425         if (GVSrc->isConstant()) {
9426           Module *M = CI.getParent()->getParent()->getParent();
9427           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9428           const Type *Tys[1];
9429           Tys[0] = CI.getOperand(3)->getType();
9430           CI.setOperand(0, 
9431                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9432           Changed = true;
9433         }
9434
9435       // memmove(x,x,size) -> noop.
9436       if (MMI->getSource() == MMI->getDest())
9437         return EraseInstFromFunction(CI);
9438     }
9439
9440     // If we can determine a pointer alignment that is bigger than currently
9441     // set, update the alignment.
9442     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9443       if (Instruction *I = SimplifyMemTransfer(MI))
9444         return I;
9445     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9446       if (Instruction *I = SimplifyMemSet(MSI))
9447         return I;
9448     }
9449           
9450     if (Changed) return II;
9451   }
9452   
9453   switch (II->getIntrinsicID()) {
9454   default: break;
9455   case Intrinsic::bswap:
9456     // bswap(bswap(x)) -> x
9457     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9458       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9459         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9460     break;
9461   case Intrinsic::ppc_altivec_lvx:
9462   case Intrinsic::ppc_altivec_lvxl:
9463   case Intrinsic::x86_sse_loadu_ps:
9464   case Intrinsic::x86_sse2_loadu_pd:
9465   case Intrinsic::x86_sse2_loadu_dq:
9466     // Turn PPC lvx     -> load if the pointer is known aligned.
9467     // Turn X86 loadups -> load if the pointer is known aligned.
9468     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9469       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9470                                        PointerType::getUnqual(II->getType()),
9471                                        CI);
9472       return new LoadInst(Ptr);
9473     }
9474     break;
9475   case Intrinsic::ppc_altivec_stvx:
9476   case Intrinsic::ppc_altivec_stvxl:
9477     // Turn stvx -> store if the pointer is known aligned.
9478     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9479       const Type *OpPtrTy = 
9480         PointerType::getUnqual(II->getOperand(1)->getType());
9481       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9482       return new StoreInst(II->getOperand(1), Ptr);
9483     }
9484     break;
9485   case Intrinsic::x86_sse_storeu_ps:
9486   case Intrinsic::x86_sse2_storeu_pd:
9487   case Intrinsic::x86_sse2_storeu_dq:
9488     // Turn X86 storeu -> store if the pointer is known aligned.
9489     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9490       const Type *OpPtrTy = 
9491         PointerType::getUnqual(II->getOperand(2)->getType());
9492       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9493       return new StoreInst(II->getOperand(2), Ptr);
9494     }
9495     break;
9496     
9497   case Intrinsic::x86_sse_cvttss2si: {
9498     // These intrinsics only demands the 0th element of its input vector.  If
9499     // we can simplify the input based on that, do so now.
9500     unsigned VWidth =
9501       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9502     APInt DemandedElts(VWidth, 1);
9503     APInt UndefElts(VWidth, 0);
9504     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9505                                               UndefElts)) {
9506       II->setOperand(1, V);
9507       return II;
9508     }
9509     break;
9510   }
9511     
9512   case Intrinsic::ppc_altivec_vperm:
9513     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9514     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9515       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9516       
9517       // Check that all of the elements are integer constants or undefs.
9518       bool AllEltsOk = true;
9519       for (unsigned i = 0; i != 16; ++i) {
9520         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9521             !isa<UndefValue>(Mask->getOperand(i))) {
9522           AllEltsOk = false;
9523           break;
9524         }
9525       }
9526       
9527       if (AllEltsOk) {
9528         // Cast the input vectors to byte vectors.
9529         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9530         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9531         Value *Result = UndefValue::get(Op0->getType());
9532         
9533         // Only extract each element once.
9534         Value *ExtractedElts[32];
9535         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9536         
9537         for (unsigned i = 0; i != 16; ++i) {
9538           if (isa<UndefValue>(Mask->getOperand(i)))
9539             continue;
9540           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9541           Idx &= 31;  // Match the hardware behavior.
9542           
9543           if (ExtractedElts[Idx] == 0) {
9544             Instruction *Elt = 
9545               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9546             InsertNewInstBefore(Elt, CI);
9547             ExtractedElts[Idx] = Elt;
9548           }
9549         
9550           // Insert this value into the result vector.
9551           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9552                                              i, "tmp");
9553           InsertNewInstBefore(cast<Instruction>(Result), CI);
9554         }
9555         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9556       }
9557     }
9558     break;
9559
9560   case Intrinsic::stackrestore: {
9561     // If the save is right next to the restore, remove the restore.  This can
9562     // happen when variable allocas are DCE'd.
9563     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9564       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9565         BasicBlock::iterator BI = SS;
9566         if (&*++BI == II)
9567           return EraseInstFromFunction(CI);
9568       }
9569     }
9570     
9571     // Scan down this block to see if there is another stack restore in the
9572     // same block without an intervening call/alloca.
9573     BasicBlock::iterator BI = II;
9574     TerminatorInst *TI = II->getParent()->getTerminator();
9575     bool CannotRemove = false;
9576     for (++BI; &*BI != TI; ++BI) {
9577       if (isa<AllocaInst>(BI)) {
9578         CannotRemove = true;
9579         break;
9580       }
9581       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9582         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9583           // If there is a stackrestore below this one, remove this one.
9584           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9585             return EraseInstFromFunction(CI);
9586           // Otherwise, ignore the intrinsic.
9587         } else {
9588           // If we found a non-intrinsic call, we can't remove the stack
9589           // restore.
9590           CannotRemove = true;
9591           break;
9592         }
9593       }
9594     }
9595     
9596     // If the stack restore is in a return/unwind block and if there are no
9597     // allocas or calls between the restore and the return, nuke the restore.
9598     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9599       return EraseInstFromFunction(CI);
9600     break;
9601   }
9602   }
9603
9604   return visitCallSite(II);
9605 }
9606
9607 // InvokeInst simplification
9608 //
9609 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9610   return visitCallSite(&II);
9611 }
9612
9613 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9614 /// passed through the varargs area, we can eliminate the use of the cast.
9615 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9616                                          const CastInst * const CI,
9617                                          const TargetData * const TD,
9618                                          const int ix) {
9619   if (!CI->isLosslessCast())
9620     return false;
9621
9622   // The size of ByVal arguments is derived from the type, so we
9623   // can't change to a type with a different size.  If the size were
9624   // passed explicitly we could avoid this check.
9625   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9626     return true;
9627
9628   const Type* SrcTy = 
9629             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9630   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9631   if (!SrcTy->isSized() || !DstTy->isSized())
9632     return false;
9633   if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
9634     return false;
9635   return true;
9636 }
9637
9638 // visitCallSite - Improvements for call and invoke instructions.
9639 //
9640 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9641   bool Changed = false;
9642
9643   // If the callee is a constexpr cast of a function, attempt to move the cast
9644   // to the arguments of the call/invoke.
9645   if (transformConstExprCastCall(CS)) return 0;
9646
9647   Value *Callee = CS.getCalledValue();
9648
9649   if (Function *CalleeF = dyn_cast<Function>(Callee))
9650     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9651       Instruction *OldCall = CS.getInstruction();
9652       // If the call and callee calling conventions don't match, this call must
9653       // be unreachable, as the call is undefined.
9654       new StoreInst(ConstantInt::getTrue(),
9655                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9656                                     OldCall);
9657       if (!OldCall->use_empty())
9658         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9659       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9660         return EraseInstFromFunction(*OldCall);
9661       return 0;
9662     }
9663
9664   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9665     // This instruction is not reachable, just remove it.  We insert a store to
9666     // undef so that we know that this code is not reachable, despite the fact
9667     // that we can't modify the CFG here.
9668     new StoreInst(ConstantInt::getTrue(),
9669                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9670                   CS.getInstruction());
9671
9672     if (!CS.getInstruction()->use_empty())
9673       CS.getInstruction()->
9674         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9675
9676     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9677       // Don't break the CFG, insert a dummy cond branch.
9678       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9679                          ConstantInt::getTrue(), II);
9680     }
9681     return EraseInstFromFunction(*CS.getInstruction());
9682   }
9683
9684   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9685     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9686       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9687         return transformCallThroughTrampoline(CS);
9688
9689   const PointerType *PTy = cast<PointerType>(Callee->getType());
9690   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9691   if (FTy->isVarArg()) {
9692     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9693     // See if we can optimize any arguments passed through the varargs area of
9694     // the call.
9695     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9696            E = CS.arg_end(); I != E; ++I, ++ix) {
9697       CastInst *CI = dyn_cast<CastInst>(*I);
9698       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9699         *I = CI->getOperand(0);
9700         Changed = true;
9701       }
9702     }
9703   }
9704
9705   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9706     // Inline asm calls cannot throw - mark them 'nounwind'.
9707     CS.setDoesNotThrow();
9708     Changed = true;
9709   }
9710
9711   return Changed ? CS.getInstruction() : 0;
9712 }
9713
9714 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9715 // attempt to move the cast to the arguments of the call/invoke.
9716 //
9717 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9718   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9719   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9720   if (CE->getOpcode() != Instruction::BitCast || 
9721       !isa<Function>(CE->getOperand(0)))
9722     return false;
9723   Function *Callee = cast<Function>(CE->getOperand(0));
9724   Instruction *Caller = CS.getInstruction();
9725   const AttrListPtr &CallerPAL = CS.getAttributes();
9726
9727   // Okay, this is a cast from a function to a different type.  Unless doing so
9728   // would cause a type conversion of one of our arguments, change this call to
9729   // be a direct call with arguments casted to the appropriate types.
9730   //
9731   const FunctionType *FT = Callee->getFunctionType();
9732   const Type *OldRetTy = Caller->getType();
9733   const Type *NewRetTy = FT->getReturnType();
9734
9735   if (isa<StructType>(NewRetTy))
9736     return false; // TODO: Handle multiple return values.
9737
9738   // Check to see if we are changing the return type...
9739   if (OldRetTy != NewRetTy) {
9740     if (Callee->isDeclaration() &&
9741         // Conversion is ok if changing from one pointer type to another or from
9742         // a pointer to an integer of the same size.
9743         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9744           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9745       return false;   // Cannot transform this return value.
9746
9747     if (!Caller->use_empty() &&
9748         // void -> non-void is handled specially
9749         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9750       return false;   // Cannot transform this return value.
9751
9752     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9753       Attributes RAttrs = CallerPAL.getRetAttributes();
9754       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9755         return false;   // Attribute not compatible with transformed value.
9756     }
9757
9758     // If the callsite is an invoke instruction, and the return value is used by
9759     // a PHI node in a successor, we cannot change the return type of the call
9760     // because there is no place to put the cast instruction (without breaking
9761     // the critical edge).  Bail out in this case.
9762     if (!Caller->use_empty())
9763       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9764         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9765              UI != E; ++UI)
9766           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9767             if (PN->getParent() == II->getNormalDest() ||
9768                 PN->getParent() == II->getUnwindDest())
9769               return false;
9770   }
9771
9772   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9773   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9774
9775   CallSite::arg_iterator AI = CS.arg_begin();
9776   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9777     const Type *ParamTy = FT->getParamType(i);
9778     const Type *ActTy = (*AI)->getType();
9779
9780     if (!CastInst::isCastable(ActTy, ParamTy))
9781       return false;   // Cannot transform this parameter value.
9782
9783     if (CallerPAL.getParamAttributes(i + 1) 
9784         & Attribute::typeIncompatible(ParamTy))
9785       return false;   // Attribute not compatible with transformed value.
9786
9787     // Converting from one pointer type to another or between a pointer and an
9788     // integer of the same size is safe even if we do not have a body.
9789     bool isConvertible = ActTy == ParamTy ||
9790       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9791        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9792     if (Callee->isDeclaration() && !isConvertible) return false;
9793   }
9794
9795   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9796       Callee->isDeclaration())
9797     return false;   // Do not delete arguments unless we have a function body.
9798
9799   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9800       !CallerPAL.isEmpty())
9801     // In this case we have more arguments than the new function type, but we
9802     // won't be dropping them.  Check that these extra arguments have attributes
9803     // that are compatible with being a vararg call argument.
9804     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9805       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9806         break;
9807       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9808       if (PAttrs & Attribute::VarArgsIncompatible)
9809         return false;
9810     }
9811
9812   // Okay, we decided that this is a safe thing to do: go ahead and start
9813   // inserting cast instructions as necessary...
9814   std::vector<Value*> Args;
9815   Args.reserve(NumActualArgs);
9816   SmallVector<AttributeWithIndex, 8> attrVec;
9817   attrVec.reserve(NumCommonArgs);
9818
9819   // Get any return attributes.
9820   Attributes RAttrs = CallerPAL.getRetAttributes();
9821
9822   // If the return value is not being used, the type may not be compatible
9823   // with the existing attributes.  Wipe out any problematic attributes.
9824   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9825
9826   // Add the new return attributes.
9827   if (RAttrs)
9828     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9829
9830   AI = CS.arg_begin();
9831   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9832     const Type *ParamTy = FT->getParamType(i);
9833     if ((*AI)->getType() == ParamTy) {
9834       Args.push_back(*AI);
9835     } else {
9836       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9837           false, ParamTy, false);
9838       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9839       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9840     }
9841
9842     // Add any parameter attributes.
9843     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9844       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9845   }
9846
9847   // If the function takes more arguments than the call was taking, add them
9848   // now...
9849   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9850     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9851
9852   // If we are removing arguments to the function, emit an obnoxious warning...
9853   if (FT->getNumParams() < NumActualArgs) {
9854     if (!FT->isVarArg()) {
9855       cerr << "WARNING: While resolving call to function '"
9856            << Callee->getName() << "' arguments were dropped!\n";
9857     } else {
9858       // Add all of the arguments in their promoted form to the arg list...
9859       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9860         const Type *PTy = getPromotedType((*AI)->getType());
9861         if (PTy != (*AI)->getType()) {
9862           // Must promote to pass through va_arg area!
9863           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9864                                                                 PTy, false);
9865           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9866           InsertNewInstBefore(Cast, *Caller);
9867           Args.push_back(Cast);
9868         } else {
9869           Args.push_back(*AI);
9870         }
9871
9872         // Add any parameter attributes.
9873         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9874           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9875       }
9876     }
9877   }
9878
9879   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9880     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9881
9882   if (NewRetTy == Type::VoidTy)
9883     Caller->setName("");   // Void type should not have a name.
9884
9885   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9886
9887   Instruction *NC;
9888   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9889     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9890                             Args.begin(), Args.end(),
9891                             Caller->getName(), Caller);
9892     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9893     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9894   } else {
9895     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9896                           Caller->getName(), Caller);
9897     CallInst *CI = cast<CallInst>(Caller);
9898     if (CI->isTailCall())
9899       cast<CallInst>(NC)->setTailCall();
9900     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9901     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9902   }
9903
9904   // Insert a cast of the return type as necessary.
9905   Value *NV = NC;
9906   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9907     if (NV->getType() != Type::VoidTy) {
9908       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9909                                                             OldRetTy, false);
9910       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9911
9912       // If this is an invoke instruction, we should insert it after the first
9913       // non-phi, instruction in the normal successor block.
9914       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9915         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9916         InsertNewInstBefore(NC, *I);
9917       } else {
9918         // Otherwise, it's a call, just insert cast right after the call instr
9919         InsertNewInstBefore(NC, *Caller);
9920       }
9921       AddUsersToWorkList(*Caller);
9922     } else {
9923       NV = UndefValue::get(Caller->getType());
9924     }
9925   }
9926
9927   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9928     Caller->replaceAllUsesWith(NV);
9929   Caller->eraseFromParent();
9930   RemoveFromWorkList(Caller);
9931   return true;
9932 }
9933
9934 // transformCallThroughTrampoline - Turn a call to a function created by the
9935 // init_trampoline intrinsic into a direct call to the underlying function.
9936 //
9937 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9938   Value *Callee = CS.getCalledValue();
9939   const PointerType *PTy = cast<PointerType>(Callee->getType());
9940   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9941   const AttrListPtr &Attrs = CS.getAttributes();
9942
9943   // If the call already has the 'nest' attribute somewhere then give up -
9944   // otherwise 'nest' would occur twice after splicing in the chain.
9945   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9946     return 0;
9947
9948   IntrinsicInst *Tramp =
9949     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9950
9951   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9952   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9953   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9954
9955   const AttrListPtr &NestAttrs = NestF->getAttributes();
9956   if (!NestAttrs.isEmpty()) {
9957     unsigned NestIdx = 1;
9958     const Type *NestTy = 0;
9959     Attributes NestAttr = Attribute::None;
9960
9961     // Look for a parameter marked with the 'nest' attribute.
9962     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9963          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9964       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9965         // Record the parameter type and any other attributes.
9966         NestTy = *I;
9967         NestAttr = NestAttrs.getParamAttributes(NestIdx);
9968         break;
9969       }
9970
9971     if (NestTy) {
9972       Instruction *Caller = CS.getInstruction();
9973       std::vector<Value*> NewArgs;
9974       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9975
9976       SmallVector<AttributeWithIndex, 8> NewAttrs;
9977       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9978
9979       // Insert the nest argument into the call argument list, which may
9980       // mean appending it.  Likewise for attributes.
9981
9982       // Add any result attributes.
9983       if (Attributes Attr = Attrs.getRetAttributes())
9984         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9985
9986       {
9987         unsigned Idx = 1;
9988         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9989         do {
9990           if (Idx == NestIdx) {
9991             // Add the chain argument and attributes.
9992             Value *NestVal = Tramp->getOperand(3);
9993             if (NestVal->getType() != NestTy)
9994               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9995             NewArgs.push_back(NestVal);
9996             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9997           }
9998
9999           if (I == E)
10000             break;
10001
10002           // Add the original argument and attributes.
10003           NewArgs.push_back(*I);
10004           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10005             NewAttrs.push_back
10006               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10007
10008           ++Idx, ++I;
10009         } while (1);
10010       }
10011
10012       // Add any function attributes.
10013       if (Attributes Attr = Attrs.getFnAttributes())
10014         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10015
10016       // The trampoline may have been bitcast to a bogus type (FTy).
10017       // Handle this by synthesizing a new function type, equal to FTy
10018       // with the chain parameter inserted.
10019
10020       std::vector<const Type*> NewTypes;
10021       NewTypes.reserve(FTy->getNumParams()+1);
10022
10023       // Insert the chain's type into the list of parameter types, which may
10024       // mean appending it.
10025       {
10026         unsigned Idx = 1;
10027         FunctionType::param_iterator I = FTy->param_begin(),
10028           E = FTy->param_end();
10029
10030         do {
10031           if (Idx == NestIdx)
10032             // Add the chain's type.
10033             NewTypes.push_back(NestTy);
10034
10035           if (I == E)
10036             break;
10037
10038           // Add the original type.
10039           NewTypes.push_back(*I);
10040
10041           ++Idx, ++I;
10042         } while (1);
10043       }
10044
10045       // Replace the trampoline call with a direct call.  Let the generic
10046       // code sort out any function type mismatches.
10047       FunctionType *NewFTy =
10048         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10049       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10050         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10051       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10052
10053       Instruction *NewCaller;
10054       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10055         NewCaller = InvokeInst::Create(NewCallee,
10056                                        II->getNormalDest(), II->getUnwindDest(),
10057                                        NewArgs.begin(), NewArgs.end(),
10058                                        Caller->getName(), Caller);
10059         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10060         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10061       } else {
10062         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10063                                      Caller->getName(), Caller);
10064         if (cast<CallInst>(Caller)->isTailCall())
10065           cast<CallInst>(NewCaller)->setTailCall();
10066         cast<CallInst>(NewCaller)->
10067           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10068         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10069       }
10070       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10071         Caller->replaceAllUsesWith(NewCaller);
10072       Caller->eraseFromParent();
10073       RemoveFromWorkList(Caller);
10074       return 0;
10075     }
10076   }
10077
10078   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10079   // parameter, there is no need to adjust the argument list.  Let the generic
10080   // code sort out any function type mismatches.
10081   Constant *NewCallee =
10082     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10083   CS.setCalledFunction(NewCallee);
10084   return CS.getInstruction();
10085 }
10086
10087 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10088 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10089 /// and a single binop.
10090 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10091   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10092   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10093   unsigned Opc = FirstInst->getOpcode();
10094   Value *LHSVal = FirstInst->getOperand(0);
10095   Value *RHSVal = FirstInst->getOperand(1);
10096     
10097   const Type *LHSType = LHSVal->getType();
10098   const Type *RHSType = RHSVal->getType();
10099   
10100   // Scan to see if all operands are the same opcode, all have one use, and all
10101   // kill their operands (i.e. the operands have one use).
10102   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10103     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10104     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10105         // Verify type of the LHS matches so we don't fold cmp's of different
10106         // types or GEP's with different index types.
10107         I->getOperand(0)->getType() != LHSType ||
10108         I->getOperand(1)->getType() != RHSType)
10109       return 0;
10110
10111     // If they are CmpInst instructions, check their predicates
10112     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10113       if (cast<CmpInst>(I)->getPredicate() !=
10114           cast<CmpInst>(FirstInst)->getPredicate())
10115         return 0;
10116     
10117     // Keep track of which operand needs a phi node.
10118     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10119     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10120   }
10121   
10122   // Otherwise, this is safe to transform!
10123   
10124   Value *InLHS = FirstInst->getOperand(0);
10125   Value *InRHS = FirstInst->getOperand(1);
10126   PHINode *NewLHS = 0, *NewRHS = 0;
10127   if (LHSVal == 0) {
10128     NewLHS = PHINode::Create(LHSType,
10129                              FirstInst->getOperand(0)->getName() + ".pn");
10130     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10131     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10132     InsertNewInstBefore(NewLHS, PN);
10133     LHSVal = NewLHS;
10134   }
10135   
10136   if (RHSVal == 0) {
10137     NewRHS = PHINode::Create(RHSType,
10138                              FirstInst->getOperand(1)->getName() + ".pn");
10139     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10140     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10141     InsertNewInstBefore(NewRHS, PN);
10142     RHSVal = NewRHS;
10143   }
10144   
10145   // Add all operands to the new PHIs.
10146   if (NewLHS || NewRHS) {
10147     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10148       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10149       if (NewLHS) {
10150         Value *NewInLHS = InInst->getOperand(0);
10151         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10152       }
10153       if (NewRHS) {
10154         Value *NewInRHS = InInst->getOperand(1);
10155         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10156       }
10157     }
10158   }
10159     
10160   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10161     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10162   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10163   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10164                          RHSVal);
10165 }
10166
10167 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10168   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10169   
10170   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10171                                         FirstInst->op_end());
10172   
10173   // Scan to see if all operands are the same opcode, all have one use, and all
10174   // kill their operands (i.e. the operands have one use).
10175   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10176     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10177     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10178       GEP->getNumOperands() != FirstInst->getNumOperands())
10179       return 0;
10180
10181     // Compare the operand lists.
10182     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10183       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10184         continue;
10185       
10186       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10187       // if one of the PHIs has a constant for the index.  The index may be
10188       // substantially cheaper to compute for the constants, so making it a
10189       // variable index could pessimize the path.  This also handles the case
10190       // for struct indices, which must always be constant.
10191       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10192           isa<ConstantInt>(GEP->getOperand(op)))
10193         return 0;
10194       
10195       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10196         return 0;
10197       FixedOperands[op] = 0;  // Needs a PHI.
10198     }
10199   }
10200   
10201   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10202   // that is variable.
10203   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10204   
10205   bool HasAnyPHIs = false;
10206   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10207     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10208     Value *FirstOp = FirstInst->getOperand(i);
10209     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10210                                      FirstOp->getName()+".pn");
10211     InsertNewInstBefore(NewPN, PN);
10212     
10213     NewPN->reserveOperandSpace(e);
10214     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10215     OperandPhis[i] = NewPN;
10216     FixedOperands[i] = NewPN;
10217     HasAnyPHIs = true;
10218   }
10219
10220   
10221   // Add all operands to the new PHIs.
10222   if (HasAnyPHIs) {
10223     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10224       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10225       BasicBlock *InBB = PN.getIncomingBlock(i);
10226       
10227       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10228         if (PHINode *OpPhi = OperandPhis[op])
10229           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10230     }
10231   }
10232   
10233   Value *Base = FixedOperands[0];
10234   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10235                                    FixedOperands.end());
10236 }
10237
10238
10239 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10240 /// of the block that defines it.  This means that it must be obvious the value
10241 /// of the load is not changed from the point of the load to the end of the
10242 /// block it is in.
10243 ///
10244 /// Finally, it is safe, but not profitable, to sink a load targetting a
10245 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10246 /// to a register.
10247 static bool isSafeToSinkLoad(LoadInst *L) {
10248   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10249   
10250   for (++BBI; BBI != E; ++BBI)
10251     if (BBI->mayWriteToMemory())
10252       return false;
10253   
10254   // Check for non-address taken alloca.  If not address-taken already, it isn't
10255   // profitable to do this xform.
10256   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10257     bool isAddressTaken = false;
10258     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10259          UI != E; ++UI) {
10260       if (isa<LoadInst>(UI)) continue;
10261       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10262         // If storing TO the alloca, then the address isn't taken.
10263         if (SI->getOperand(1) == AI) continue;
10264       }
10265       isAddressTaken = true;
10266       break;
10267     }
10268     
10269     if (!isAddressTaken)
10270       return false;
10271   }
10272   
10273   return true;
10274 }
10275
10276
10277 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10278 // operator and they all are only used by the PHI, PHI together their
10279 // inputs, and do the operation once, to the result of the PHI.
10280 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10281   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10282
10283   // Scan the instruction, looking for input operations that can be folded away.
10284   // If all input operands to the phi are the same instruction (e.g. a cast from
10285   // the same type or "+42") we can pull the operation through the PHI, reducing
10286   // code size and simplifying code.
10287   Constant *ConstantOp = 0;
10288   const Type *CastSrcTy = 0;
10289   bool isVolatile = false;
10290   if (isa<CastInst>(FirstInst)) {
10291     CastSrcTy = FirstInst->getOperand(0)->getType();
10292   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10293     // Can fold binop, compare or shift here if the RHS is a constant, 
10294     // otherwise call FoldPHIArgBinOpIntoPHI.
10295     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10296     if (ConstantOp == 0)
10297       return FoldPHIArgBinOpIntoPHI(PN);
10298   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10299     isVolatile = LI->isVolatile();
10300     // We can't sink the load if the loaded value could be modified between the
10301     // load and the PHI.
10302     if (LI->getParent() != PN.getIncomingBlock(0) ||
10303         !isSafeToSinkLoad(LI))
10304       return 0;
10305     
10306     // If the PHI is of volatile loads and the load block has multiple
10307     // successors, sinking it would remove a load of the volatile value from
10308     // the path through the other successor.
10309     if (isVolatile &&
10310         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10311       return 0;
10312     
10313   } else if (isa<GetElementPtrInst>(FirstInst)) {
10314     return FoldPHIArgGEPIntoPHI(PN);
10315   } else {
10316     return 0;  // Cannot fold this operation.
10317   }
10318
10319   // Check to see if all arguments are the same operation.
10320   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10321     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10322     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10323     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10324       return 0;
10325     if (CastSrcTy) {
10326       if (I->getOperand(0)->getType() != CastSrcTy)
10327         return 0;  // Cast operation must match.
10328     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10329       // We can't sink the load if the loaded value could be modified between 
10330       // the load and the PHI.
10331       if (LI->isVolatile() != isVolatile ||
10332           LI->getParent() != PN.getIncomingBlock(i) ||
10333           !isSafeToSinkLoad(LI))
10334         return 0;
10335       
10336       // If the PHI is of volatile loads and the load block has multiple
10337       // successors, sinking it would remove a load of the volatile value from
10338       // the path through the other successor.
10339       if (isVolatile &&
10340           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10341         return 0;
10342
10343       
10344     } else if (I->getOperand(1) != ConstantOp) {
10345       return 0;
10346     }
10347   }
10348
10349   // Okay, they are all the same operation.  Create a new PHI node of the
10350   // correct type, and PHI together all of the LHS's of the instructions.
10351   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10352                                    PN.getName()+".in");
10353   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10354
10355   Value *InVal = FirstInst->getOperand(0);
10356   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10357
10358   // Add all operands to the new PHI.
10359   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10360     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10361     if (NewInVal != InVal)
10362       InVal = 0;
10363     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10364   }
10365
10366   Value *PhiVal;
10367   if (InVal) {
10368     // The new PHI unions all of the same values together.  This is really
10369     // common, so we handle it intelligently here for compile-time speed.
10370     PhiVal = InVal;
10371     delete NewPN;
10372   } else {
10373     InsertNewInstBefore(NewPN, PN);
10374     PhiVal = NewPN;
10375   }
10376
10377   // Insert and return the new operation.
10378   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10379     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10380   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10381     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10382   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10383     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10384                            PhiVal, ConstantOp);
10385   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10386   
10387   // If this was a volatile load that we are merging, make sure to loop through
10388   // and mark all the input loads as non-volatile.  If we don't do this, we will
10389   // insert a new volatile load and the old ones will not be deletable.
10390   if (isVolatile)
10391     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10392       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10393   
10394   return new LoadInst(PhiVal, "", isVolatile);
10395 }
10396
10397 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10398 /// that is dead.
10399 static bool DeadPHICycle(PHINode *PN,
10400                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10401   if (PN->use_empty()) return true;
10402   if (!PN->hasOneUse()) return false;
10403
10404   // Remember this node, and if we find the cycle, return.
10405   if (!PotentiallyDeadPHIs.insert(PN))
10406     return true;
10407   
10408   // Don't scan crazily complex things.
10409   if (PotentiallyDeadPHIs.size() == 16)
10410     return false;
10411
10412   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10413     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10414
10415   return false;
10416 }
10417
10418 /// PHIsEqualValue - Return true if this phi node is always equal to
10419 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10420 ///   z = some value; x = phi (y, z); y = phi (x, z)
10421 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10422                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10423   // See if we already saw this PHI node.
10424   if (!ValueEqualPHIs.insert(PN))
10425     return true;
10426   
10427   // Don't scan crazily complex things.
10428   if (ValueEqualPHIs.size() == 16)
10429     return false;
10430  
10431   // Scan the operands to see if they are either phi nodes or are equal to
10432   // the value.
10433   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10434     Value *Op = PN->getIncomingValue(i);
10435     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10436       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10437         return false;
10438     } else if (Op != NonPhiInVal)
10439       return false;
10440   }
10441   
10442   return true;
10443 }
10444
10445
10446 // PHINode simplification
10447 //
10448 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10449   // If LCSSA is around, don't mess with Phi nodes
10450   if (MustPreserveLCSSA) return 0;
10451   
10452   if (Value *V = PN.hasConstantValue())
10453     return ReplaceInstUsesWith(PN, V);
10454
10455   // If all PHI operands are the same operation, pull them through the PHI,
10456   // reducing code size.
10457   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10458       isa<Instruction>(PN.getIncomingValue(1)) &&
10459       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10460       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10461       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10462       // than themselves more than once.
10463       PN.getIncomingValue(0)->hasOneUse())
10464     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10465       return Result;
10466
10467   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10468   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10469   // PHI)... break the cycle.
10470   if (PN.hasOneUse()) {
10471     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10472     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10473       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10474       PotentiallyDeadPHIs.insert(&PN);
10475       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10476         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10477     }
10478    
10479     // If this phi has a single use, and if that use just computes a value for
10480     // the next iteration of a loop, delete the phi.  This occurs with unused
10481     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10482     // common case here is good because the only other things that catch this
10483     // are induction variable analysis (sometimes) and ADCE, which is only run
10484     // late.
10485     if (PHIUser->hasOneUse() &&
10486         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10487         PHIUser->use_back() == &PN) {
10488       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10489     }
10490   }
10491
10492   // We sometimes end up with phi cycles that non-obviously end up being the
10493   // same value, for example:
10494   //   z = some value; x = phi (y, z); y = phi (x, z)
10495   // where the phi nodes don't necessarily need to be in the same block.  Do a
10496   // quick check to see if the PHI node only contains a single non-phi value, if
10497   // so, scan to see if the phi cycle is actually equal to that value.
10498   {
10499     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10500     // Scan for the first non-phi operand.
10501     while (InValNo != NumOperandVals && 
10502            isa<PHINode>(PN.getIncomingValue(InValNo)))
10503       ++InValNo;
10504
10505     if (InValNo != NumOperandVals) {
10506       Value *NonPhiInVal = PN.getOperand(InValNo);
10507       
10508       // Scan the rest of the operands to see if there are any conflicts, if so
10509       // there is no need to recursively scan other phis.
10510       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10511         Value *OpVal = PN.getIncomingValue(InValNo);
10512         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10513           break;
10514       }
10515       
10516       // If we scanned over all operands, then we have one unique value plus
10517       // phi values.  Scan PHI nodes to see if they all merge in each other or
10518       // the value.
10519       if (InValNo == NumOperandVals) {
10520         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10521         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10522           return ReplaceInstUsesWith(PN, NonPhiInVal);
10523       }
10524     }
10525   }
10526   return 0;
10527 }
10528
10529 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10530                                    Instruction *InsertPoint,
10531                                    InstCombiner *IC) {
10532   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10533   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10534   // We must cast correctly to the pointer type. Ensure that we
10535   // sign extend the integer value if it is smaller as this is
10536   // used for address computation.
10537   Instruction::CastOps opcode = 
10538      (VTySize < PtrSize ? Instruction::SExt :
10539       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10540   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10541 }
10542
10543
10544 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10545   Value *PtrOp = GEP.getOperand(0);
10546   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10547   // If so, eliminate the noop.
10548   if (GEP.getNumOperands() == 1)
10549     return ReplaceInstUsesWith(GEP, PtrOp);
10550
10551   if (isa<UndefValue>(GEP.getOperand(0)))
10552     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10553
10554   bool HasZeroPointerIndex = false;
10555   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10556     HasZeroPointerIndex = C->isNullValue();
10557
10558   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10559     return ReplaceInstUsesWith(GEP, PtrOp);
10560
10561   // Eliminate unneeded casts for indices.
10562   bool MadeChange = false;
10563   
10564   gep_type_iterator GTI = gep_type_begin(GEP);
10565   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10566        i != e; ++i, ++GTI) {
10567     if (isa<SequentialType>(*GTI)) {
10568       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10569         if (CI->getOpcode() == Instruction::ZExt ||
10570             CI->getOpcode() == Instruction::SExt) {
10571           const Type *SrcTy = CI->getOperand(0)->getType();
10572           // We can eliminate a cast from i32 to i64 iff the target 
10573           // is a 32-bit pointer target.
10574           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10575             MadeChange = true;
10576             *i = CI->getOperand(0);
10577           }
10578         }
10579       }
10580       // If we are using a wider index than needed for this platform, shrink it
10581       // to what we need.  If narrower, sign-extend it to what we need.
10582       // If the incoming value needs a cast instruction,
10583       // insert it.  This explicit cast can make subsequent optimizations more
10584       // obvious.
10585       Value *Op = *i;
10586       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10587         if (Constant *C = dyn_cast<Constant>(Op)) {
10588           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10589           MadeChange = true;
10590         } else {
10591           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10592                                 GEP);
10593           *i = Op;
10594           MadeChange = true;
10595         }
10596       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10597         if (Constant *C = dyn_cast<Constant>(Op)) {
10598           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10599           MadeChange = true;
10600         } else {
10601           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10602                                 GEP);
10603           *i = Op;
10604           MadeChange = true;
10605         }
10606       }
10607     }
10608   }
10609   if (MadeChange) return &GEP;
10610
10611   // Combine Indices - If the source pointer to this getelementptr instruction
10612   // is a getelementptr instruction, combine the indices of the two
10613   // getelementptr instructions into a single instruction.
10614   //
10615   SmallVector<Value*, 8> SrcGEPOperands;
10616   if (User *Src = dyn_castGetElementPtr(PtrOp))
10617     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10618
10619   if (!SrcGEPOperands.empty()) {
10620     // Note that if our source is a gep chain itself that we wait for that
10621     // chain to be resolved before we perform this transformation.  This
10622     // avoids us creating a TON of code in some cases.
10623     //
10624     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10625         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10626       return 0;   // Wait until our source is folded to completion.
10627
10628     SmallVector<Value*, 8> Indices;
10629
10630     // Find out whether the last index in the source GEP is a sequential idx.
10631     bool EndsWithSequential = false;
10632     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10633            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10634       EndsWithSequential = !isa<StructType>(*I);
10635
10636     // Can we combine the two pointer arithmetics offsets?
10637     if (EndsWithSequential) {
10638       // Replace: gep (gep %P, long B), long A, ...
10639       // With:    T = long A+B; gep %P, T, ...
10640       //
10641       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10642       if (SO1 == Constant::getNullValue(SO1->getType())) {
10643         Sum = GO1;
10644       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10645         Sum = SO1;
10646       } else {
10647         // If they aren't the same type, convert both to an integer of the
10648         // target's pointer size.
10649         if (SO1->getType() != GO1->getType()) {
10650           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10651             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10652           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10653             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10654           } else {
10655             unsigned PS = TD->getPointerSizeInBits();
10656             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10657               // Convert GO1 to SO1's type.
10658               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10659
10660             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10661               // Convert SO1 to GO1's type.
10662               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10663             } else {
10664               const Type *PT = TD->getIntPtrType();
10665               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10666               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10667             }
10668           }
10669         }
10670         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10671           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10672         else {
10673           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10674           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10675         }
10676       }
10677
10678       // Recycle the GEP we already have if possible.
10679       if (SrcGEPOperands.size() == 2) {
10680         GEP.setOperand(0, SrcGEPOperands[0]);
10681         GEP.setOperand(1, Sum);
10682         return &GEP;
10683       } else {
10684         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10685                        SrcGEPOperands.end()-1);
10686         Indices.push_back(Sum);
10687         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10688       }
10689     } else if (isa<Constant>(*GEP.idx_begin()) &&
10690                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10691                SrcGEPOperands.size() != 1) {
10692       // Otherwise we can do the fold if the first index of the GEP is a zero
10693       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10694                      SrcGEPOperands.end());
10695       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10696     }
10697
10698     if (!Indices.empty())
10699       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10700                                        Indices.end(), GEP.getName());
10701
10702   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10703     // GEP of global variable.  If all of the indices for this GEP are
10704     // constants, we can promote this to a constexpr instead of an instruction.
10705
10706     // Scan for nonconstants...
10707     SmallVector<Constant*, 8> Indices;
10708     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10709     for (; I != E && isa<Constant>(*I); ++I)
10710       Indices.push_back(cast<Constant>(*I));
10711
10712     if (I == E) {  // If they are all constants...
10713       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10714                                                     &Indices[0],Indices.size());
10715
10716       // Replace all uses of the GEP with the new constexpr...
10717       return ReplaceInstUsesWith(GEP, CE);
10718     }
10719   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10720     if (!isa<PointerType>(X->getType())) {
10721       // Not interesting.  Source pointer must be a cast from pointer.
10722     } else if (HasZeroPointerIndex) {
10723       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10724       // into     : GEP [10 x i8]* X, i32 0, ...
10725       //
10726       // This occurs when the program declares an array extern like "int X[];"
10727       //
10728       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10729       const PointerType *XTy = cast<PointerType>(X->getType());
10730       if (const ArrayType *XATy =
10731           dyn_cast<ArrayType>(XTy->getElementType()))
10732         if (const ArrayType *CATy =
10733             dyn_cast<ArrayType>(CPTy->getElementType()))
10734           if (CATy->getElementType() == XATy->getElementType()) {
10735             // At this point, we know that the cast source type is a pointer
10736             // to an array of the same type as the destination pointer
10737             // array.  Because the array type is never stepped over (there
10738             // is a leading zero) we can fold the cast into this GEP.
10739             GEP.setOperand(0, X);
10740             return &GEP;
10741           }
10742     } else if (GEP.getNumOperands() == 2) {
10743       // Transform things like:
10744       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10745       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10746       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10747       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10748       if (isa<ArrayType>(SrcElTy) &&
10749           TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10750           TD->getTypePaddedSize(ResElTy)) {
10751         Value *Idx[2];
10752         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10753         Idx[1] = GEP.getOperand(1);
10754         Value *V = InsertNewInstBefore(
10755                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10756         // V and GEP are both pointer types --> BitCast
10757         return new BitCastInst(V, GEP.getType());
10758       }
10759       
10760       // Transform things like:
10761       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10762       //   (where tmp = 8*tmp2) into:
10763       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10764       
10765       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10766         uint64_t ArrayEltSize =
10767             TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
10768         
10769         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10770         // allow either a mul, shift, or constant here.
10771         Value *NewIdx = 0;
10772         ConstantInt *Scale = 0;
10773         if (ArrayEltSize == 1) {
10774           NewIdx = GEP.getOperand(1);
10775           Scale = ConstantInt::get(NewIdx->getType(), 1);
10776         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10777           NewIdx = ConstantInt::get(CI->getType(), 1);
10778           Scale = CI;
10779         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10780           if (Inst->getOpcode() == Instruction::Shl &&
10781               isa<ConstantInt>(Inst->getOperand(1))) {
10782             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10783             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10784             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10785             NewIdx = Inst->getOperand(0);
10786           } else if (Inst->getOpcode() == Instruction::Mul &&
10787                      isa<ConstantInt>(Inst->getOperand(1))) {
10788             Scale = cast<ConstantInt>(Inst->getOperand(1));
10789             NewIdx = Inst->getOperand(0);
10790           }
10791         }
10792         
10793         // If the index will be to exactly the right offset with the scale taken
10794         // out, perform the transformation. Note, we don't know whether Scale is
10795         // signed or not. We'll use unsigned version of division/modulo
10796         // operation after making sure Scale doesn't have the sign bit set.
10797         if (Scale && Scale->getSExtValue() >= 0LL &&
10798             Scale->getZExtValue() % ArrayEltSize == 0) {
10799           Scale = ConstantInt::get(Scale->getType(),
10800                                    Scale->getZExtValue() / ArrayEltSize);
10801           if (Scale->getZExtValue() != 1) {
10802             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10803                                                        false /*ZExt*/);
10804             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10805             NewIdx = InsertNewInstBefore(Sc, GEP);
10806           }
10807
10808           // Insert the new GEP instruction.
10809           Value *Idx[2];
10810           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10811           Idx[1] = NewIdx;
10812           Instruction *NewGEP =
10813             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10814           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10815           // The NewGEP must be pointer typed, so must the old one -> BitCast
10816           return new BitCastInst(NewGEP, GEP.getType());
10817         }
10818       }
10819     }
10820   }
10821   
10822   /// See if we can simplify:
10823   ///   X = bitcast A to B*
10824   ///   Y = gep X, <...constant indices...>
10825   /// into a gep of the original struct.  This is important for SROA and alias
10826   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
10827   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
10828     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10829       // Determine how much the GEP moves the pointer.  We are guaranteed to get
10830       // a constant back from EmitGEPOffset.
10831       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10832       int64_t Offset = OffsetV->getSExtValue();
10833       
10834       // If this GEP instruction doesn't move the pointer, just replace the GEP
10835       // with a bitcast of the real input to the dest type.
10836       if (Offset == 0) {
10837         // If the bitcast is of an allocation, and the allocation will be
10838         // converted to match the type of the cast, don't touch this.
10839         if (isa<AllocationInst>(BCI->getOperand(0))) {
10840           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10841           if (Instruction *I = visitBitCast(*BCI)) {
10842             if (I != BCI) {
10843               I->takeName(BCI);
10844               BCI->getParent()->getInstList().insert(BCI, I);
10845               ReplaceInstUsesWith(*BCI, I);
10846             }
10847             return &GEP;
10848           }
10849         }
10850         return new BitCastInst(BCI->getOperand(0), GEP.getType());
10851       }
10852       
10853       // Otherwise, if the offset is non-zero, we need to find out if there is a
10854       // field at Offset in 'A's type.  If so, we can pull the cast through the
10855       // GEP.
10856       SmallVector<Value*, 8> NewIndices;
10857       const Type *InTy =
10858         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10859       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10860         Instruction *NGEP =
10861            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10862                                      NewIndices.end());
10863         if (NGEP->getType() == GEP.getType()) return NGEP;
10864         InsertNewInstBefore(NGEP, GEP);
10865         NGEP->takeName(&GEP);
10866         return new BitCastInst(NGEP, GEP.getType());
10867       }
10868     }
10869   }    
10870     
10871   return 0;
10872 }
10873
10874 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10875   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10876   if (AI.isArrayAllocation()) {  // Check C != 1
10877     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10878       const Type *NewTy = 
10879         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10880       AllocationInst *New = 0;
10881
10882       // Create and insert the replacement instruction...
10883       if (isa<MallocInst>(AI))
10884         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10885       else {
10886         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10887         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10888       }
10889
10890       InsertNewInstBefore(New, AI);
10891
10892       // Scan to the end of the allocation instructions, to skip over a block of
10893       // allocas if possible...
10894       //
10895       BasicBlock::iterator It = New;
10896       while (isa<AllocationInst>(*It)) ++It;
10897
10898       // Now that I is pointing to the first non-allocation-inst in the block,
10899       // insert our getelementptr instruction...
10900       //
10901       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10902       Value *Idx[2];
10903       Idx[0] = NullIdx;
10904       Idx[1] = NullIdx;
10905       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10906                                            New->getName()+".sub", It);
10907
10908       // Now make everything use the getelementptr instead of the original
10909       // allocation.
10910       return ReplaceInstUsesWith(AI, V);
10911     } else if (isa<UndefValue>(AI.getArraySize())) {
10912       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10913     }
10914   }
10915
10916   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10917     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10918     // Note that we only do this for alloca's, because malloc should allocate and
10919     // return a unique pointer, even for a zero byte allocation.
10920     if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10921       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10922
10923     // If the alignment is 0 (unspecified), assign it the preferred alignment.
10924     if (AI.getAlignment() == 0)
10925       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10926   }
10927
10928   return 0;
10929 }
10930
10931 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10932   Value *Op = FI.getOperand(0);
10933
10934   // free undef -> unreachable.
10935   if (isa<UndefValue>(Op)) {
10936     // Insert a new store to null because we cannot modify the CFG here.
10937     new StoreInst(ConstantInt::getTrue(),
10938                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10939     return EraseInstFromFunction(FI);
10940   }
10941   
10942   // If we have 'free null' delete the instruction.  This can happen in stl code
10943   // when lots of inlining happens.
10944   if (isa<ConstantPointerNull>(Op))
10945     return EraseInstFromFunction(FI);
10946   
10947   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10948   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10949     FI.setOperand(0, CI->getOperand(0));
10950     return &FI;
10951   }
10952   
10953   // Change free (gep X, 0,0,0,0) into free(X)
10954   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10955     if (GEPI->hasAllZeroIndices()) {
10956       AddToWorkList(GEPI);
10957       FI.setOperand(0, GEPI->getOperand(0));
10958       return &FI;
10959     }
10960   }
10961   
10962   // Change free(malloc) into nothing, if the malloc has a single use.
10963   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10964     if (MI->hasOneUse()) {
10965       EraseInstFromFunction(FI);
10966       return EraseInstFromFunction(*MI);
10967     }
10968
10969   return 0;
10970 }
10971
10972
10973 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10974 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10975                                         const TargetData *TD) {
10976   User *CI = cast<User>(LI.getOperand(0));
10977   Value *CastOp = CI->getOperand(0);
10978
10979   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10980     // Instead of loading constant c string, use corresponding integer value
10981     // directly if string length is small enough.
10982     std::string Str;
10983     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10984       unsigned len = Str.length();
10985       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10986       unsigned numBits = Ty->getPrimitiveSizeInBits();
10987       // Replace LI with immediate integer store.
10988       if ((numBits >> 3) == len + 1) {
10989         APInt StrVal(numBits, 0);
10990         APInt SingleChar(numBits, 0);
10991         if (TD->isLittleEndian()) {
10992           for (signed i = len-1; i >= 0; i--) {
10993             SingleChar = (uint64_t) Str[i];
10994             StrVal = (StrVal << 8) | SingleChar;
10995           }
10996         } else {
10997           for (unsigned i = 0; i < len; i++) {
10998             SingleChar = (uint64_t) Str[i];
10999             StrVal = (StrVal << 8) | SingleChar;
11000           }
11001           // Append NULL at the end.
11002           SingleChar = 0;
11003           StrVal = (StrVal << 8) | SingleChar;
11004         }
11005         Value *NL = ConstantInt::get(StrVal);
11006         return IC.ReplaceInstUsesWith(LI, NL);
11007       }
11008     }
11009   }
11010
11011   const PointerType *DestTy = cast<PointerType>(CI->getType());
11012   const Type *DestPTy = DestTy->getElementType();
11013   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11014
11015     // If the address spaces don't match, don't eliminate the cast.
11016     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11017       return 0;
11018
11019     const Type *SrcPTy = SrcTy->getElementType();
11020
11021     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11022          isa<VectorType>(DestPTy)) {
11023       // If the source is an array, the code below will not succeed.  Check to
11024       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11025       // constants.
11026       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11027         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11028           if (ASrcTy->getNumElements() != 0) {
11029             Value *Idxs[2];
11030             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11031             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11032             SrcTy = cast<PointerType>(CastOp->getType());
11033             SrcPTy = SrcTy->getElementType();
11034           }
11035
11036       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11037             isa<VectorType>(SrcPTy)) &&
11038           // Do not allow turning this into a load of an integer, which is then
11039           // casted to a pointer, this pessimizes pointer analysis a lot.
11040           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11041           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11042                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11043
11044         // Okay, we are casting from one integer or pointer type to another of
11045         // the same size.  Instead of casting the pointer before the load, cast
11046         // the result of the loaded value.
11047         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11048                                                              CI->getName(),
11049                                                          LI.isVolatile()),LI);
11050         // Now cast the result of the load.
11051         return new BitCastInst(NewLoad, LI.getType());
11052       }
11053     }
11054   }
11055   return 0;
11056 }
11057
11058 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
11059 /// from this value cannot trap.  If it is not obviously safe to load from the
11060 /// specified pointer, we do a quick local scan of the basic block containing
11061 /// ScanFrom, to determine if the address is already accessed.
11062 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
11063   // If it is an alloca it is always safe to load from.
11064   if (isa<AllocaInst>(V)) return true;
11065
11066   // If it is a global variable it is mostly safe to load from.
11067   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
11068     // Don't try to evaluate aliases.  External weak GV can be null.
11069     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
11070
11071   // Otherwise, be a little bit agressive by scanning the local block where we
11072   // want to check to see if the pointer is already being loaded or stored
11073   // from/to.  If so, the previous load or store would have already trapped,
11074   // so there is no harm doing an extra load (also, CSE will later eliminate
11075   // the load entirely).
11076   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11077
11078   while (BBI != E) {
11079     --BBI;
11080
11081     // If we see a free or a call (which might do a free) the pointer could be
11082     // marked invalid.
11083     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
11084       return false;
11085     
11086     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11087       if (LI->getOperand(0) == V) return true;
11088     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11089       if (SI->getOperand(1) == V) return true;
11090     }
11091
11092   }
11093   return false;
11094 }
11095
11096 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11097   Value *Op = LI.getOperand(0);
11098
11099   // Attempt to improve the alignment.
11100   unsigned KnownAlign =
11101     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11102   if (KnownAlign >
11103       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11104                                 LI.getAlignment()))
11105     LI.setAlignment(KnownAlign);
11106
11107   // load (cast X) --> cast (load X) iff safe
11108   if (isa<CastInst>(Op))
11109     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11110       return Res;
11111
11112   // None of the following transforms are legal for volatile loads.
11113   if (LI.isVolatile()) return 0;
11114   
11115   // Do really simple store-to-load forwarding and load CSE, to catch cases
11116   // where there are several consequtive memory accesses to the same location,
11117   // separated by a few arithmetic operations.
11118   BasicBlock::iterator BBI = &LI;
11119   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11120     return ReplaceInstUsesWith(LI, AvailableVal);
11121
11122   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11123     const Value *GEPI0 = GEPI->getOperand(0);
11124     // TODO: Consider a target hook for valid address spaces for this xform.
11125     if (isa<ConstantPointerNull>(GEPI0) &&
11126         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11127       // Insert a new store to null instruction before the load to indicate
11128       // that this code is not reachable.  We do this instead of inserting
11129       // an unreachable instruction directly because we cannot modify the
11130       // CFG.
11131       new StoreInst(UndefValue::get(LI.getType()),
11132                     Constant::getNullValue(Op->getType()), &LI);
11133       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11134     }
11135   } 
11136
11137   if (Constant *C = dyn_cast<Constant>(Op)) {
11138     // load null/undef -> undef
11139     // TODO: Consider a target hook for valid address spaces for this xform.
11140     if (isa<UndefValue>(C) || (C->isNullValue() && 
11141         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11142       // Insert a new store to null instruction before the load to indicate that
11143       // this code is not reachable.  We do this instead of inserting an
11144       // unreachable instruction directly because we cannot modify the CFG.
11145       new StoreInst(UndefValue::get(LI.getType()),
11146                     Constant::getNullValue(Op->getType()), &LI);
11147       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11148     }
11149
11150     // Instcombine load (constant global) into the value loaded.
11151     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11152       if (GV->isConstant() && !GV->isDeclaration())
11153         return ReplaceInstUsesWith(LI, GV->getInitializer());
11154
11155     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11156     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11157       if (CE->getOpcode() == Instruction::GetElementPtr) {
11158         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11159           if (GV->isConstant() && !GV->isDeclaration())
11160             if (Constant *V = 
11161                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11162               return ReplaceInstUsesWith(LI, V);
11163         if (CE->getOperand(0)->isNullValue()) {
11164           // Insert a new store to null instruction before the load to indicate
11165           // that this code is not reachable.  We do this instead of inserting
11166           // an unreachable instruction directly because we cannot modify the
11167           // CFG.
11168           new StoreInst(UndefValue::get(LI.getType()),
11169                         Constant::getNullValue(Op->getType()), &LI);
11170           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11171         }
11172
11173       } else if (CE->isCast()) {
11174         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11175           return Res;
11176       }
11177     }
11178   }
11179     
11180   // If this load comes from anywhere in a constant global, and if the global
11181   // is all undef or zero, we know what it loads.
11182   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11183     if (GV->isConstant() && GV->hasInitializer()) {
11184       if (GV->getInitializer()->isNullValue())
11185         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11186       else if (isa<UndefValue>(GV->getInitializer()))
11187         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11188     }
11189   }
11190
11191   if (Op->hasOneUse()) {
11192     // Change select and PHI nodes to select values instead of addresses: this
11193     // helps alias analysis out a lot, allows many others simplifications, and
11194     // exposes redundancy in the code.
11195     //
11196     // Note that we cannot do the transformation unless we know that the
11197     // introduced loads cannot trap!  Something like this is valid as long as
11198     // the condition is always false: load (select bool %C, int* null, int* %G),
11199     // but it would not be valid if we transformed it to load from null
11200     // unconditionally.
11201     //
11202     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11203       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11204       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11205           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11206         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11207                                      SI->getOperand(1)->getName()+".val"), LI);
11208         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11209                                      SI->getOperand(2)->getName()+".val"), LI);
11210         return SelectInst::Create(SI->getCondition(), V1, V2);
11211       }
11212
11213       // load (select (cond, null, P)) -> load P
11214       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11215         if (C->isNullValue()) {
11216           LI.setOperand(0, SI->getOperand(2));
11217           return &LI;
11218         }
11219
11220       // load (select (cond, P, null)) -> load P
11221       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11222         if (C->isNullValue()) {
11223           LI.setOperand(0, SI->getOperand(1));
11224           return &LI;
11225         }
11226     }
11227   }
11228   return 0;
11229 }
11230
11231 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11232 /// when possible.  This makes it generally easy to do alias analysis and/or
11233 /// SROA/mem2reg of the memory object.
11234 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11235   User *CI = cast<User>(SI.getOperand(1));
11236   Value *CastOp = CI->getOperand(0);
11237
11238   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11239   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11240   if (SrcTy == 0) return 0;
11241   
11242   const Type *SrcPTy = SrcTy->getElementType();
11243
11244   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11245     return 0;
11246   
11247   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11248   /// to its first element.  This allows us to handle things like:
11249   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11250   /// on 32-bit hosts.
11251   SmallVector<Value*, 4> NewGEPIndices;
11252   
11253   // If the source is an array, the code below will not succeed.  Check to
11254   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11255   // constants.
11256   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11257     // Index through pointer.
11258     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11259     NewGEPIndices.push_back(Zero);
11260     
11261     while (1) {
11262       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11263         if (!STy->getNumElements()) /* Struct can be empty {} */
11264           break;
11265         NewGEPIndices.push_back(Zero);
11266         SrcPTy = STy->getElementType(0);
11267       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11268         NewGEPIndices.push_back(Zero);
11269         SrcPTy = ATy->getElementType();
11270       } else {
11271         break;
11272       }
11273     }
11274     
11275     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11276   }
11277
11278   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11279     return 0;
11280   
11281   // If the pointers point into different address spaces or if they point to
11282   // values with different sizes, we can't do the transformation.
11283   if (SrcTy->getAddressSpace() != 
11284         cast<PointerType>(CI->getType())->getAddressSpace() ||
11285       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11286       IC.getTargetData().getTypeSizeInBits(DestPTy))
11287     return 0;
11288
11289   // Okay, we are casting from one integer or pointer type to another of
11290   // the same size.  Instead of casting the pointer before 
11291   // the store, cast the value to be stored.
11292   Value *NewCast;
11293   Value *SIOp0 = SI.getOperand(0);
11294   Instruction::CastOps opcode = Instruction::BitCast;
11295   const Type* CastSrcTy = SIOp0->getType();
11296   const Type* CastDstTy = SrcPTy;
11297   if (isa<PointerType>(CastDstTy)) {
11298     if (CastSrcTy->isInteger())
11299       opcode = Instruction::IntToPtr;
11300   } else if (isa<IntegerType>(CastDstTy)) {
11301     if (isa<PointerType>(SIOp0->getType()))
11302       opcode = Instruction::PtrToInt;
11303   }
11304   
11305   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11306   // emit a GEP to index into its first field.
11307   if (!NewGEPIndices.empty()) {
11308     if (Constant *C = dyn_cast<Constant>(CastOp))
11309       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11310                                               NewGEPIndices.size());
11311     else
11312       CastOp = IC.InsertNewInstBefore(
11313               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11314                                         NewGEPIndices.end()), SI);
11315   }
11316   
11317   if (Constant *C = dyn_cast<Constant>(SIOp0))
11318     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11319   else
11320     NewCast = IC.InsertNewInstBefore(
11321       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11322       SI);
11323   return new StoreInst(NewCast, CastOp);
11324 }
11325
11326 /// equivalentAddressValues - Test if A and B will obviously have the same
11327 /// value. This includes recognizing that %t0 and %t1 will have the same
11328 /// value in code like this:
11329 ///   %t0 = getelementptr @a, 0, 3
11330 ///   store i32 0, i32* %t0
11331 ///   %t1 = getelementptr @a, 0, 3
11332 ///   %t2 = load i32* %t1
11333 ///
11334 static bool equivalentAddressValues(Value *A, Value *B) {
11335   // Test if the values are trivially equivalent.
11336   if (A == B) return true;
11337   
11338   // Test if the values come form identical arithmetic instructions.
11339   if (isa<BinaryOperator>(A) ||
11340       isa<CastInst>(A) ||
11341       isa<PHINode>(A) ||
11342       isa<GetElementPtrInst>(A))
11343     if (Instruction *BI = dyn_cast<Instruction>(B))
11344       if (cast<Instruction>(A)->isIdenticalTo(BI))
11345         return true;
11346   
11347   // Otherwise they may not be equivalent.
11348   return false;
11349 }
11350
11351 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11352   Value *Val = SI.getOperand(0);
11353   Value *Ptr = SI.getOperand(1);
11354
11355   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11356     EraseInstFromFunction(SI);
11357     ++NumCombined;
11358     return 0;
11359   }
11360   
11361   // If the RHS is an alloca with a single use, zapify the store, making the
11362   // alloca dead.
11363   if (Ptr->hasOneUse() && !SI.isVolatile()) {
11364     if (isa<AllocaInst>(Ptr)) {
11365       EraseInstFromFunction(SI);
11366       ++NumCombined;
11367       return 0;
11368     }
11369     
11370     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11371       if (isa<AllocaInst>(GEP->getOperand(0)) &&
11372           GEP->getOperand(0)->hasOneUse()) {
11373         EraseInstFromFunction(SI);
11374         ++NumCombined;
11375         return 0;
11376       }
11377   }
11378
11379   // Attempt to improve the alignment.
11380   unsigned KnownAlign =
11381     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11382   if (KnownAlign >
11383       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11384                                 SI.getAlignment()))
11385     SI.setAlignment(KnownAlign);
11386
11387   // Do really simple DSE, to catch cases where there are several consequtive
11388   // stores to the same location, separated by a few arithmetic operations. This
11389   // situation often occurs with bitfield accesses.
11390   BasicBlock::iterator BBI = &SI;
11391   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11392        --ScanInsts) {
11393     --BBI;
11394     
11395     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11396       // Prev store isn't volatile, and stores to the same location?
11397       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11398                                                           SI.getOperand(1))) {
11399         ++NumDeadStore;
11400         ++BBI;
11401         EraseInstFromFunction(*PrevSI);
11402         continue;
11403       }
11404       break;
11405     }
11406     
11407     // If this is a load, we have to stop.  However, if the loaded value is from
11408     // the pointer we're loading and is producing the pointer we're storing,
11409     // then *this* store is dead (X = load P; store X -> P).
11410     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11411       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11412           !SI.isVolatile()) {
11413         EraseInstFromFunction(SI);
11414         ++NumCombined;
11415         return 0;
11416       }
11417       // Otherwise, this is a load from some other location.  Stores before it
11418       // may not be dead.
11419       break;
11420     }
11421     
11422     // Don't skip over loads or things that can modify memory.
11423     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11424       break;
11425   }
11426   
11427   
11428   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11429
11430   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11431   if (isa<ConstantPointerNull>(Ptr)) {
11432     if (!isa<UndefValue>(Val)) {
11433       SI.setOperand(0, UndefValue::get(Val->getType()));
11434       if (Instruction *U = dyn_cast<Instruction>(Val))
11435         AddToWorkList(U);  // Dropped a use.
11436       ++NumCombined;
11437     }
11438     return 0;  // Do not modify these!
11439   }
11440
11441   // store undef, Ptr -> noop
11442   if (isa<UndefValue>(Val)) {
11443     EraseInstFromFunction(SI);
11444     ++NumCombined;
11445     return 0;
11446   }
11447
11448   // If the pointer destination is a cast, see if we can fold the cast into the
11449   // source instead.
11450   if (isa<CastInst>(Ptr))
11451     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11452       return Res;
11453   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11454     if (CE->isCast())
11455       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11456         return Res;
11457
11458   
11459   // If this store is the last instruction in the basic block, and if the block
11460   // ends with an unconditional branch, try to move it to the successor block.
11461   BBI = &SI; ++BBI;
11462   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11463     if (BI->isUnconditional())
11464       if (SimplifyStoreAtEndOfBlock(SI))
11465         return 0;  // xform done!
11466   
11467   return 0;
11468 }
11469
11470 /// SimplifyStoreAtEndOfBlock - Turn things like:
11471 ///   if () { *P = v1; } else { *P = v2 }
11472 /// into a phi node with a store in the successor.
11473 ///
11474 /// Simplify things like:
11475 ///   *P = v1; if () { *P = v2; }
11476 /// into a phi node with a store in the successor.
11477 ///
11478 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11479   BasicBlock *StoreBB = SI.getParent();
11480   
11481   // Check to see if the successor block has exactly two incoming edges.  If
11482   // so, see if the other predecessor contains a store to the same location.
11483   // if so, insert a PHI node (if needed) and move the stores down.
11484   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11485   
11486   // Determine whether Dest has exactly two predecessors and, if so, compute
11487   // the other predecessor.
11488   pred_iterator PI = pred_begin(DestBB);
11489   BasicBlock *OtherBB = 0;
11490   if (*PI != StoreBB)
11491     OtherBB = *PI;
11492   ++PI;
11493   if (PI == pred_end(DestBB))
11494     return false;
11495   
11496   if (*PI != StoreBB) {
11497     if (OtherBB)
11498       return false;
11499     OtherBB = *PI;
11500   }
11501   if (++PI != pred_end(DestBB))
11502     return false;
11503
11504   // Bail out if all the relevant blocks aren't distinct (this can happen,
11505   // for example, if SI is in an infinite loop)
11506   if (StoreBB == DestBB || OtherBB == DestBB)
11507     return false;
11508
11509   // Verify that the other block ends in a branch and is not otherwise empty.
11510   BasicBlock::iterator BBI = OtherBB->getTerminator();
11511   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11512   if (!OtherBr || BBI == OtherBB->begin())
11513     return false;
11514   
11515   // If the other block ends in an unconditional branch, check for the 'if then
11516   // else' case.  there is an instruction before the branch.
11517   StoreInst *OtherStore = 0;
11518   if (OtherBr->isUnconditional()) {
11519     // If this isn't a store, or isn't a store to the same location, bail out.
11520     --BBI;
11521     OtherStore = dyn_cast<StoreInst>(BBI);
11522     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11523       return false;
11524   } else {
11525     // Otherwise, the other block ended with a conditional branch. If one of the
11526     // destinations is StoreBB, then we have the if/then case.
11527     if (OtherBr->getSuccessor(0) != StoreBB && 
11528         OtherBr->getSuccessor(1) != StoreBB)
11529       return false;
11530     
11531     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11532     // if/then triangle.  See if there is a store to the same ptr as SI that
11533     // lives in OtherBB.
11534     for (;; --BBI) {
11535       // Check to see if we find the matching store.
11536       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11537         if (OtherStore->getOperand(1) != SI.getOperand(1))
11538           return false;
11539         break;
11540       }
11541       // If we find something that may be using or overwriting the stored
11542       // value, or if we run out of instructions, we can't do the xform.
11543       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11544           BBI == OtherBB->begin())
11545         return false;
11546     }
11547     
11548     // In order to eliminate the store in OtherBr, we have to
11549     // make sure nothing reads or overwrites the stored value in
11550     // StoreBB.
11551     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11552       // FIXME: This should really be AA driven.
11553       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11554         return false;
11555     }
11556   }
11557   
11558   // Insert a PHI node now if we need it.
11559   Value *MergedVal = OtherStore->getOperand(0);
11560   if (MergedVal != SI.getOperand(0)) {
11561     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11562     PN->reserveOperandSpace(2);
11563     PN->addIncoming(SI.getOperand(0), SI.getParent());
11564     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11565     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11566   }
11567   
11568   // Advance to a place where it is safe to insert the new store and
11569   // insert it.
11570   BBI = DestBB->getFirstNonPHI();
11571   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11572                                     OtherStore->isVolatile()), *BBI);
11573   
11574   // Nuke the old stores.
11575   EraseInstFromFunction(SI);
11576   EraseInstFromFunction(*OtherStore);
11577   ++NumCombined;
11578   return true;
11579 }
11580
11581
11582 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11583   // Change br (not X), label True, label False to: br X, label False, True
11584   Value *X = 0;
11585   BasicBlock *TrueDest;
11586   BasicBlock *FalseDest;
11587   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11588       !isa<Constant>(X)) {
11589     // Swap Destinations and condition...
11590     BI.setCondition(X);
11591     BI.setSuccessor(0, FalseDest);
11592     BI.setSuccessor(1, TrueDest);
11593     return &BI;
11594   }
11595
11596   // Cannonicalize fcmp_one -> fcmp_oeq
11597   FCmpInst::Predicate FPred; Value *Y;
11598   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11599                              TrueDest, FalseDest)))
11600     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11601          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11602       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11603       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11604       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11605       NewSCC->takeName(I);
11606       // Swap Destinations and condition...
11607       BI.setCondition(NewSCC);
11608       BI.setSuccessor(0, FalseDest);
11609       BI.setSuccessor(1, TrueDest);
11610       RemoveFromWorkList(I);
11611       I->eraseFromParent();
11612       AddToWorkList(NewSCC);
11613       return &BI;
11614     }
11615
11616   // Cannonicalize icmp_ne -> icmp_eq
11617   ICmpInst::Predicate IPred;
11618   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11619                       TrueDest, FalseDest)))
11620     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11621          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11622          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11623       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11624       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11625       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11626       NewSCC->takeName(I);
11627       // Swap Destinations and condition...
11628       BI.setCondition(NewSCC);
11629       BI.setSuccessor(0, FalseDest);
11630       BI.setSuccessor(1, TrueDest);
11631       RemoveFromWorkList(I);
11632       I->eraseFromParent();;
11633       AddToWorkList(NewSCC);
11634       return &BI;
11635     }
11636
11637   return 0;
11638 }
11639
11640 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11641   Value *Cond = SI.getCondition();
11642   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11643     if (I->getOpcode() == Instruction::Add)
11644       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11645         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11646         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11647           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11648                                                 AddRHS));
11649         SI.setOperand(0, I->getOperand(0));
11650         AddToWorkList(I);
11651         return &SI;
11652       }
11653   }
11654   return 0;
11655 }
11656
11657 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11658   Value *Agg = EV.getAggregateOperand();
11659
11660   if (!EV.hasIndices())
11661     return ReplaceInstUsesWith(EV, Agg);
11662
11663   if (Constant *C = dyn_cast<Constant>(Agg)) {
11664     if (isa<UndefValue>(C))
11665       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11666       
11667     if (isa<ConstantAggregateZero>(C))
11668       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11669
11670     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11671       // Extract the element indexed by the first index out of the constant
11672       Value *V = C->getOperand(*EV.idx_begin());
11673       if (EV.getNumIndices() > 1)
11674         // Extract the remaining indices out of the constant indexed by the
11675         // first index
11676         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11677       else
11678         return ReplaceInstUsesWith(EV, V);
11679     }
11680     return 0; // Can't handle other constants
11681   } 
11682   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11683     // We're extracting from an insertvalue instruction, compare the indices
11684     const unsigned *exti, *exte, *insi, *inse;
11685     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11686          exte = EV.idx_end(), inse = IV->idx_end();
11687          exti != exte && insi != inse;
11688          ++exti, ++insi) {
11689       if (*insi != *exti)
11690         // The insert and extract both reference distinctly different elements.
11691         // This means the extract is not influenced by the insert, and we can
11692         // replace the aggregate operand of the extract with the aggregate
11693         // operand of the insert. i.e., replace
11694         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11695         // %E = extractvalue { i32, { i32 } } %I, 0
11696         // with
11697         // %E = extractvalue { i32, { i32 } } %A, 0
11698         return ExtractValueInst::Create(IV->getAggregateOperand(),
11699                                         EV.idx_begin(), EV.idx_end());
11700     }
11701     if (exti == exte && insi == inse)
11702       // Both iterators are at the end: Index lists are identical. Replace
11703       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11704       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11705       // with "i32 42"
11706       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11707     if (exti == exte) {
11708       // The extract list is a prefix of the insert list. i.e. replace
11709       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11710       // %E = extractvalue { i32, { i32 } } %I, 1
11711       // with
11712       // %X = extractvalue { i32, { i32 } } %A, 1
11713       // %E = insertvalue { i32 } %X, i32 42, 0
11714       // by switching the order of the insert and extract (though the
11715       // insertvalue should be left in, since it may have other uses).
11716       Value *NewEV = InsertNewInstBefore(
11717         ExtractValueInst::Create(IV->getAggregateOperand(),
11718                                  EV.idx_begin(), EV.idx_end()),
11719         EV);
11720       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11721                                      insi, inse);
11722     }
11723     if (insi == inse)
11724       // The insert list is a prefix of the extract list
11725       // We can simply remove the common indices from the extract and make it
11726       // operate on the inserted value instead of the insertvalue result.
11727       // i.e., replace
11728       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11729       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11730       // with
11731       // %E extractvalue { i32 } { i32 42 }, 0
11732       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11733                                       exti, exte);
11734   }
11735   // Can't simplify extracts from other values. Note that nested extracts are
11736   // already simplified implicitely by the above (extract ( extract (insert) )
11737   // will be translated into extract ( insert ( extract ) ) first and then just
11738   // the value inserted, if appropriate).
11739   return 0;
11740 }
11741
11742 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11743 /// is to leave as a vector operation.
11744 static bool CheapToScalarize(Value *V, bool isConstant) {
11745   if (isa<ConstantAggregateZero>(V)) 
11746     return true;
11747   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11748     if (isConstant) return true;
11749     // If all elts are the same, we can extract.
11750     Constant *Op0 = C->getOperand(0);
11751     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11752       if (C->getOperand(i) != Op0)
11753         return false;
11754     return true;
11755   }
11756   Instruction *I = dyn_cast<Instruction>(V);
11757   if (!I) return false;
11758   
11759   // Insert element gets simplified to the inserted element or is deleted if
11760   // this is constant idx extract element and its a constant idx insertelt.
11761   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11762       isa<ConstantInt>(I->getOperand(2)))
11763     return true;
11764   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11765     return true;
11766   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11767     if (BO->hasOneUse() &&
11768         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11769          CheapToScalarize(BO->getOperand(1), isConstant)))
11770       return true;
11771   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11772     if (CI->hasOneUse() &&
11773         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11774          CheapToScalarize(CI->getOperand(1), isConstant)))
11775       return true;
11776   
11777   return false;
11778 }
11779
11780 /// Read and decode a shufflevector mask.
11781 ///
11782 /// It turns undef elements into values that are larger than the number of
11783 /// elements in the input.
11784 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11785   unsigned NElts = SVI->getType()->getNumElements();
11786   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11787     return std::vector<unsigned>(NElts, 0);
11788   if (isa<UndefValue>(SVI->getOperand(2)))
11789     return std::vector<unsigned>(NElts, 2*NElts);
11790
11791   std::vector<unsigned> Result;
11792   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11793   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11794     if (isa<UndefValue>(*i))
11795       Result.push_back(NElts*2);  // undef -> 8
11796     else
11797       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11798   return Result;
11799 }
11800
11801 /// FindScalarElement - Given a vector and an element number, see if the scalar
11802 /// value is already around as a register, for example if it were inserted then
11803 /// extracted from the vector.
11804 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11805   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11806   const VectorType *PTy = cast<VectorType>(V->getType());
11807   unsigned Width = PTy->getNumElements();
11808   if (EltNo >= Width)  // Out of range access.
11809     return UndefValue::get(PTy->getElementType());
11810   
11811   if (isa<UndefValue>(V))
11812     return UndefValue::get(PTy->getElementType());
11813   else if (isa<ConstantAggregateZero>(V))
11814     return Constant::getNullValue(PTy->getElementType());
11815   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11816     return CP->getOperand(EltNo);
11817   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11818     // If this is an insert to a variable element, we don't know what it is.
11819     if (!isa<ConstantInt>(III->getOperand(2))) 
11820       return 0;
11821     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11822     
11823     // If this is an insert to the element we are looking for, return the
11824     // inserted value.
11825     if (EltNo == IIElt) 
11826       return III->getOperand(1);
11827     
11828     // Otherwise, the insertelement doesn't modify the value, recurse on its
11829     // vector input.
11830     return FindScalarElement(III->getOperand(0), EltNo);
11831   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11832     unsigned LHSWidth =
11833       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11834     unsigned InEl = getShuffleMask(SVI)[EltNo];
11835     if (InEl < LHSWidth)
11836       return FindScalarElement(SVI->getOperand(0), InEl);
11837     else if (InEl < LHSWidth*2)
11838       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11839     else
11840       return UndefValue::get(PTy->getElementType());
11841   }
11842   
11843   // Otherwise, we don't know.
11844   return 0;
11845 }
11846
11847 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11848   // If vector val is undef, replace extract with scalar undef.
11849   if (isa<UndefValue>(EI.getOperand(0)))
11850     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11851
11852   // If vector val is constant 0, replace extract with scalar 0.
11853   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11854     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11855   
11856   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11857     // If vector val is constant with all elements the same, replace EI with
11858     // that element. When the elements are not identical, we cannot replace yet
11859     // (we do that below, but only when the index is constant).
11860     Constant *op0 = C->getOperand(0);
11861     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11862       if (C->getOperand(i) != op0) {
11863         op0 = 0; 
11864         break;
11865       }
11866     if (op0)
11867       return ReplaceInstUsesWith(EI, op0);
11868   }
11869   
11870   // If extracting a specified index from the vector, see if we can recursively
11871   // find a previously computed scalar that was inserted into the vector.
11872   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11873     unsigned IndexVal = IdxC->getZExtValue();
11874     unsigned VectorWidth = 
11875       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11876       
11877     // If this is extracting an invalid index, turn this into undef, to avoid
11878     // crashing the code below.
11879     if (IndexVal >= VectorWidth)
11880       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11881     
11882     // This instruction only demands the single element from the input vector.
11883     // If the input vector has a single use, simplify it based on this use
11884     // property.
11885     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11886       APInt UndefElts(VectorWidth, 0);
11887       APInt DemandedMask(VectorWidth, 1 << IndexVal);
11888       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11889                                                 DemandedMask, UndefElts)) {
11890         EI.setOperand(0, V);
11891         return &EI;
11892       }
11893     }
11894     
11895     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11896       return ReplaceInstUsesWith(EI, Elt);
11897     
11898     // If the this extractelement is directly using a bitcast from a vector of
11899     // the same number of elements, see if we can find the source element from
11900     // it.  In this case, we will end up needing to bitcast the scalars.
11901     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11902       if (const VectorType *VT = 
11903               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11904         if (VT->getNumElements() == VectorWidth)
11905           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11906             return new BitCastInst(Elt, EI.getType());
11907     }
11908   }
11909   
11910   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11911     if (I->hasOneUse()) {
11912       // Push extractelement into predecessor operation if legal and
11913       // profitable to do so
11914       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11915         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11916         if (CheapToScalarize(BO, isConstantElt)) {
11917           ExtractElementInst *newEI0 = 
11918             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11919                                    EI.getName()+".lhs");
11920           ExtractElementInst *newEI1 =
11921             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11922                                    EI.getName()+".rhs");
11923           InsertNewInstBefore(newEI0, EI);
11924           InsertNewInstBefore(newEI1, EI);
11925           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11926         }
11927       } else if (isa<LoadInst>(I)) {
11928         unsigned AS = 
11929           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11930         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11931                                          PointerType::get(EI.getType(), AS),EI);
11932         GetElementPtrInst *GEP =
11933           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11934         InsertNewInstBefore(GEP, EI);
11935         return new LoadInst(GEP);
11936       }
11937     }
11938     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11939       // Extracting the inserted element?
11940       if (IE->getOperand(2) == EI.getOperand(1))
11941         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11942       // If the inserted and extracted elements are constants, they must not
11943       // be the same value, extract from the pre-inserted value instead.
11944       if (isa<Constant>(IE->getOperand(2)) &&
11945           isa<Constant>(EI.getOperand(1))) {
11946         AddUsesToWorkList(EI);
11947         EI.setOperand(0, IE->getOperand(0));
11948         return &EI;
11949       }
11950     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11951       // If this is extracting an element from a shufflevector, figure out where
11952       // it came from and extract from the appropriate input element instead.
11953       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11954         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11955         Value *Src;
11956         unsigned LHSWidth =
11957           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11958
11959         if (SrcIdx < LHSWidth)
11960           Src = SVI->getOperand(0);
11961         else if (SrcIdx < LHSWidth*2) {
11962           SrcIdx -= LHSWidth;
11963           Src = SVI->getOperand(1);
11964         } else {
11965           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11966         }
11967         return new ExtractElementInst(Src, SrcIdx);
11968       }
11969     }
11970   }
11971   return 0;
11972 }
11973
11974 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11975 /// elements from either LHS or RHS, return the shuffle mask and true. 
11976 /// Otherwise, return false.
11977 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11978                                          std::vector<Constant*> &Mask) {
11979   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11980          "Invalid CollectSingleShuffleElements");
11981   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11982
11983   if (isa<UndefValue>(V)) {
11984     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11985     return true;
11986   } else if (V == LHS) {
11987     for (unsigned i = 0; i != NumElts; ++i)
11988       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11989     return true;
11990   } else if (V == RHS) {
11991     for (unsigned i = 0; i != NumElts; ++i)
11992       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11993     return true;
11994   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11995     // If this is an insert of an extract from some other vector, include it.
11996     Value *VecOp    = IEI->getOperand(0);
11997     Value *ScalarOp = IEI->getOperand(1);
11998     Value *IdxOp    = IEI->getOperand(2);
11999     
12000     if (!isa<ConstantInt>(IdxOp))
12001       return false;
12002     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12003     
12004     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12005       // Okay, we can handle this if the vector we are insertinting into is
12006       // transitively ok.
12007       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12008         // If so, update the mask to reflect the inserted undef.
12009         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12010         return true;
12011       }      
12012     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12013       if (isa<ConstantInt>(EI->getOperand(1)) &&
12014           EI->getOperand(0)->getType() == V->getType()) {
12015         unsigned ExtractedIdx =
12016           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12017         
12018         // This must be extracting from either LHS or RHS.
12019         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12020           // Okay, we can handle this if the vector we are insertinting into is
12021           // transitively ok.
12022           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12023             // If so, update the mask to reflect the inserted value.
12024             if (EI->getOperand(0) == LHS) {
12025               Mask[InsertedIdx % NumElts] = 
12026                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12027             } else {
12028               assert(EI->getOperand(0) == RHS);
12029               Mask[InsertedIdx % NumElts] = 
12030                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12031               
12032             }
12033             return true;
12034           }
12035         }
12036       }
12037     }
12038   }
12039   // TODO: Handle shufflevector here!
12040   
12041   return false;
12042 }
12043
12044 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12045 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12046 /// that computes V and the LHS value of the shuffle.
12047 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12048                                      Value *&RHS) {
12049   assert(isa<VectorType>(V->getType()) && 
12050          (RHS == 0 || V->getType() == RHS->getType()) &&
12051          "Invalid shuffle!");
12052   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12053
12054   if (isa<UndefValue>(V)) {
12055     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12056     return V;
12057   } else if (isa<ConstantAggregateZero>(V)) {
12058     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12059     return V;
12060   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12061     // If this is an insert of an extract from some other vector, include it.
12062     Value *VecOp    = IEI->getOperand(0);
12063     Value *ScalarOp = IEI->getOperand(1);
12064     Value *IdxOp    = IEI->getOperand(2);
12065     
12066     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12067       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12068           EI->getOperand(0)->getType() == V->getType()) {
12069         unsigned ExtractedIdx =
12070           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12071         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12072         
12073         // Either the extracted from or inserted into vector must be RHSVec,
12074         // otherwise we'd end up with a shuffle of three inputs.
12075         if (EI->getOperand(0) == RHS || RHS == 0) {
12076           RHS = EI->getOperand(0);
12077           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12078           Mask[InsertedIdx % NumElts] = 
12079             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12080           return V;
12081         }
12082         
12083         if (VecOp == RHS) {
12084           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12085           // Everything but the extracted element is replaced with the RHS.
12086           for (unsigned i = 0; i != NumElts; ++i) {
12087             if (i != InsertedIdx)
12088               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12089           }
12090           return V;
12091         }
12092         
12093         // If this insertelement is a chain that comes from exactly these two
12094         // vectors, return the vector and the effective shuffle.
12095         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12096           return EI->getOperand(0);
12097         
12098       }
12099     }
12100   }
12101   // TODO: Handle shufflevector here!
12102   
12103   // Otherwise, can't do anything fancy.  Return an identity vector.
12104   for (unsigned i = 0; i != NumElts; ++i)
12105     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12106   return V;
12107 }
12108
12109 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12110   Value *VecOp    = IE.getOperand(0);
12111   Value *ScalarOp = IE.getOperand(1);
12112   Value *IdxOp    = IE.getOperand(2);
12113   
12114   // Inserting an undef or into an undefined place, remove this.
12115   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12116     ReplaceInstUsesWith(IE, VecOp);
12117   
12118   // If the inserted element was extracted from some other vector, and if the 
12119   // indexes are constant, try to turn this into a shufflevector operation.
12120   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12121     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12122         EI->getOperand(0)->getType() == IE.getType()) {
12123       unsigned NumVectorElts = IE.getType()->getNumElements();
12124       unsigned ExtractedIdx =
12125         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12126       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12127       
12128       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12129         return ReplaceInstUsesWith(IE, VecOp);
12130       
12131       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12132         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12133       
12134       // If we are extracting a value from a vector, then inserting it right
12135       // back into the same place, just use the input vector.
12136       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12137         return ReplaceInstUsesWith(IE, VecOp);      
12138       
12139       // We could theoretically do this for ANY input.  However, doing so could
12140       // turn chains of insertelement instructions into a chain of shufflevector
12141       // instructions, and right now we do not merge shufflevectors.  As such,
12142       // only do this in a situation where it is clear that there is benefit.
12143       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12144         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12145         // the values of VecOp, except then one read from EIOp0.
12146         // Build a new shuffle mask.
12147         std::vector<Constant*> Mask;
12148         if (isa<UndefValue>(VecOp))
12149           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12150         else {
12151           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12152           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12153                                                        NumVectorElts));
12154         } 
12155         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12156         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12157                                      ConstantVector::get(Mask));
12158       }
12159       
12160       // If this insertelement isn't used by some other insertelement, turn it
12161       // (and any insertelements it points to), into one big shuffle.
12162       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12163         std::vector<Constant*> Mask;
12164         Value *RHS = 0;
12165         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12166         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12167         // We now have a shuffle of LHS, RHS, Mask.
12168         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12169       }
12170     }
12171   }
12172
12173   return 0;
12174 }
12175
12176
12177 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12178   Value *LHS = SVI.getOperand(0);
12179   Value *RHS = SVI.getOperand(1);
12180   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12181
12182   bool MadeChange = false;
12183
12184   // Undefined shuffle mask -> undefined value.
12185   if (isa<UndefValue>(SVI.getOperand(2)))
12186     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12187
12188   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12189
12190   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12191     return 0;
12192
12193   APInt UndefElts(VWidth, 0);
12194   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12195   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12196     LHS = SVI.getOperand(0);
12197     RHS = SVI.getOperand(1);
12198     MadeChange = true;
12199   }
12200   
12201   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12202   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12203   if (LHS == RHS || isa<UndefValue>(LHS)) {
12204     if (isa<UndefValue>(LHS) && LHS == RHS) {
12205       // shuffle(undef,undef,mask) -> undef.
12206       return ReplaceInstUsesWith(SVI, LHS);
12207     }
12208     
12209     // Remap any references to RHS to use LHS.
12210     std::vector<Constant*> Elts;
12211     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12212       if (Mask[i] >= 2*e)
12213         Elts.push_back(UndefValue::get(Type::Int32Ty));
12214       else {
12215         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12216             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12217           Mask[i] = 2*e;     // Turn into undef.
12218           Elts.push_back(UndefValue::get(Type::Int32Ty));
12219         } else {
12220           Mask[i] = Mask[i] % e;  // Force to LHS.
12221           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12222         }
12223       }
12224     }
12225     SVI.setOperand(0, SVI.getOperand(1));
12226     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12227     SVI.setOperand(2, ConstantVector::get(Elts));
12228     LHS = SVI.getOperand(0);
12229     RHS = SVI.getOperand(1);
12230     MadeChange = true;
12231   }
12232   
12233   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12234   bool isLHSID = true, isRHSID = true;
12235     
12236   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12237     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12238     // Is this an identity shuffle of the LHS value?
12239     isLHSID &= (Mask[i] == i);
12240       
12241     // Is this an identity shuffle of the RHS value?
12242     isRHSID &= (Mask[i]-e == i);
12243   }
12244
12245   // Eliminate identity shuffles.
12246   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12247   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12248   
12249   // If the LHS is a shufflevector itself, see if we can combine it with this
12250   // one without producing an unusual shuffle.  Here we are really conservative:
12251   // we are absolutely afraid of producing a shuffle mask not in the input
12252   // program, because the code gen may not be smart enough to turn a merged
12253   // shuffle into two specific shuffles: it may produce worse code.  As such,
12254   // we only merge two shuffles if the result is one of the two input shuffle
12255   // masks.  In this case, merging the shuffles just removes one instruction,
12256   // which we know is safe.  This is good for things like turning:
12257   // (splat(splat)) -> splat.
12258   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12259     if (isa<UndefValue>(RHS)) {
12260       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12261
12262       std::vector<unsigned> NewMask;
12263       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12264         if (Mask[i] >= 2*e)
12265           NewMask.push_back(2*e);
12266         else
12267           NewMask.push_back(LHSMask[Mask[i]]);
12268       
12269       // If the result mask is equal to the src shuffle or this shuffle mask, do
12270       // the replacement.
12271       if (NewMask == LHSMask || NewMask == Mask) {
12272         unsigned LHSInNElts =
12273           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12274         std::vector<Constant*> Elts;
12275         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12276           if (NewMask[i] >= LHSInNElts*2) {
12277             Elts.push_back(UndefValue::get(Type::Int32Ty));
12278           } else {
12279             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12280           }
12281         }
12282         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12283                                      LHSSVI->getOperand(1),
12284                                      ConstantVector::get(Elts));
12285       }
12286     }
12287   }
12288
12289   return MadeChange ? &SVI : 0;
12290 }
12291
12292
12293
12294
12295 /// TryToSinkInstruction - Try to move the specified instruction from its
12296 /// current block into the beginning of DestBlock, which can only happen if it's
12297 /// safe to move the instruction past all of the instructions between it and the
12298 /// end of its block.
12299 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12300   assert(I->hasOneUse() && "Invariants didn't hold!");
12301
12302   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12303   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12304     return false;
12305
12306   // Do not sink alloca instructions out of the entry block.
12307   if (isa<AllocaInst>(I) && I->getParent() ==
12308         &DestBlock->getParent()->getEntryBlock())
12309     return false;
12310
12311   // We can only sink load instructions if there is nothing between the load and
12312   // the end of block that could change the value.
12313   if (I->mayReadFromMemory()) {
12314     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12315          Scan != E; ++Scan)
12316       if (Scan->mayWriteToMemory())
12317         return false;
12318   }
12319
12320   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12321
12322   I->moveBefore(InsertPos);
12323   ++NumSunkInst;
12324   return true;
12325 }
12326
12327
12328 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12329 /// all reachable code to the worklist.
12330 ///
12331 /// This has a couple of tricks to make the code faster and more powerful.  In
12332 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12333 /// them to the worklist (this significantly speeds up instcombine on code where
12334 /// many instructions are dead or constant).  Additionally, if we find a branch
12335 /// whose condition is a known constant, we only visit the reachable successors.
12336 ///
12337 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12338                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12339                                        InstCombiner &IC,
12340                                        const TargetData *TD) {
12341   SmallVector<BasicBlock*, 256> Worklist;
12342   Worklist.push_back(BB);
12343
12344   while (!Worklist.empty()) {
12345     BB = Worklist.back();
12346     Worklist.pop_back();
12347     
12348     // We have now visited this block!  If we've already been here, ignore it.
12349     if (!Visited.insert(BB)) continue;
12350
12351     DbgInfoIntrinsic *DBI_Prev = NULL;
12352     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12353       Instruction *Inst = BBI++;
12354       
12355       // DCE instruction if trivially dead.
12356       if (isInstructionTriviallyDead(Inst)) {
12357         ++NumDeadInst;
12358         DOUT << "IC: DCE: " << *Inst;
12359         Inst->eraseFromParent();
12360         continue;
12361       }
12362       
12363       // ConstantProp instruction if trivially constant.
12364       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12365         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12366         Inst->replaceAllUsesWith(C);
12367         ++NumConstProp;
12368         Inst->eraseFromParent();
12369         continue;
12370       }
12371      
12372       // If there are two consecutive llvm.dbg.stoppoint calls then
12373       // it is likely that the optimizer deleted code in between these
12374       // two intrinsics. 
12375       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12376       if (DBI_Next) {
12377         if (DBI_Prev
12378             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12379             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12380           IC.RemoveFromWorkList(DBI_Prev);
12381           DBI_Prev->eraseFromParent();
12382         }
12383         DBI_Prev = DBI_Next;
12384       }
12385
12386       IC.AddToWorkList(Inst);
12387     }
12388
12389     // Recursively visit successors.  If this is a branch or switch on a
12390     // constant, only visit the reachable successor.
12391     TerminatorInst *TI = BB->getTerminator();
12392     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12393       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12394         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12395         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12396         Worklist.push_back(ReachableBB);
12397         continue;
12398       }
12399     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12400       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12401         // See if this is an explicit destination.
12402         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12403           if (SI->getCaseValue(i) == Cond) {
12404             BasicBlock *ReachableBB = SI->getSuccessor(i);
12405             Worklist.push_back(ReachableBB);
12406             continue;
12407           }
12408         
12409         // Otherwise it is the default destination.
12410         Worklist.push_back(SI->getSuccessor(0));
12411         continue;
12412       }
12413     }
12414     
12415     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12416       Worklist.push_back(TI->getSuccessor(i));
12417   }
12418 }
12419
12420 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12421   bool Changed = false;
12422   TD = &getAnalysis<TargetData>();
12423   
12424   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12425              << F.getNameStr() << "\n");
12426
12427   {
12428     // Do a depth-first traversal of the function, populate the worklist with
12429     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12430     // track of which blocks we visit.
12431     SmallPtrSet<BasicBlock*, 64> Visited;
12432     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12433
12434     // Do a quick scan over the function.  If we find any blocks that are
12435     // unreachable, remove any instructions inside of them.  This prevents
12436     // the instcombine code from having to deal with some bad special cases.
12437     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12438       if (!Visited.count(BB)) {
12439         Instruction *Term = BB->getTerminator();
12440         while (Term != BB->begin()) {   // Remove instrs bottom-up
12441           BasicBlock::iterator I = Term; --I;
12442
12443           DOUT << "IC: DCE: " << *I;
12444           ++NumDeadInst;
12445
12446           if (!I->use_empty())
12447             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12448           I->eraseFromParent();
12449           Changed = true;
12450         }
12451       }
12452   }
12453
12454   while (!Worklist.empty()) {
12455     Instruction *I = RemoveOneFromWorkList();
12456     if (I == 0) continue;  // skip null values.
12457
12458     // Check to see if we can DCE the instruction.
12459     if (isInstructionTriviallyDead(I)) {
12460       // Add operands to the worklist.
12461       if (I->getNumOperands() < 4)
12462         AddUsesToWorkList(*I);
12463       ++NumDeadInst;
12464
12465       DOUT << "IC: DCE: " << *I;
12466
12467       I->eraseFromParent();
12468       RemoveFromWorkList(I);
12469       Changed = true;
12470       continue;
12471     }
12472
12473     // Instruction isn't dead, see if we can constant propagate it.
12474     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12475       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12476
12477       // Add operands to the worklist.
12478       AddUsesToWorkList(*I);
12479       ReplaceInstUsesWith(*I, C);
12480
12481       ++NumConstProp;
12482       I->eraseFromParent();
12483       RemoveFromWorkList(I);
12484       Changed = true;
12485       continue;
12486     }
12487
12488     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12489       // See if we can constant fold its operands.
12490       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12491         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12492           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12493             if (NewC != CE) {
12494               i->set(NewC);
12495               Changed = true;
12496             }
12497     }
12498
12499     // See if we can trivially sink this instruction to a successor basic block.
12500     if (I->hasOneUse()) {
12501       BasicBlock *BB = I->getParent();
12502       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12503       if (UserParent != BB) {
12504         bool UserIsSuccessor = false;
12505         // See if the user is one of our successors.
12506         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12507           if (*SI == UserParent) {
12508             UserIsSuccessor = true;
12509             break;
12510           }
12511
12512         // If the user is one of our immediate successors, and if that successor
12513         // only has us as a predecessors (we'd have to split the critical edge
12514         // otherwise), we can keep going.
12515         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12516             next(pred_begin(UserParent)) == pred_end(UserParent))
12517           // Okay, the CFG is simple enough, try to sink this instruction.
12518           Changed |= TryToSinkInstruction(I, UserParent);
12519       }
12520     }
12521
12522     // Now that we have an instruction, try combining it to simplify it...
12523 #ifndef NDEBUG
12524     std::string OrigI;
12525 #endif
12526     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12527     if (Instruction *Result = visit(*I)) {
12528       ++NumCombined;
12529       // Should we replace the old instruction with a new one?
12530       if (Result != I) {
12531         DOUT << "IC: Old = " << *I
12532              << "    New = " << *Result;
12533
12534         // Everything uses the new instruction now.
12535         I->replaceAllUsesWith(Result);
12536
12537         // Push the new instruction and any users onto the worklist.
12538         AddToWorkList(Result);
12539         AddUsersToWorkList(*Result);
12540
12541         // Move the name to the new instruction first.
12542         Result->takeName(I);
12543
12544         // Insert the new instruction into the basic block...
12545         BasicBlock *InstParent = I->getParent();
12546         BasicBlock::iterator InsertPos = I;
12547
12548         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12549           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12550             ++InsertPos;
12551
12552         InstParent->getInstList().insert(InsertPos, Result);
12553
12554         // Make sure that we reprocess all operands now that we reduced their
12555         // use counts.
12556         AddUsesToWorkList(*I);
12557
12558         // Instructions can end up on the worklist more than once.  Make sure
12559         // we do not process an instruction that has been deleted.
12560         RemoveFromWorkList(I);
12561
12562         // Erase the old instruction.
12563         InstParent->getInstList().erase(I);
12564       } else {
12565 #ifndef NDEBUG
12566         DOUT << "IC: Mod = " << OrigI
12567              << "    New = " << *I;
12568 #endif
12569
12570         // If the instruction was modified, it's possible that it is now dead.
12571         // if so, remove it.
12572         if (isInstructionTriviallyDead(I)) {
12573           // Make sure we process all operands now that we are reducing their
12574           // use counts.
12575           AddUsesToWorkList(*I);
12576
12577           // Instructions may end up in the worklist more than once.  Erase all
12578           // occurrences of this instruction.
12579           RemoveFromWorkList(I);
12580           I->eraseFromParent();
12581         } else {
12582           AddToWorkList(I);
12583           AddUsersToWorkList(*I);
12584         }
12585       }
12586       Changed = true;
12587     }
12588   }
12589
12590   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12591     
12592   // Do an explicit clear, this shrinks the map if needed.
12593   WorklistMap.clear();
12594   return Changed;
12595 }
12596
12597
12598 bool InstCombiner::runOnFunction(Function &F) {
12599   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12600   
12601   bool EverMadeChange = false;
12602
12603   // Iterate while there is work to do.
12604   unsigned Iteration = 0;
12605   while (DoOneIteration(F, Iteration++))
12606     EverMadeChange = true;
12607   return EverMadeChange;
12608 }
12609
12610 FunctionPass *llvm::createInstructionCombiningPass() {
12611   return new InstCombiner();
12612 }