Add a couple of missed optimizations on integer vectors. Multiply and divide
[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 *visitOr (BinaryOperator &I);
187     Instruction *visitXor(BinaryOperator &I);
188     Instruction *visitShl(BinaryOperator &I);
189     Instruction *visitAShr(BinaryOperator &I);
190     Instruction *visitLShr(BinaryOperator &I);
191     Instruction *commonShiftTransforms(BinaryOperator &I);
192     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
193                                       Constant *RHSC);
194     Instruction *visitFCmpInst(FCmpInst &I);
195     Instruction *visitICmpInst(ICmpInst &I);
196     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
197     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
198                                                 Instruction *LHS,
199                                                 ConstantInt *RHS);
200     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
201                                 ConstantInt *DivRHS);
202
203     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
204                              ICmpInst::Predicate Cond, Instruction &I);
205     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
206                                      BinaryOperator &I);
207     Instruction *commonCastTransforms(CastInst &CI);
208     Instruction *commonIntCastTransforms(CastInst &CI);
209     Instruction *commonPointerCastTransforms(CastInst &CI);
210     Instruction *visitTrunc(TruncInst &CI);
211     Instruction *visitZExt(ZExtInst &CI);
212     Instruction *visitSExt(SExtInst &CI);
213     Instruction *visitFPTrunc(FPTruncInst &CI);
214     Instruction *visitFPExt(CastInst &CI);
215     Instruction *visitFPToUI(FPToUIInst &FI);
216     Instruction *visitFPToSI(FPToSIInst &FI);
217     Instruction *visitUIToFP(CastInst &CI);
218     Instruction *visitSIToFP(CastInst &CI);
219     Instruction *visitPtrToInt(CastInst &CI);
220     Instruction *visitIntToPtr(IntToPtrInst &CI);
221     Instruction *visitBitCast(BitCastInst &CI);
222     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
223                                 Instruction *FI);
224     Instruction *visitSelectInst(SelectInst &SI);
225     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
226     Instruction *visitCallInst(CallInst &CI);
227     Instruction *visitInvokeInst(InvokeInst &II);
228     Instruction *visitPHINode(PHINode &PN);
229     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
230     Instruction *visitAllocationInst(AllocationInst &AI);
231     Instruction *visitFreeInst(FreeInst &FI);
232     Instruction *visitLoadInst(LoadInst &LI);
233     Instruction *visitStoreInst(StoreInst &SI);
234     Instruction *visitBranchInst(BranchInst &BI);
235     Instruction *visitSwitchInst(SwitchInst &SI);
236     Instruction *visitInsertElementInst(InsertElementInst &IE);
237     Instruction *visitExtractElementInst(ExtractElementInst &EI);
238     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
239     Instruction *visitExtractValueInst(ExtractValueInst &EV);
240
241     // visitInstruction - Specify what to return for unhandled instructions...
242     Instruction *visitInstruction(Instruction &I) { return 0; }
243
244   private:
245     Instruction *visitCallSite(CallSite CS);
246     bool transformConstExprCastCall(CallSite CS);
247     Instruction *transformCallThroughTrampoline(CallSite CS);
248     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
249                                    bool DoXform = true);
250     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
251
252   public:
253     // InsertNewInstBefore - insert an instruction New before instruction Old
254     // in the program.  Add the new instruction to the worklist.
255     //
256     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
257       assert(New && New->getParent() == 0 &&
258              "New instruction already inserted into a basic block!");
259       BasicBlock *BB = Old.getParent();
260       BB->getInstList().insert(&Old, New);  // Insert inst
261       AddToWorkList(New);
262       return New;
263     }
264
265     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
266     /// This also adds the cast to the worklist.  Finally, this returns the
267     /// cast.
268     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
269                             Instruction &Pos) {
270       if (V->getType() == Ty) return V;
271
272       if (Constant *CV = dyn_cast<Constant>(V))
273         return ConstantExpr::getCast(opc, CV, Ty);
274       
275       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
276       AddToWorkList(C);
277       return C;
278     }
279         
280     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
281       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
282     }
283
284
285     // ReplaceInstUsesWith - This method is to be used when an instruction is
286     // found to be dead, replacable with another preexisting expression.  Here
287     // we add all uses of I to the worklist, replace all uses of I with the new
288     // value, then return I, so that the inst combiner will know that I was
289     // modified.
290     //
291     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
292       AddUsersToWorkList(I);         // Add all modified instrs to worklist
293       if (&I != V) {
294         I.replaceAllUsesWith(V);
295         return &I;
296       } else {
297         // If we are replacing the instruction with itself, this must be in a
298         // segment of unreachable code, so just clobber the instruction.
299         I.replaceAllUsesWith(UndefValue::get(I.getType()));
300         return &I;
301       }
302     }
303
304     // UpdateValueUsesWith - This method is to be used when an value is
305     // found to be replacable with another preexisting expression or was
306     // updated.  Here we add all uses of I to the worklist, replace all uses of
307     // I with the new value (unless the instruction was just updated), then
308     // return true, so that the inst combiner will know that I was modified.
309     //
310     bool UpdateValueUsesWith(Value *Old, Value *New) {
311       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
312       if (Old != New)
313         Old->replaceAllUsesWith(New);
314       if (Instruction *I = dyn_cast<Instruction>(Old))
315         AddToWorkList(I);
316       if (Instruction *I = dyn_cast<Instruction>(New))
317         AddToWorkList(I);
318       return true;
319     }
320     
321     // EraseInstFromFunction - When dealing with an instruction that has side
322     // effects or produces a void value, we can't rely on DCE to delete the
323     // instruction.  Instead, visit methods should return the value returned by
324     // this function.
325     Instruction *EraseInstFromFunction(Instruction &I) {
326       assert(I.use_empty() && "Cannot erase instruction that is used!");
327       AddUsesToWorkList(I);
328       RemoveFromWorkList(&I);
329       I.eraseFromParent();
330       return 0;  // Don't do anything with FI
331     }
332         
333     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
334                            APInt &KnownOne, unsigned Depth = 0) const {
335       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
336     }
337     
338     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
339                            unsigned Depth = 0) const {
340       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
341     }
342     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
343       return llvm::ComputeNumSignBits(Op, TD, Depth);
344     }
345
346   private:
347     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
348     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
349     /// casts that are known to not do anything...
350     ///
351     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
352                                    Value *V, const Type *DestTy,
353                                    Instruction *InsertBefore);
354
355     /// SimplifyCommutative - This performs a few simplifications for 
356     /// commutative operators.
357     bool SimplifyCommutative(BinaryOperator &I);
358
359     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
360     /// most-complex to least-complex order.
361     bool SimplifyCompare(CmpInst &I);
362
363     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
364     /// on the demanded bits.
365     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
366                               APInt& KnownZero, APInt& KnownOne,
367                               unsigned Depth = 0);
368
369     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
370                                       uint64_t &UndefElts, unsigned Depth = 0);
371       
372     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373     // PHI node as operand #0, see if we can fold the instruction into the PHI
374     // (which is only possible if all operands to the PHI are constants).
375     Instruction *FoldOpIntoPhi(Instruction &I);
376
377     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378     // operator and they all are only used by the PHI, PHI together their
379     // inputs, and do the operation once, to the result of the PHI.
380     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
381     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
382     
383     
384     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
385                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
386     
387     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
388                               bool isSub, Instruction &I);
389     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
390                                  bool isSigned, bool Inside, Instruction &IB);
391     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
392     Instruction *MatchBSwap(BinaryOperator &I);
393     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
394     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
395     Instruction *SimplifyMemSet(MemSetInst *MI);
396
397
398     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
399
400     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
401                                     unsigned CastOpc,
402                                     int &NumCastsRemoved);
403     unsigned GetOrEnforceKnownAlignment(Value *V,
404                                         unsigned PrefAlign = 0);
405
406   };
407 }
408
409 char InstCombiner::ID = 0;
410 static RegisterPass<InstCombiner>
411 X("instcombine", "Combine redundant instructions");
412
413 // getComplexity:  Assign a complexity or rank value to LLVM Values...
414 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
415 static unsigned getComplexity(Value *V) {
416   if (isa<Instruction>(V)) {
417     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
418       return 3;
419     return 4;
420   }
421   if (isa<Argument>(V)) return 3;
422   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
423 }
424
425 // isOnlyUse - Return true if this instruction will be deleted if we stop using
426 // it.
427 static bool isOnlyUse(Value *V) {
428   return V->hasOneUse() || isa<Constant>(V);
429 }
430
431 // getPromotedType - Return the specified type promoted as it would be to pass
432 // though a va_arg area...
433 static const Type *getPromotedType(const Type *Ty) {
434   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
435     if (ITy->getBitWidth() < 32)
436       return Type::Int32Ty;
437   }
438   return Ty;
439 }
440
441 /// getBitCastOperand - If the specified operand is a CastInst, a constant
442 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
443 /// operand value, otherwise return null.
444 static Value *getBitCastOperand(Value *V) {
445   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
446     // BitCastInst?
447     return I->getOperand(0);
448   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
449     // GetElementPtrInst?
450     if (GEP->hasAllZeroIndices())
451       return GEP->getOperand(0);
452   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
453     if (CE->getOpcode() == Instruction::BitCast)
454       // BitCast ConstantExp?
455       return CE->getOperand(0);
456     else if (CE->getOpcode() == Instruction::GetElementPtr) {
457       // GetElementPtr ConstantExp?
458       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
459            I != E; ++I) {
460         ConstantInt *CI = dyn_cast<ConstantInt>(I);
461         if (!CI || !CI->isZero())
462           // Any non-zero indices? Not cast-like.
463           return 0;
464       }
465       // All-zero indices? This is just like casting.
466       return CE->getOperand(0);
467     }
468   }
469   return 0;
470 }
471
472 /// This function is a wrapper around CastInst::isEliminableCastPair. It
473 /// simply extracts arguments and returns what that function returns.
474 static Instruction::CastOps 
475 isEliminableCastPair(
476   const CastInst *CI, ///< The first cast instruction
477   unsigned opcode,       ///< The opcode of the second cast instruction
478   const Type *DstTy,     ///< The target type for the second cast instruction
479   TargetData *TD         ///< The target data for pointer size
480 ) {
481   
482   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
483   const Type *MidTy = CI->getType();                  // B from above
484
485   // Get the opcodes of the two Cast instructions
486   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
487   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
488
489   return Instruction::CastOps(
490       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
491                                      DstTy, TD->getIntPtrType()));
492 }
493
494 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
495 /// in any code being generated.  It does not require codegen if V is simple
496 /// enough or if the cast can be folded into other casts.
497 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
498                               const Type *Ty, TargetData *TD) {
499   if (V->getType() == Ty || isa<Constant>(V)) return false;
500   
501   // If this is another cast that can be eliminated, it isn't codegen either.
502   if (const CastInst *CI = dyn_cast<CastInst>(V))
503     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
504       return false;
505   return true;
506 }
507
508 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
509 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
510 /// casts that are known to not do anything...
511 ///
512 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
513                                              Value *V, const Type *DestTy,
514                                              Instruction *InsertBefore) {
515   if (V->getType() == DestTy) return V;
516   if (Constant *C = dyn_cast<Constant>(V))
517     return ConstantExpr::getCast(opcode, C, DestTy);
518   
519   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
520 }
521
522 // SimplifyCommutative - This performs a few simplifications for commutative
523 // operators:
524 //
525 //  1. Order operands such that they are listed from right (least complex) to
526 //     left (most complex).  This puts constants before unary operators before
527 //     binary operators.
528 //
529 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
530 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
531 //
532 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
533   bool Changed = false;
534   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
535     Changed = !I.swapOperands();
536
537   if (!I.isAssociative()) return Changed;
538   Instruction::BinaryOps Opcode = I.getOpcode();
539   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
540     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
541       if (isa<Constant>(I.getOperand(1))) {
542         Constant *Folded = ConstantExpr::get(I.getOpcode(),
543                                              cast<Constant>(I.getOperand(1)),
544                                              cast<Constant>(Op->getOperand(1)));
545         I.setOperand(0, Op->getOperand(0));
546         I.setOperand(1, Folded);
547         return true;
548       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
549         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
550             isOnlyUse(Op) && isOnlyUse(Op1)) {
551           Constant *C1 = cast<Constant>(Op->getOperand(1));
552           Constant *C2 = cast<Constant>(Op1->getOperand(1));
553
554           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
555           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
556           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
557                                                     Op1->getOperand(0),
558                                                     Op1->getName(), &I);
559           AddToWorkList(New);
560           I.setOperand(0, New);
561           I.setOperand(1, Folded);
562           return true;
563         }
564     }
565   return Changed;
566 }
567
568 /// SimplifyCompare - For a CmpInst this function just orders the operands
569 /// so that theyare listed from right (least complex) to left (most complex).
570 /// This puts constants before unary operators before binary operators.
571 bool InstCombiner::SimplifyCompare(CmpInst &I) {
572   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
573     return false;
574   I.swapOperands();
575   // Compare instructions are not associative so there's nothing else we can do.
576   return true;
577 }
578
579 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
580 // if the LHS is a constant zero (which is the 'negate' form).
581 //
582 static inline Value *dyn_castNegVal(Value *V) {
583   if (BinaryOperator::isNeg(V))
584     return BinaryOperator::getNegArgument(V);
585
586   // Constants can be considered to be negated values if they can be folded.
587   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
588     return ConstantExpr::getNeg(C);
589
590   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591     if (C->getType()->getElementType()->isInteger())
592       return ConstantExpr::getNeg(C);
593
594   return 0;
595 }
596
597 static inline Value *dyn_castNotVal(Value *V) {
598   if (BinaryOperator::isNot(V))
599     return BinaryOperator::getNotArgument(V);
600
601   // Constants can be considered to be not'ed values...
602   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
603     return ConstantInt::get(~C->getValue());
604   return 0;
605 }
606
607 // dyn_castFoldableMul - If this value is a multiply that can be folded into
608 // other computations (because it has a constant operand), return the
609 // non-constant operand of the multiply, and set CST to point to the multiplier.
610 // Otherwise, return null.
611 //
612 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
613   if (V->hasOneUse() && V->getType()->isInteger())
614     if (Instruction *I = dyn_cast<Instruction>(V)) {
615       if (I->getOpcode() == Instruction::Mul)
616         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
617           return I->getOperand(0);
618       if (I->getOpcode() == Instruction::Shl)
619         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
620           // The multiplier is really 1 << CST.
621           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
622           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
623           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
624           return I->getOperand(0);
625         }
626     }
627   return 0;
628 }
629
630 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
631 /// expression, return it.
632 static User *dyn_castGetElementPtr(Value *V) {
633   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
634   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
635     if (CE->getOpcode() == Instruction::GetElementPtr)
636       return cast<User>(V);
637   return false;
638 }
639
640 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
641 /// opcode value. Otherwise return UserOp1.
642 static unsigned getOpcode(const Value *V) {
643   if (const Instruction *I = dyn_cast<Instruction>(V))
644     return I->getOpcode();
645   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
646     return CE->getOpcode();
647   // Use UserOp1 to mean there's no opcode.
648   return Instruction::UserOp1;
649 }
650
651 /// AddOne - Add one to a ConstantInt
652 static ConstantInt *AddOne(ConstantInt *C) {
653   APInt Val(C->getValue());
654   return ConstantInt::get(++Val);
655 }
656 /// SubOne - Subtract one from a ConstantInt
657 static ConstantInt *SubOne(ConstantInt *C) {
658   APInt Val(C->getValue());
659   return ConstantInt::get(--Val);
660 }
661 /// Add - Add two ConstantInts together
662 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
663   return ConstantInt::get(C1->getValue() + C2->getValue());
664 }
665 /// And - Bitwise AND two ConstantInts together
666 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
667   return ConstantInt::get(C1->getValue() & C2->getValue());
668 }
669 /// Subtract - Subtract one ConstantInt from another
670 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
671   return ConstantInt::get(C1->getValue() - C2->getValue());
672 }
673 /// Multiply - Multiply two ConstantInts together
674 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
675   return ConstantInt::get(C1->getValue() * C2->getValue());
676 }
677 /// MultiplyOverflows - True if the multiply can not be expressed in an int
678 /// this size.
679 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
680   uint32_t W = C1->getBitWidth();
681   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
682   if (sign) {
683     LHSExt.sext(W * 2);
684     RHSExt.sext(W * 2);
685   } else {
686     LHSExt.zext(W * 2);
687     RHSExt.zext(W * 2);
688   }
689
690   APInt MulExt = LHSExt * RHSExt;
691
692   if (sign) {
693     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
694     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
695     return MulExt.slt(Min) || MulExt.sgt(Max);
696   } else 
697     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
698 }
699
700
701 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
702 /// specified instruction is a constant integer.  If so, check to see if there
703 /// are any bits set in the constant that are not demanded.  If so, shrink the
704 /// constant and return true.
705 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
706                                    APInt Demanded) {
707   assert(I && "No instruction?");
708   assert(OpNo < I->getNumOperands() && "Operand index too large");
709
710   // If the operand is not a constant integer, nothing to do.
711   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
712   if (!OpC) return false;
713
714   // If there are no bits set that aren't demanded, nothing to do.
715   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
716   if ((~Demanded & OpC->getValue()) == 0)
717     return false;
718
719   // This instruction is producing bits that are not demanded. Shrink the RHS.
720   Demanded &= OpC->getValue();
721   I->setOperand(OpNo, ConstantInt::get(Demanded));
722   return true;
723 }
724
725 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
726 // set of known zero and one bits, compute the maximum and minimum values that
727 // could have the specified known zero and known one bits, returning them in
728 // min/max.
729 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
730                                                    const APInt& KnownZero,
731                                                    const APInt& KnownOne,
732                                                    APInt& Min, APInt& Max) {
733   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
734   assert(KnownZero.getBitWidth() == BitWidth && 
735          KnownOne.getBitWidth() == BitWidth &&
736          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
737          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
738   APInt UnknownBits = ~(KnownZero|KnownOne);
739
740   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
741   // bit if it is unknown.
742   Min = KnownOne;
743   Max = KnownOne|UnknownBits;
744   
745   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
746     Min.set(BitWidth-1);
747     Max.clear(BitWidth-1);
748   }
749 }
750
751 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
752 // a set of known zero and one bits, compute the maximum and minimum values that
753 // could have the specified known zero and known one bits, returning them in
754 // min/max.
755 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
756                                                      const APInt &KnownZero,
757                                                      const APInt &KnownOne,
758                                                      APInt &Min, APInt &Max) {
759   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
760   assert(KnownZero.getBitWidth() == BitWidth && 
761          KnownOne.getBitWidth() == BitWidth &&
762          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
763          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
764   APInt UnknownBits = ~(KnownZero|KnownOne);
765   
766   // The minimum value is when the unknown bits are all zeros.
767   Min = KnownOne;
768   // The maximum value is when the unknown bits are all ones.
769   Max = KnownOne|UnknownBits;
770 }
771
772 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
773 /// value based on the demanded bits. When this function is called, it is known
774 /// that only the bits set in DemandedMask of the result of V are ever used
775 /// downstream. Consequently, depending on the mask and V, it may be possible
776 /// to replace V with a constant or one of its operands. In such cases, this
777 /// function does the replacement and returns true. In all other cases, it
778 /// returns false after analyzing the expression and setting KnownOne and known
779 /// to be one in the expression. KnownZero contains all the bits that are known
780 /// to be zero in the expression. These are provided to potentially allow the
781 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
782 /// the expression. KnownOne and KnownZero always follow the invariant that 
783 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
784 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
785 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
786 /// and KnownOne must all be the same.
787 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
788                                         APInt& KnownZero, APInt& KnownOne,
789                                         unsigned Depth) {
790   assert(V != 0 && "Null pointer of Value???");
791   assert(Depth <= 6 && "Limit Search Depth");
792   uint32_t BitWidth = DemandedMask.getBitWidth();
793   const IntegerType *VTy = cast<IntegerType>(V->getType());
794   assert(VTy->getBitWidth() == BitWidth && 
795          KnownZero.getBitWidth() == BitWidth && 
796          KnownOne.getBitWidth() == BitWidth &&
797          "Value *V, DemandedMask, KnownZero and KnownOne \
798           must have same BitWidth");
799   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
800     // We know all of the bits for a constant!
801     KnownOne = CI->getValue() & DemandedMask;
802     KnownZero = ~KnownOne & DemandedMask;
803     return false;
804   }
805   
806   KnownZero.clear(); 
807   KnownOne.clear();
808   if (!V->hasOneUse()) {    // Other users may use these bits.
809     if (Depth != 0) {       // Not at the root.
810       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
811       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
812       return false;
813     }
814     // If this is the root being simplified, allow it to have multiple uses,
815     // just set the DemandedMask to all bits.
816     DemandedMask = APInt::getAllOnesValue(BitWidth);
817   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
818     if (V != UndefValue::get(VTy))
819       return UpdateValueUsesWith(V, UndefValue::get(VTy));
820     return false;
821   } else if (Depth == 6) {        // Limit search depth.
822     return false;
823   }
824   
825   Instruction *I = dyn_cast<Instruction>(V);
826   if (!I) return false;        // Only analyze instructions.
827
828   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
829   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
830   switch (I->getOpcode()) {
831   default:
832     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
833     break;
834   case Instruction::And:
835     // If either the LHS or the RHS are Zero, the result is zero.
836     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
837                              RHSKnownZero, RHSKnownOne, Depth+1))
838       return true;
839     assert((RHSKnownZero & RHSKnownOne) == 0 && 
840            "Bits known to be one AND zero?"); 
841
842     // If something is known zero on the RHS, the bits aren't demanded on the
843     // LHS.
844     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
845                              LHSKnownZero, LHSKnownOne, Depth+1))
846       return true;
847     assert((LHSKnownZero & LHSKnownOne) == 0 && 
848            "Bits known to be one AND zero?"); 
849
850     // If all of the demanded bits are known 1 on one side, return the other.
851     // These bits cannot contribute to the result of the 'and'.
852     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
853         (DemandedMask & ~LHSKnownZero))
854       return UpdateValueUsesWith(I, I->getOperand(0));
855     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
856         (DemandedMask & ~RHSKnownZero))
857       return UpdateValueUsesWith(I, I->getOperand(1));
858     
859     // If all of the demanded bits in the inputs are known zeros, return zero.
860     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
861       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
862       
863     // If the RHS is a constant, see if we can simplify it.
864     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
865       return UpdateValueUsesWith(I, I);
866       
867     // Output known-1 bits are only known if set in both the LHS & RHS.
868     RHSKnownOne &= LHSKnownOne;
869     // Output known-0 are known to be clear if zero in either the LHS | RHS.
870     RHSKnownZero |= LHSKnownZero;
871     break;
872   case Instruction::Or:
873     // If either the LHS or the RHS are One, the result is One.
874     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
875                              RHSKnownZero, RHSKnownOne, Depth+1))
876       return true;
877     assert((RHSKnownZero & RHSKnownOne) == 0 && 
878            "Bits known to be one AND zero?"); 
879     // If something is known one on the RHS, the bits aren't demanded on the
880     // LHS.
881     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
882                              LHSKnownZero, LHSKnownOne, Depth+1))
883       return true;
884     assert((LHSKnownZero & LHSKnownOne) == 0 && 
885            "Bits known to be one AND zero?"); 
886     
887     // If all of the demanded bits are known zero on one side, return the other.
888     // These bits cannot contribute to the result of the 'or'.
889     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
890         (DemandedMask & ~LHSKnownOne))
891       return UpdateValueUsesWith(I, I->getOperand(0));
892     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
893         (DemandedMask & ~RHSKnownOne))
894       return UpdateValueUsesWith(I, I->getOperand(1));
895
896     // If all of the potentially set bits on one side are known to be set on
897     // the other side, just use the 'other' side.
898     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
899         (DemandedMask & (~RHSKnownZero)))
900       return UpdateValueUsesWith(I, I->getOperand(0));
901     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
902         (DemandedMask & (~LHSKnownZero)))
903       return UpdateValueUsesWith(I, I->getOperand(1));
904         
905     // If the RHS is a constant, see if we can simplify it.
906     if (ShrinkDemandedConstant(I, 1, DemandedMask))
907       return UpdateValueUsesWith(I, I);
908           
909     // Output known-0 bits are only known if clear in both the LHS & RHS.
910     RHSKnownZero &= LHSKnownZero;
911     // Output known-1 are known to be set if set in either the LHS | RHS.
912     RHSKnownOne |= LHSKnownOne;
913     break;
914   case Instruction::Xor: {
915     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
916                              RHSKnownZero, RHSKnownOne, Depth+1))
917       return true;
918     assert((RHSKnownZero & RHSKnownOne) == 0 && 
919            "Bits known to be one AND zero?"); 
920     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
921                              LHSKnownZero, LHSKnownOne, Depth+1))
922       return true;
923     assert((LHSKnownZero & LHSKnownOne) == 0 && 
924            "Bits known to be one AND zero?"); 
925     
926     // If all of the demanded bits are known zero on one side, return the other.
927     // These bits cannot contribute to the result of the 'xor'.
928     if ((DemandedMask & RHSKnownZero) == DemandedMask)
929       return UpdateValueUsesWith(I, I->getOperand(0));
930     if ((DemandedMask & LHSKnownZero) == DemandedMask)
931       return UpdateValueUsesWith(I, I->getOperand(1));
932     
933     // Output known-0 bits are known if clear or set in both the LHS & RHS.
934     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
935                          (RHSKnownOne & LHSKnownOne);
936     // Output known-1 are known to be set if set in only one of the LHS, RHS.
937     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
938                         (RHSKnownOne & LHSKnownZero);
939     
940     // If all of the demanded bits are known to be zero on one side or the
941     // other, turn this into an *inclusive* or.
942     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
943     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
944       Instruction *Or =
945         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
946                                  I->getName());
947       InsertNewInstBefore(Or, *I);
948       return UpdateValueUsesWith(I, Or);
949     }
950     
951     // If all of the demanded bits on one side are known, and all of the set
952     // bits on that side are also known to be set on the other side, turn this
953     // into an AND, as we know the bits will be cleared.
954     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
955     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
956       // all known
957       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
958         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
959         Instruction *And = 
960           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
961         InsertNewInstBefore(And, *I);
962         return UpdateValueUsesWith(I, And);
963       }
964     }
965     
966     // If the RHS is a constant, see if we can simplify it.
967     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
968     if (ShrinkDemandedConstant(I, 1, DemandedMask))
969       return UpdateValueUsesWith(I, I);
970     
971     RHSKnownZero = KnownZeroOut;
972     RHSKnownOne  = KnownOneOut;
973     break;
974   }
975   case Instruction::Select:
976     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
977                              RHSKnownZero, RHSKnownOne, Depth+1))
978       return true;
979     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
980                              LHSKnownZero, LHSKnownOne, Depth+1))
981       return true;
982     assert((RHSKnownZero & RHSKnownOne) == 0 && 
983            "Bits known to be one AND zero?"); 
984     assert((LHSKnownZero & LHSKnownOne) == 0 && 
985            "Bits known to be one AND zero?"); 
986     
987     // If the operands are constants, see if we can simplify them.
988     if (ShrinkDemandedConstant(I, 1, DemandedMask))
989       return UpdateValueUsesWith(I, I);
990     if (ShrinkDemandedConstant(I, 2, DemandedMask))
991       return UpdateValueUsesWith(I, I);
992     
993     // Only known if known in both the LHS and RHS.
994     RHSKnownOne &= LHSKnownOne;
995     RHSKnownZero &= LHSKnownZero;
996     break;
997   case Instruction::Trunc: {
998     uint32_t truncBf = 
999       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1000     DemandedMask.zext(truncBf);
1001     RHSKnownZero.zext(truncBf);
1002     RHSKnownOne.zext(truncBf);
1003     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1004                              RHSKnownZero, RHSKnownOne, Depth+1))
1005       return true;
1006     DemandedMask.trunc(BitWidth);
1007     RHSKnownZero.trunc(BitWidth);
1008     RHSKnownOne.trunc(BitWidth);
1009     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1010            "Bits known to be one AND zero?"); 
1011     break;
1012   }
1013   case Instruction::BitCast:
1014     if (!I->getOperand(0)->getType()->isInteger())
1015       return false;
1016       
1017     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1018                              RHSKnownZero, RHSKnownOne, Depth+1))
1019       return true;
1020     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1021            "Bits known to be one AND zero?"); 
1022     break;
1023   case Instruction::ZExt: {
1024     // Compute the bits in the result that are not present in the input.
1025     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1026     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1027     
1028     DemandedMask.trunc(SrcBitWidth);
1029     RHSKnownZero.trunc(SrcBitWidth);
1030     RHSKnownOne.trunc(SrcBitWidth);
1031     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1032                              RHSKnownZero, RHSKnownOne, Depth+1))
1033       return true;
1034     DemandedMask.zext(BitWidth);
1035     RHSKnownZero.zext(BitWidth);
1036     RHSKnownOne.zext(BitWidth);
1037     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1038            "Bits known to be one AND zero?"); 
1039     // The top bits are known to be zero.
1040     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1041     break;
1042   }
1043   case Instruction::SExt: {
1044     // Compute the bits in the result that are not present in the input.
1045     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1046     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1047     
1048     APInt InputDemandedBits = DemandedMask & 
1049                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1050
1051     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1052     // If any of the sign extended bits are demanded, we know that the sign
1053     // bit is demanded.
1054     if ((NewBits & DemandedMask) != 0)
1055       InputDemandedBits.set(SrcBitWidth-1);
1056       
1057     InputDemandedBits.trunc(SrcBitWidth);
1058     RHSKnownZero.trunc(SrcBitWidth);
1059     RHSKnownOne.trunc(SrcBitWidth);
1060     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1061                              RHSKnownZero, RHSKnownOne, Depth+1))
1062       return true;
1063     InputDemandedBits.zext(BitWidth);
1064     RHSKnownZero.zext(BitWidth);
1065     RHSKnownOne.zext(BitWidth);
1066     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1067            "Bits known to be one AND zero?"); 
1068       
1069     // If the sign bit of the input is known set or clear, then we know the
1070     // top bits of the result.
1071
1072     // If the input sign bit is known zero, or if the NewBits are not demanded
1073     // convert this into a zero extension.
1074     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1075     {
1076       // Convert to ZExt cast
1077       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1078       return UpdateValueUsesWith(I, NewCast);
1079     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1080       RHSKnownOne |= NewBits;
1081     }
1082     break;
1083   }
1084   case Instruction::Add: {
1085     // Figure out what the input bits are.  If the top bits of the and result
1086     // are not demanded, then the add doesn't demand them from its input
1087     // either.
1088     uint32_t NLZ = DemandedMask.countLeadingZeros();
1089       
1090     // If there is a constant on the RHS, there are a variety of xformations
1091     // we can do.
1092     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1093       // If null, this should be simplified elsewhere.  Some of the xforms here
1094       // won't work if the RHS is zero.
1095       if (RHS->isZero())
1096         break;
1097       
1098       // If the top bit of the output is demanded, demand everything from the
1099       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1100       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1101
1102       // Find information about known zero/one bits in the input.
1103       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1104                                LHSKnownZero, LHSKnownOne, Depth+1))
1105         return true;
1106
1107       // If the RHS of the add has bits set that can't affect the input, reduce
1108       // the constant.
1109       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1110         return UpdateValueUsesWith(I, I);
1111       
1112       // Avoid excess work.
1113       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1114         break;
1115       
1116       // Turn it into OR if input bits are zero.
1117       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1118         Instruction *Or =
1119           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1120                                    I->getName());
1121         InsertNewInstBefore(Or, *I);
1122         return UpdateValueUsesWith(I, Or);
1123       }
1124       
1125       // We can say something about the output known-zero and known-one bits,
1126       // depending on potential carries from the input constant and the
1127       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1128       // bits set and the RHS constant is 0x01001, then we know we have a known
1129       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1130       
1131       // To compute this, we first compute the potential carry bits.  These are
1132       // the bits which may be modified.  I'm not aware of a better way to do
1133       // this scan.
1134       const APInt& RHSVal = RHS->getValue();
1135       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1136       
1137       // Now that we know which bits have carries, compute the known-1/0 sets.
1138       
1139       // Bits are known one if they are known zero in one operand and one in the
1140       // other, and there is no input carry.
1141       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1142                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1143       
1144       // Bits are known zero if they are known zero in both operands and there
1145       // is no input carry.
1146       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1147     } else {
1148       // If the high-bits of this ADD are not demanded, then it does not demand
1149       // the high bits of its LHS or RHS.
1150       if (DemandedMask[BitWidth-1] == 0) {
1151         // Right fill the mask of bits for this ADD to demand the most
1152         // significant bit and all those below it.
1153         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1154         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1155                                  LHSKnownZero, LHSKnownOne, Depth+1))
1156           return true;
1157         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1158                                  LHSKnownZero, LHSKnownOne, Depth+1))
1159           return true;
1160       }
1161     }
1162     break;
1163   }
1164   case Instruction::Sub:
1165     // If the high-bits of this SUB are not demanded, then it does not demand
1166     // the high bits of its LHS or RHS.
1167     if (DemandedMask[BitWidth-1] == 0) {
1168       // Right fill the mask of bits for this SUB to demand the most
1169       // significant bit and all those below it.
1170       uint32_t NLZ = DemandedMask.countLeadingZeros();
1171       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1172       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1173                                LHSKnownZero, LHSKnownOne, Depth+1))
1174         return true;
1175       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1176                                LHSKnownZero, LHSKnownOne, Depth+1))
1177         return true;
1178     }
1179     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1180     // the known zeros and ones.
1181     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1182     break;
1183   case Instruction::Shl:
1184     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1186       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1187       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1188                                RHSKnownZero, RHSKnownOne, Depth+1))
1189         return true;
1190       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1191              "Bits known to be one AND zero?"); 
1192       RHSKnownZero <<= ShiftAmt;
1193       RHSKnownOne  <<= ShiftAmt;
1194       // low bits known zero.
1195       if (ShiftAmt)
1196         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1197     }
1198     break;
1199   case Instruction::LShr:
1200     // For a logical shift right
1201     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1202       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1203       
1204       // Unsigned shift right.
1205       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1206       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1207                                RHSKnownZero, RHSKnownOne, Depth+1))
1208         return true;
1209       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1210              "Bits known to be one AND zero?"); 
1211       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1212       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1213       if (ShiftAmt) {
1214         // Compute the new bits that are at the top now.
1215         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1216         RHSKnownZero |= HighBits;  // high bits known zero.
1217       }
1218     }
1219     break;
1220   case Instruction::AShr:
1221     // If this is an arithmetic shift right and only the low-bit is set, we can
1222     // always convert this into a logical shr, even if the shift amount is
1223     // variable.  The low bit of the shift cannot be an input sign bit unless
1224     // the shift amount is >= the size of the datatype, which is undefined.
1225     if (DemandedMask == 1) {
1226       // Perform the logical shift right.
1227       Value *NewVal = BinaryOperator::CreateLShr(
1228                         I->getOperand(0), I->getOperand(1), I->getName());
1229       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1230       return UpdateValueUsesWith(I, NewVal);
1231     }    
1232
1233     // If the sign bit is the only bit demanded by this ashr, then there is no
1234     // need to do it, the shift doesn't change the high bit.
1235     if (DemandedMask.isSignBit())
1236       return UpdateValueUsesWith(I, I->getOperand(0));
1237     
1238     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1239       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1240       
1241       // Signed shift right.
1242       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1243       // If any of the "high bits" are demanded, we should set the sign bit as
1244       // demanded.
1245       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1246         DemandedMaskIn.set(BitWidth-1);
1247       if (SimplifyDemandedBits(I->getOperand(0),
1248                                DemandedMaskIn,
1249                                RHSKnownZero, RHSKnownOne, Depth+1))
1250         return true;
1251       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1252              "Bits known to be one AND zero?"); 
1253       // Compute the new bits that are at the top now.
1254       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1255       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1256       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1257         
1258       // Handle the sign bits.
1259       APInt SignBit(APInt::getSignBit(BitWidth));
1260       // Adjust to where it is now in the mask.
1261       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1262         
1263       // If the input sign bit is known to be zero, or if none of the top bits
1264       // are demanded, turn this into an unsigned shift right.
1265       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1266           (HighBits & ~DemandedMask) == HighBits) {
1267         // Perform the logical shift right.
1268         Value *NewVal = BinaryOperator::CreateLShr(
1269                           I->getOperand(0), SA, I->getName());
1270         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1271         return UpdateValueUsesWith(I, NewVal);
1272       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1273         RHSKnownOne |= HighBits;
1274       }
1275     }
1276     break;
1277   case Instruction::SRem:
1278     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1279       APInt RA = Rem->getValue().abs();
1280       if (RA.isPowerOf2()) {
1281         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1282           return UpdateValueUsesWith(I, I->getOperand(0));
1283
1284         APInt LowBits = RA - 1;
1285         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1286         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1287                                  LHSKnownZero, LHSKnownOne, Depth+1))
1288           return true;
1289
1290         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1291           LHSKnownZero |= ~LowBits;
1292
1293         KnownZero |= LHSKnownZero & DemandedMask;
1294
1295         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1296       }
1297     }
1298     break;
1299   case Instruction::URem: {
1300     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1301     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1302     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1303                              KnownZero2, KnownOne2, Depth+1))
1304       return true;
1305
1306     uint32_t Leaders = KnownZero2.countLeadingOnes();
1307     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1308                              KnownZero2, KnownOne2, Depth+1))
1309       return true;
1310
1311     Leaders = std::max(Leaders,
1312                        KnownZero2.countLeadingOnes());
1313     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1314     break;
1315   }
1316   case Instruction::Call:
1317     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1318       switch (II->getIntrinsicID()) {
1319       default: break;
1320       case Intrinsic::bswap: {
1321         // If the only bits demanded come from one byte of the bswap result,
1322         // just shift the input byte into position to eliminate the bswap.
1323         unsigned NLZ = DemandedMask.countLeadingZeros();
1324         unsigned NTZ = DemandedMask.countTrailingZeros();
1325           
1326         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1327         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1328         // have 14 leading zeros, round to 8.
1329         NLZ &= ~7;
1330         NTZ &= ~7;
1331         // If we need exactly one byte, we can do this transformation.
1332         if (BitWidth-NLZ-NTZ == 8) {
1333           unsigned ResultBit = NTZ;
1334           unsigned InputBit = BitWidth-NTZ-8;
1335           
1336           // Replace this with either a left or right shift to get the byte into
1337           // the right place.
1338           Instruction *NewVal;
1339           if (InputBit > ResultBit)
1340             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1341                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1342           else
1343             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1344                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1345           NewVal->takeName(I);
1346           InsertNewInstBefore(NewVal, *I);
1347           return UpdateValueUsesWith(I, NewVal);
1348         }
1349           
1350         // TODO: Could compute known zero/one bits based on the input.
1351         break;
1352       }
1353       }
1354     }
1355     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1356     break;
1357   }
1358   
1359   // If the client is only demanding bits that we know, return the known
1360   // constant.
1361   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1362     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1363   return false;
1364 }
1365
1366
1367 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1368 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1369 /// actually used by the caller.  This method analyzes which elements of the
1370 /// operand are undef and returns that information in UndefElts.
1371 ///
1372 /// If the information about demanded elements can be used to simplify the
1373 /// operation, the operation is simplified, then the resultant value is
1374 /// returned.  This returns null if no change was made.
1375 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1376                                                 uint64_t &UndefElts,
1377                                                 unsigned Depth) {
1378   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1379   assert(VWidth <= 64 && "Vector too wide to analyze!");
1380   uint64_t EltMask = ~0ULL >> (64-VWidth);
1381   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1382
1383   if (isa<UndefValue>(V)) {
1384     // If the entire vector is undefined, just return this info.
1385     UndefElts = EltMask;
1386     return 0;
1387   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1388     UndefElts = EltMask;
1389     return UndefValue::get(V->getType());
1390   }
1391
1392   UndefElts = 0;
1393   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1394     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1395     Constant *Undef = UndefValue::get(EltTy);
1396
1397     std::vector<Constant*> Elts;
1398     for (unsigned i = 0; i != VWidth; ++i)
1399       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1400         Elts.push_back(Undef);
1401         UndefElts |= (1ULL << i);
1402       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1403         Elts.push_back(Undef);
1404         UndefElts |= (1ULL << i);
1405       } else {                               // Otherwise, defined.
1406         Elts.push_back(CP->getOperand(i));
1407       }
1408
1409     // If we changed the constant, return it.
1410     Constant *NewCP = ConstantVector::get(Elts);
1411     return NewCP != CP ? NewCP : 0;
1412   } else if (isa<ConstantAggregateZero>(V)) {
1413     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1414     // set to undef.
1415     
1416     // Check if this is identity. If so, return 0 since we are not simplifying
1417     // anything.
1418     if (DemandedElts == ((1ULL << VWidth) -1))
1419       return 0;
1420     
1421     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1422     Constant *Zero = Constant::getNullValue(EltTy);
1423     Constant *Undef = UndefValue::get(EltTy);
1424     std::vector<Constant*> Elts;
1425     for (unsigned i = 0; i != VWidth; ++i)
1426       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1427     UndefElts = DemandedElts ^ EltMask;
1428     return ConstantVector::get(Elts);
1429   }
1430   
1431   // Limit search depth.
1432   if (Depth == 10)
1433     return false;
1434
1435   // If multiple users are using the root value, procede with
1436   // simplification conservatively assuming that all elements
1437   // are needed.
1438   if (!V->hasOneUse()) {
1439     // Quit if we find multiple users of a non-root value though.
1440     // They'll be handled when it's their turn to be visited by
1441     // the main instcombine process.
1442     if (Depth != 0)
1443       // TODO: Just compute the UndefElts information recursively.
1444       return false;
1445
1446     // Conservatively assume that all elements are needed.
1447     DemandedElts = EltMask;
1448   }
1449   
1450   Instruction *I = dyn_cast<Instruction>(V);
1451   if (!I) return false;        // Only analyze instructions.
1452   
1453   bool MadeChange = false;
1454   uint64_t UndefElts2;
1455   Value *TmpV;
1456   switch (I->getOpcode()) {
1457   default: break;
1458     
1459   case Instruction::InsertElement: {
1460     // If this is a variable index, we don't know which element it overwrites.
1461     // demand exactly the same input as we produce.
1462     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1463     if (Idx == 0) {
1464       // Note that we can't propagate undef elt info, because we don't know
1465       // which elt is getting updated.
1466       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1467                                         UndefElts2, Depth+1);
1468       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1469       break;
1470     }
1471     
1472     // If this is inserting an element that isn't demanded, remove this
1473     // insertelement.
1474     unsigned IdxNo = Idx->getZExtValue();
1475     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1476       return AddSoonDeadInstToWorklist(*I, 0);
1477     
1478     // Otherwise, the element inserted overwrites whatever was there, so the
1479     // input demanded set is simpler than the output set.
1480     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1481                                       DemandedElts & ~(1ULL << IdxNo),
1482                                       UndefElts, Depth+1);
1483     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1484
1485     // The inserted element is defined.
1486     UndefElts &= ~(1ULL << IdxNo);
1487     break;
1488   }
1489   case Instruction::ShuffleVector: {
1490     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1491     uint64_t LHSVWidth =
1492       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1493     uint64_t LeftDemanded = 0, RightDemanded = 0;
1494     for (unsigned i = 0; i < VWidth; i++) {
1495       if (DemandedElts & (1ULL << i)) {
1496         unsigned MaskVal = Shuffle->getMaskValue(i);
1497         if (MaskVal != -1u) {
1498           assert(MaskVal < LHSVWidth * 2 &&
1499                  "shufflevector mask index out of range!");
1500           if (MaskVal < LHSVWidth)
1501             LeftDemanded |= 1ULL << MaskVal;
1502           else
1503             RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
1504         }
1505       }
1506     }
1507
1508     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1509                                       UndefElts2, Depth+1);
1510     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1511
1512     uint64_t UndefElts3;
1513     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1514                                       UndefElts3, Depth+1);
1515     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1516
1517     bool NewUndefElts = false;
1518     for (unsigned i = 0; i < VWidth; i++) {
1519       unsigned MaskVal = Shuffle->getMaskValue(i);
1520       if (MaskVal == -1u) {
1521         uint64_t NewBit = 1ULL << i;
1522         UndefElts |= NewBit;
1523       } else if (MaskVal < LHSVWidth) {
1524         uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1525         NewUndefElts |= NewBit;
1526         UndefElts |= NewBit;
1527       } else {
1528         uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
1529         NewUndefElts |= NewBit;
1530         UndefElts |= NewBit;
1531       }
1532     }
1533
1534     if (NewUndefElts) {
1535       // Add additional discovered undefs.
1536       std::vector<Constant*> Elts;
1537       for (unsigned i = 0; i < VWidth; ++i) {
1538         if (UndefElts & (1ULL << i))
1539           Elts.push_back(UndefValue::get(Type::Int32Ty));
1540         else
1541           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1542                                           Shuffle->getMaskValue(i)));
1543       }
1544       I->setOperand(2, ConstantVector::get(Elts));
1545       MadeChange = true;
1546     }
1547     break;
1548   }
1549   case Instruction::BitCast: {
1550     // Vector->vector casts only.
1551     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1552     if (!VTy) break;
1553     unsigned InVWidth = VTy->getNumElements();
1554     uint64_t InputDemandedElts = 0;
1555     unsigned Ratio;
1556
1557     if (VWidth == InVWidth) {
1558       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1559       // elements as are demanded of us.
1560       Ratio = 1;
1561       InputDemandedElts = DemandedElts;
1562     } else if (VWidth > InVWidth) {
1563       // Untested so far.
1564       break;
1565       
1566       // If there are more elements in the result than there are in the source,
1567       // then an input element is live if any of the corresponding output
1568       // elements are live.
1569       Ratio = VWidth/InVWidth;
1570       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1571         if (DemandedElts & (1ULL << OutIdx))
1572           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1573       }
1574     } else {
1575       // Untested so far.
1576       break;
1577       
1578       // If there are more elements in the source than there are in the result,
1579       // then an input element is live if the corresponding output element is
1580       // live.
1581       Ratio = InVWidth/VWidth;
1582       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1583         if (DemandedElts & (1ULL << InIdx/Ratio))
1584           InputDemandedElts |= 1ULL << InIdx;
1585     }
1586     
1587     // div/rem demand all inputs, because they don't want divide by zero.
1588     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1589                                       UndefElts2, Depth+1);
1590     if (TmpV) {
1591       I->setOperand(0, TmpV);
1592       MadeChange = true;
1593     }
1594     
1595     UndefElts = UndefElts2;
1596     if (VWidth > InVWidth) {
1597       assert(0 && "Unimp");
1598       // If there are more elements in the result than there are in the source,
1599       // then an output element is undef if the corresponding input element is
1600       // undef.
1601       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1602         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1603           UndefElts |= 1ULL << OutIdx;
1604     } else if (VWidth < InVWidth) {
1605       assert(0 && "Unimp");
1606       // If there are more elements in the source than there are in the result,
1607       // then a result element is undef if all of the corresponding input
1608       // elements are undef.
1609       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1610       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1611         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1612           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1613     }
1614     break;
1615   }
1616   case Instruction::And:
1617   case Instruction::Or:
1618   case Instruction::Xor:
1619   case Instruction::Add:
1620   case Instruction::Sub:
1621   case Instruction::Mul:
1622     // div/rem demand all inputs, because they don't want divide by zero.
1623     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1624                                       UndefElts, Depth+1);
1625     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1626     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1627                                       UndefElts2, Depth+1);
1628     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1629       
1630     // Output elements are undefined if both are undefined.  Consider things
1631     // like undef&0.  The result is known zero, not undef.
1632     UndefElts &= UndefElts2;
1633     break;
1634     
1635   case Instruction::Call: {
1636     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1637     if (!II) break;
1638     switch (II->getIntrinsicID()) {
1639     default: break;
1640       
1641     // Binary vector operations that work column-wise.  A dest element is a
1642     // function of the corresponding input elements from the two inputs.
1643     case Intrinsic::x86_sse_sub_ss:
1644     case Intrinsic::x86_sse_mul_ss:
1645     case Intrinsic::x86_sse_min_ss:
1646     case Intrinsic::x86_sse_max_ss:
1647     case Intrinsic::x86_sse2_sub_sd:
1648     case Intrinsic::x86_sse2_mul_sd:
1649     case Intrinsic::x86_sse2_min_sd:
1650     case Intrinsic::x86_sse2_max_sd:
1651       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1652                                         UndefElts, Depth+1);
1653       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1654       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1655                                         UndefElts2, Depth+1);
1656       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1657
1658       // If only the low elt is demanded and this is a scalarizable intrinsic,
1659       // scalarize it now.
1660       if (DemandedElts == 1) {
1661         switch (II->getIntrinsicID()) {
1662         default: break;
1663         case Intrinsic::x86_sse_sub_ss:
1664         case Intrinsic::x86_sse_mul_ss:
1665         case Intrinsic::x86_sse2_sub_sd:
1666         case Intrinsic::x86_sse2_mul_sd:
1667           // TODO: Lower MIN/MAX/ABS/etc
1668           Value *LHS = II->getOperand(1);
1669           Value *RHS = II->getOperand(2);
1670           // Extract the element as scalars.
1671           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1672           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1673           
1674           switch (II->getIntrinsicID()) {
1675           default: assert(0 && "Case stmts out of sync!");
1676           case Intrinsic::x86_sse_sub_ss:
1677           case Intrinsic::x86_sse2_sub_sd:
1678             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1679                                                         II->getName()), *II);
1680             break;
1681           case Intrinsic::x86_sse_mul_ss:
1682           case Intrinsic::x86_sse2_mul_sd:
1683             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1684                                                          II->getName()), *II);
1685             break;
1686           }
1687           
1688           Instruction *New =
1689             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1690                                       II->getName());
1691           InsertNewInstBefore(New, *II);
1692           AddSoonDeadInstToWorklist(*II, 0);
1693           return New;
1694         }            
1695       }
1696         
1697       // Output elements are undefined if both are undefined.  Consider things
1698       // like undef&0.  The result is known zero, not undef.
1699       UndefElts &= UndefElts2;
1700       break;
1701     }
1702     break;
1703   }
1704   }
1705   return MadeChange ? I : 0;
1706 }
1707
1708
1709 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1710 /// function is designed to check a chain of associative operators for a
1711 /// potential to apply a certain optimization.  Since the optimization may be
1712 /// applicable if the expression was reassociated, this checks the chain, then
1713 /// reassociates the expression as necessary to expose the optimization
1714 /// opportunity.  This makes use of a special Functor, which must define
1715 /// 'shouldApply' and 'apply' methods.
1716 ///
1717 template<typename Functor>
1718 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1719   unsigned Opcode = Root.getOpcode();
1720   Value *LHS = Root.getOperand(0);
1721
1722   // Quick check, see if the immediate LHS matches...
1723   if (F.shouldApply(LHS))
1724     return F.apply(Root);
1725
1726   // Otherwise, if the LHS is not of the same opcode as the root, return.
1727   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1728   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1729     // Should we apply this transform to the RHS?
1730     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1731
1732     // If not to the RHS, check to see if we should apply to the LHS...
1733     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1734       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1735       ShouldApply = true;
1736     }
1737
1738     // If the functor wants to apply the optimization to the RHS of LHSI,
1739     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1740     if (ShouldApply) {
1741       // Now all of the instructions are in the current basic block, go ahead
1742       // and perform the reassociation.
1743       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1744
1745       // First move the selected RHS to the LHS of the root...
1746       Root.setOperand(0, LHSI->getOperand(1));
1747
1748       // Make what used to be the LHS of the root be the user of the root...
1749       Value *ExtraOperand = TmpLHSI->getOperand(1);
1750       if (&Root == TmpLHSI) {
1751         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1752         return 0;
1753       }
1754       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1755       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1756       BasicBlock::iterator ARI = &Root; ++ARI;
1757       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1758       ARI = Root;
1759
1760       // Now propagate the ExtraOperand down the chain of instructions until we
1761       // get to LHSI.
1762       while (TmpLHSI != LHSI) {
1763         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1764         // Move the instruction to immediately before the chain we are
1765         // constructing to avoid breaking dominance properties.
1766         NextLHSI->moveBefore(ARI);
1767         ARI = NextLHSI;
1768
1769         Value *NextOp = NextLHSI->getOperand(1);
1770         NextLHSI->setOperand(1, ExtraOperand);
1771         TmpLHSI = NextLHSI;
1772         ExtraOperand = NextOp;
1773       }
1774
1775       // Now that the instructions are reassociated, have the functor perform
1776       // the transformation...
1777       return F.apply(Root);
1778     }
1779
1780     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1781   }
1782   return 0;
1783 }
1784
1785 namespace {
1786
1787 // AddRHS - Implements: X + X --> X << 1
1788 struct AddRHS {
1789   Value *RHS;
1790   AddRHS(Value *rhs) : RHS(rhs) {}
1791   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1792   Instruction *apply(BinaryOperator &Add) const {
1793     return BinaryOperator::CreateShl(Add.getOperand(0),
1794                                      ConstantInt::get(Add.getType(), 1));
1795   }
1796 };
1797
1798 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1799 //                 iff C1&C2 == 0
1800 struct AddMaskingAnd {
1801   Constant *C2;
1802   AddMaskingAnd(Constant *c) : C2(c) {}
1803   bool shouldApply(Value *LHS) const {
1804     ConstantInt *C1;
1805     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1806            ConstantExpr::getAnd(C1, C2)->isNullValue();
1807   }
1808   Instruction *apply(BinaryOperator &Add) const {
1809     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1810   }
1811 };
1812
1813 }
1814
1815 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1816                                              InstCombiner *IC) {
1817   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1818     if (Constant *SOC = dyn_cast<Constant>(SO))
1819       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1820
1821     return IC->InsertNewInstBefore(CastInst::Create(
1822           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1823   }
1824
1825   // Figure out if the constant is the left or the right argument.
1826   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1827   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1828
1829   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1830     if (ConstIsRHS)
1831       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1832     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1833   }
1834
1835   Value *Op0 = SO, *Op1 = ConstOperand;
1836   if (!ConstIsRHS)
1837     std::swap(Op0, Op1);
1838   Instruction *New;
1839   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1840     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1841   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1842     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1843                           SO->getName()+".cmp");
1844   else {
1845     assert(0 && "Unknown binary instruction type!");
1846     abort();
1847   }
1848   return IC->InsertNewInstBefore(New, I);
1849 }
1850
1851 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1852 // constant as the other operand, try to fold the binary operator into the
1853 // select arguments.  This also works for Cast instructions, which obviously do
1854 // not have a second operand.
1855 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1856                                      InstCombiner *IC) {
1857   // Don't modify shared select instructions
1858   if (!SI->hasOneUse()) return 0;
1859   Value *TV = SI->getOperand(1);
1860   Value *FV = SI->getOperand(2);
1861
1862   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1863     // Bool selects with constant operands can be folded to logical ops.
1864     if (SI->getType() == Type::Int1Ty) return 0;
1865
1866     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1867     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1868
1869     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1870                               SelectFalseVal);
1871   }
1872   return 0;
1873 }
1874
1875
1876 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1877 /// node as operand #0, see if we can fold the instruction into the PHI (which
1878 /// is only possible if all operands to the PHI are constants).
1879 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1880   PHINode *PN = cast<PHINode>(I.getOperand(0));
1881   unsigned NumPHIValues = PN->getNumIncomingValues();
1882   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1883
1884   // Check to see if all of the operands of the PHI are constants.  If there is
1885   // one non-constant value, remember the BB it is.  If there is more than one
1886   // or if *it* is a PHI, bail out.
1887   BasicBlock *NonConstBB = 0;
1888   for (unsigned i = 0; i != NumPHIValues; ++i)
1889     if (!isa<Constant>(PN->getIncomingValue(i))) {
1890       if (NonConstBB) return 0;  // More than one non-const value.
1891       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1892       NonConstBB = PN->getIncomingBlock(i);
1893       
1894       // If the incoming non-constant value is in I's block, we have an infinite
1895       // loop.
1896       if (NonConstBB == I.getParent())
1897         return 0;
1898     }
1899   
1900   // If there is exactly one non-constant value, we can insert a copy of the
1901   // operation in that block.  However, if this is a critical edge, we would be
1902   // inserting the computation one some other paths (e.g. inside a loop).  Only
1903   // do this if the pred block is unconditionally branching into the phi block.
1904   if (NonConstBB) {
1905     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1906     if (!BI || !BI->isUnconditional()) return 0;
1907   }
1908
1909   // Okay, we can do the transformation: create the new PHI node.
1910   PHINode *NewPN = PHINode::Create(I.getType(), "");
1911   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1912   InsertNewInstBefore(NewPN, *PN);
1913   NewPN->takeName(PN);
1914
1915   // Next, add all of the operands to the PHI.
1916   if (I.getNumOperands() == 2) {
1917     Constant *C = cast<Constant>(I.getOperand(1));
1918     for (unsigned i = 0; i != NumPHIValues; ++i) {
1919       Value *InV = 0;
1920       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1921         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1922           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1923         else
1924           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1925       } else {
1926         assert(PN->getIncomingBlock(i) == NonConstBB);
1927         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1928           InV = BinaryOperator::Create(BO->getOpcode(),
1929                                        PN->getIncomingValue(i), C, "phitmp",
1930                                        NonConstBB->getTerminator());
1931         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1932           InV = CmpInst::Create(CI->getOpcode(), 
1933                                 CI->getPredicate(),
1934                                 PN->getIncomingValue(i), C, "phitmp",
1935                                 NonConstBB->getTerminator());
1936         else
1937           assert(0 && "Unknown binop!");
1938         
1939         AddToWorkList(cast<Instruction>(InV));
1940       }
1941       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1942     }
1943   } else { 
1944     CastInst *CI = cast<CastInst>(&I);
1945     const Type *RetTy = CI->getType();
1946     for (unsigned i = 0; i != NumPHIValues; ++i) {
1947       Value *InV;
1948       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1949         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1950       } else {
1951         assert(PN->getIncomingBlock(i) == NonConstBB);
1952         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1953                                I.getType(), "phitmp", 
1954                                NonConstBB->getTerminator());
1955         AddToWorkList(cast<Instruction>(InV));
1956       }
1957       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1958     }
1959   }
1960   return ReplaceInstUsesWith(I, NewPN);
1961 }
1962
1963
1964 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1965 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1966 /// This basically requires proving that the add in the original type would not
1967 /// overflow to change the sign bit or have a carry out.
1968 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1969   // There are different heuristics we can use for this.  Here are some simple
1970   // ones.
1971   
1972   // Add has the property that adding any two 2's complement numbers can only 
1973   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1974   // have at least two sign bits, we know that the addition of the two values will
1975   // sign extend fine.
1976   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1977     return true;
1978   
1979   
1980   // If one of the operands only has one non-zero bit, and if the other operand
1981   // has a known-zero bit in a more significant place than it (not including the
1982   // sign bit) the ripple may go up to and fill the zero, but won't change the
1983   // sign.  For example, (X & ~4) + 1.
1984   
1985   // TODO: Implement.
1986   
1987   return false;
1988 }
1989
1990
1991 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1992   bool Changed = SimplifyCommutative(I);
1993   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1994
1995   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1996     // X + undef -> undef
1997     if (isa<UndefValue>(RHS))
1998       return ReplaceInstUsesWith(I, RHS);
1999
2000     // X + 0 --> X
2001     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2002       if (RHSC->isNullValue())
2003         return ReplaceInstUsesWith(I, LHS);
2004     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2005       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2006                               (I.getType())->getValueAPF()))
2007         return ReplaceInstUsesWith(I, LHS);
2008     }
2009
2010     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2011       // X + (signbit) --> X ^ signbit
2012       const APInt& Val = CI->getValue();
2013       uint32_t BitWidth = Val.getBitWidth();
2014       if (Val == APInt::getSignBit(BitWidth))
2015         return BinaryOperator::CreateXor(LHS, RHS);
2016       
2017       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2018       // (X & 254)+1 -> (X&254)|1
2019       if (!isa<VectorType>(I.getType())) {
2020         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2021         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2022                                  KnownZero, KnownOne))
2023           return &I;
2024       }
2025
2026       // zext(i1) - 1  ->  select i1, 0, -1
2027       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2028         if (CI->isAllOnesValue() &&
2029             ZI->getOperand(0)->getType() == Type::Int1Ty)
2030           return SelectInst::Create(ZI->getOperand(0),
2031                                     Constant::getNullValue(I.getType()),
2032                                     ConstantInt::getAllOnesValue(I.getType()));
2033     }
2034
2035     if (isa<PHINode>(LHS))
2036       if (Instruction *NV = FoldOpIntoPhi(I))
2037         return NV;
2038     
2039     ConstantInt *XorRHS = 0;
2040     Value *XorLHS = 0;
2041     if (isa<ConstantInt>(RHSC) &&
2042         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2043       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2044       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2045       
2046       uint32_t Size = TySizeBits / 2;
2047       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2048       APInt CFF80Val(-C0080Val);
2049       do {
2050         if (TySizeBits > Size) {
2051           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2052           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2053           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2054               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2055             // This is a sign extend if the top bits are known zero.
2056             if (!MaskedValueIsZero(XorLHS, 
2057                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2058               Size = 0;  // Not a sign ext, but can't be any others either.
2059             break;
2060           }
2061         }
2062         Size >>= 1;
2063         C0080Val = APIntOps::lshr(C0080Val, Size);
2064         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2065       } while (Size >= 1);
2066       
2067       // FIXME: This shouldn't be necessary. When the backends can handle types
2068       // with funny bit widths then this switch statement should be removed. It
2069       // is just here to get the size of the "middle" type back up to something
2070       // that the back ends can handle.
2071       const Type *MiddleType = 0;
2072       switch (Size) {
2073         default: break;
2074         case 32: MiddleType = Type::Int32Ty; break;
2075         case 16: MiddleType = Type::Int16Ty; break;
2076         case  8: MiddleType = Type::Int8Ty; break;
2077       }
2078       if (MiddleType) {
2079         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2080         InsertNewInstBefore(NewTrunc, I);
2081         return new SExtInst(NewTrunc, I.getType(), I.getName());
2082       }
2083     }
2084   }
2085
2086   if (I.getType() == Type::Int1Ty)
2087     return BinaryOperator::CreateXor(LHS, RHS);
2088
2089   // X + X --> X << 1
2090   if (I.getType()->isInteger()) {
2091     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2092
2093     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2094       if (RHSI->getOpcode() == Instruction::Sub)
2095         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2096           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2097     }
2098     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2099       if (LHSI->getOpcode() == Instruction::Sub)
2100         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2101           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2102     }
2103   }
2104
2105   // -A + B  -->  B - A
2106   // -A + -B  -->  -(A + B)
2107   if (Value *LHSV = dyn_castNegVal(LHS)) {
2108     if (LHS->getType()->isIntOrIntVector()) {
2109       if (Value *RHSV = dyn_castNegVal(RHS)) {
2110         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2111         InsertNewInstBefore(NewAdd, I);
2112         return BinaryOperator::CreateNeg(NewAdd);
2113       }
2114     }
2115     
2116     return BinaryOperator::CreateSub(RHS, LHSV);
2117   }
2118
2119   // A + -B  -->  A - B
2120   if (!isa<Constant>(RHS))
2121     if (Value *V = dyn_castNegVal(RHS))
2122       return BinaryOperator::CreateSub(LHS, V);
2123
2124
2125   ConstantInt *C2;
2126   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2127     if (X == RHS)   // X*C + X --> X * (C+1)
2128       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2129
2130     // X*C1 + X*C2 --> X * (C1+C2)
2131     ConstantInt *C1;
2132     if (X == dyn_castFoldableMul(RHS, C1))
2133       return BinaryOperator::CreateMul(X, Add(C1, C2));
2134   }
2135
2136   // X + X*C --> X * (C+1)
2137   if (dyn_castFoldableMul(RHS, C2) == LHS)
2138     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2139
2140   // X + ~X --> -1   since   ~X = -X-1
2141   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2142     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2143   
2144
2145   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2146   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2147     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2148       return R;
2149   
2150   // A+B --> A|B iff A and B have no bits set in common.
2151   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2152     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2153     APInt LHSKnownOne(IT->getBitWidth(), 0);
2154     APInt LHSKnownZero(IT->getBitWidth(), 0);
2155     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2156     if (LHSKnownZero != 0) {
2157       APInt RHSKnownOne(IT->getBitWidth(), 0);
2158       APInt RHSKnownZero(IT->getBitWidth(), 0);
2159       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2160       
2161       // No bits in common -> bitwise or.
2162       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2163         return BinaryOperator::CreateOr(LHS, RHS);
2164     }
2165   }
2166
2167   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2168   if (I.getType()->isIntOrIntVector()) {
2169     Value *W, *X, *Y, *Z;
2170     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2171         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2172       if (W != Y) {
2173         if (W == Z) {
2174           std::swap(Y, Z);
2175         } else if (Y == X) {
2176           std::swap(W, X);
2177         } else if (X == Z) {
2178           std::swap(Y, Z);
2179           std::swap(W, X);
2180         }
2181       }
2182
2183       if (W == Y) {
2184         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2185                                                             LHS->getName()), I);
2186         return BinaryOperator::CreateMul(W, NewAdd);
2187       }
2188     }
2189   }
2190
2191   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2192     Value *X = 0;
2193     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2194       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2195
2196     // (X & FF00) + xx00  -> (X+xx00) & FF00
2197     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2198       Constant *Anded = And(CRHS, C2);
2199       if (Anded == CRHS) {
2200         // See if all bits from the first bit set in the Add RHS up are included
2201         // in the mask.  First, get the rightmost bit.
2202         const APInt& AddRHSV = CRHS->getValue();
2203
2204         // Form a mask of all bits from the lowest bit added through the top.
2205         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2206
2207         // See if the and mask includes all of these bits.
2208         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2209
2210         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2211           // Okay, the xform is safe.  Insert the new add pronto.
2212           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2213                                                             LHS->getName()), I);
2214           return BinaryOperator::CreateAnd(NewAdd, C2);
2215         }
2216       }
2217     }
2218
2219     // Try to fold constant add into select arguments.
2220     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2221       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2222         return R;
2223   }
2224
2225   // add (cast *A to intptrtype) B -> 
2226   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2227   {
2228     CastInst *CI = dyn_cast<CastInst>(LHS);
2229     Value *Other = RHS;
2230     if (!CI) {
2231       CI = dyn_cast<CastInst>(RHS);
2232       Other = LHS;
2233     }
2234     if (CI && CI->getType()->isSized() && 
2235         (CI->getType()->getPrimitiveSizeInBits() == 
2236          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2237         && isa<PointerType>(CI->getOperand(0)->getType())) {
2238       unsigned AS =
2239         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2240       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2241                                       PointerType::get(Type::Int8Ty, AS), I);
2242       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2243       return new PtrToIntInst(I2, CI->getType());
2244     }
2245   }
2246   
2247   // add (select X 0 (sub n A)) A  -->  select X A n
2248   {
2249     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2250     Value *A = RHS;
2251     if (!SI) {
2252       SI = dyn_cast<SelectInst>(RHS);
2253       A = LHS;
2254     }
2255     if (SI && SI->hasOneUse()) {
2256       Value *TV = SI->getTrueValue();
2257       Value *FV = SI->getFalseValue();
2258       Value *N;
2259
2260       // Can we fold the add into the argument of the select?
2261       // We check both true and false select arguments for a matching subtract.
2262       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2263         // Fold the add into the true select value.
2264         return SelectInst::Create(SI->getCondition(), N, A);
2265       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2266         // Fold the add into the false select value.
2267         return SelectInst::Create(SI->getCondition(), A, N);
2268     }
2269   }
2270   
2271   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2272   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2273     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2274       return ReplaceInstUsesWith(I, LHS);
2275
2276   // Check for (add (sext x), y), see if we can merge this into an
2277   // integer add followed by a sext.
2278   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2279     // (add (sext x), cst) --> (sext (add x, cst'))
2280     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2281       Constant *CI = 
2282         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2283       if (LHSConv->hasOneUse() &&
2284           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2285           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2286         // Insert the new, smaller add.
2287         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2288                                                         CI, "addconv");
2289         InsertNewInstBefore(NewAdd, I);
2290         return new SExtInst(NewAdd, I.getType());
2291       }
2292     }
2293     
2294     // (add (sext x), (sext y)) --> (sext (add int x, y))
2295     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2296       // Only do this if x/y have the same type, if at last one of them has a
2297       // single use (so we don't increase the number of sexts), and if the
2298       // integer add will not overflow.
2299       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2300           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2301           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2302                                    RHSConv->getOperand(0))) {
2303         // Insert the new integer add.
2304         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2305                                                         RHSConv->getOperand(0),
2306                                                         "addconv");
2307         InsertNewInstBefore(NewAdd, I);
2308         return new SExtInst(NewAdd, I.getType());
2309       }
2310     }
2311   }
2312   
2313   // Check for (add double (sitofp x), y), see if we can merge this into an
2314   // integer add followed by a promotion.
2315   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2316     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2317     // ... if the constant fits in the integer value.  This is useful for things
2318     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2319     // requires a constant pool load, and generally allows the add to be better
2320     // instcombined.
2321     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2322       Constant *CI = 
2323       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2324       if (LHSConv->hasOneUse() &&
2325           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2326           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2327         // Insert the new integer add.
2328         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2329                                                         CI, "addconv");
2330         InsertNewInstBefore(NewAdd, I);
2331         return new SIToFPInst(NewAdd, I.getType());
2332       }
2333     }
2334     
2335     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2336     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2337       // Only do this if x/y have the same type, if at last one of them has a
2338       // single use (so we don't increase the number of int->fp conversions),
2339       // and if the integer add will not overflow.
2340       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2341           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2342           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2343                                    RHSConv->getOperand(0))) {
2344         // Insert the new integer add.
2345         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2346                                                         RHSConv->getOperand(0),
2347                                                         "addconv");
2348         InsertNewInstBefore(NewAdd, I);
2349         return new SIToFPInst(NewAdd, I.getType());
2350       }
2351     }
2352   }
2353   
2354   return Changed ? &I : 0;
2355 }
2356
2357 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2358   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2359
2360   if (Op0 == Op1 &&                        // sub X, X  -> 0
2361       !I.getType()->isFPOrFPVector())
2362     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2363
2364   // If this is a 'B = x-(-A)', change to B = x+A...
2365   if (Value *V = dyn_castNegVal(Op1))
2366     return BinaryOperator::CreateAdd(Op0, V);
2367
2368   if (isa<UndefValue>(Op0))
2369     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2370   if (isa<UndefValue>(Op1))
2371     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2372
2373   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2374     // Replace (-1 - A) with (~A)...
2375     if (C->isAllOnesValue())
2376       return BinaryOperator::CreateNot(Op1);
2377
2378     // C - ~X == X + (1+C)
2379     Value *X = 0;
2380     if (match(Op1, m_Not(m_Value(X))))
2381       return BinaryOperator::CreateAdd(X, AddOne(C));
2382
2383     // -(X >>u 31) -> (X >>s 31)
2384     // -(X >>s 31) -> (X >>u 31)
2385     if (C->isZero()) {
2386       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2387         if (SI->getOpcode() == Instruction::LShr) {
2388           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2389             // Check to see if we are shifting out everything but the sign bit.
2390             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2391                 SI->getType()->getPrimitiveSizeInBits()-1) {
2392               // Ok, the transformation is safe.  Insert AShr.
2393               return BinaryOperator::Create(Instruction::AShr, 
2394                                           SI->getOperand(0), CU, SI->getName());
2395             }
2396           }
2397         }
2398         else if (SI->getOpcode() == Instruction::AShr) {
2399           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2400             // Check to see if we are shifting out everything but the sign bit.
2401             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2402                 SI->getType()->getPrimitiveSizeInBits()-1) {
2403               // Ok, the transformation is safe.  Insert LShr. 
2404               return BinaryOperator::CreateLShr(
2405                                           SI->getOperand(0), CU, SI->getName());
2406             }
2407           }
2408         }
2409       }
2410     }
2411
2412     // Try to fold constant sub into select arguments.
2413     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2414       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2415         return R;
2416
2417     if (isa<PHINode>(Op0))
2418       if (Instruction *NV = FoldOpIntoPhi(I))
2419         return NV;
2420   }
2421
2422   if (I.getType() == Type::Int1Ty)
2423     return BinaryOperator::CreateXor(Op0, Op1);
2424
2425   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2426     if (Op1I->getOpcode() == Instruction::Add &&
2427         !Op0->getType()->isFPOrFPVector()) {
2428       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2429         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2430       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2431         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2432       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2433         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2434           // C1-(X+C2) --> (C1-C2)-X
2435           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2436                                            Op1I->getOperand(0));
2437       }
2438     }
2439
2440     if (Op1I->hasOneUse()) {
2441       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2442       // is not used by anyone else...
2443       //
2444       if (Op1I->getOpcode() == Instruction::Sub &&
2445           !Op1I->getType()->isFPOrFPVector()) {
2446         // Swap the two operands of the subexpr...
2447         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2448         Op1I->setOperand(0, IIOp1);
2449         Op1I->setOperand(1, IIOp0);
2450
2451         // Create the new top level add instruction...
2452         return BinaryOperator::CreateAdd(Op0, Op1);
2453       }
2454
2455       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2456       //
2457       if (Op1I->getOpcode() == Instruction::And &&
2458           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2459         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2460
2461         Value *NewNot =
2462           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2463         return BinaryOperator::CreateAnd(Op0, NewNot);
2464       }
2465
2466       // 0 - (X sdiv C)  -> (X sdiv -C)
2467       if (Op1I->getOpcode() == Instruction::SDiv)
2468         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2469           if (CSI->isZero())
2470             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2471               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2472                                                ConstantExpr::getNeg(DivRHS));
2473
2474       // X - X*C --> X * (1-C)
2475       ConstantInt *C2 = 0;
2476       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2477         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2478         return BinaryOperator::CreateMul(Op0, CP1);
2479       }
2480     }
2481   }
2482
2483   if (!Op0->getType()->isFPOrFPVector())
2484     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2485       if (Op0I->getOpcode() == Instruction::Add) {
2486         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2487           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2488         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2489           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2490       } else if (Op0I->getOpcode() == Instruction::Sub) {
2491         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2492           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2493       }
2494     }
2495
2496   ConstantInt *C1;
2497   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2498     if (X == Op1)  // X*C - X --> X * (C-1)
2499       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2500
2501     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2502     if (X == dyn_castFoldableMul(Op1, C2))
2503       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2504   }
2505   return 0;
2506 }
2507
2508 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2509 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2510 /// TrueIfSigned if the result of the comparison is true when the input value is
2511 /// signed.
2512 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2513                            bool &TrueIfSigned) {
2514   switch (pred) {
2515   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2516     TrueIfSigned = true;
2517     return RHS->isZero();
2518   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2519     TrueIfSigned = true;
2520     return RHS->isAllOnesValue();
2521   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2522     TrueIfSigned = false;
2523     return RHS->isAllOnesValue();
2524   case ICmpInst::ICMP_UGT:
2525     // True if LHS u> RHS and RHS == high-bit-mask - 1
2526     TrueIfSigned = true;
2527     return RHS->getValue() ==
2528       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2529   case ICmpInst::ICMP_UGE: 
2530     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2531     TrueIfSigned = true;
2532     return RHS->getValue().isSignBit();
2533   default:
2534     return false;
2535   }
2536 }
2537
2538 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2539   bool Changed = SimplifyCommutative(I);
2540   Value *Op0 = I.getOperand(0);
2541
2542   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2543     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2544
2545   // Simplify mul instructions with a constant RHS...
2546   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2547     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2548
2549       // ((X << C1)*C2) == (X * (C2 << C1))
2550       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2551         if (SI->getOpcode() == Instruction::Shl)
2552           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2553             return BinaryOperator::CreateMul(SI->getOperand(0),
2554                                              ConstantExpr::getShl(CI, ShOp));
2555
2556       if (CI->isZero())
2557         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2558       if (CI->equalsInt(1))                  // X * 1  == X
2559         return ReplaceInstUsesWith(I, Op0);
2560       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2561         return BinaryOperator::CreateNeg(Op0, I.getName());
2562
2563       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2564       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2565         return BinaryOperator::CreateShl(Op0,
2566                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2567       }
2568     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2569       if (Op1F->isNullValue())
2570         return ReplaceInstUsesWith(I, Op1);
2571
2572       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2573       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2574       if (Op1F->isExactlyValue(1.0))
2575         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2576     } else if (isa<VectorType>(Op1->getType())) {
2577       if (isa<ConstantAggregateZero>(Op1))
2578         return ReplaceInstUsesWith(I, Op1);
2579
2580       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2581         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2582           return BinaryOperator::CreateNeg(Op0, I.getName());
2583
2584         // As above, vector X*splat(1.0) -> X in all defined cases.
2585         if (Constant *Splat = Op1V->getSplatValue()) {
2586           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2587             if (F->isExactlyValue(1.0))
2588               return ReplaceInstUsesWith(I, Op0);
2589           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2590             if (CI->equalsInt(1))
2591               return ReplaceInstUsesWith(I, Op0);
2592         }
2593       }
2594     }
2595     
2596     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2597       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2598           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2599         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2600         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2601                                                      Op1, "tmp");
2602         InsertNewInstBefore(Add, I);
2603         Value *C1C2 = ConstantExpr::getMul(Op1, 
2604                                            cast<Constant>(Op0I->getOperand(1)));
2605         return BinaryOperator::CreateAdd(Add, C1C2);
2606         
2607       }
2608
2609     // Try to fold constant mul into select arguments.
2610     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2611       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2612         return R;
2613
2614     if (isa<PHINode>(Op0))
2615       if (Instruction *NV = FoldOpIntoPhi(I))
2616         return NV;
2617   }
2618
2619   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2620     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2621       return BinaryOperator::CreateMul(Op0v, Op1v);
2622
2623   // (X / Y) *  Y = X - (X % Y)
2624   // (X / Y) * -Y = (X % Y) - X
2625   {
2626     Value *Op1 = I.getOperand(1);
2627     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2628     if (!BO ||
2629         (BO->getOpcode() != Instruction::UDiv && 
2630          BO->getOpcode() != Instruction::SDiv)) {
2631       Op1 = Op0;
2632       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2633     }
2634     Value *Neg = dyn_castNegVal(Op1);
2635     if (BO && BO->hasOneUse() &&
2636         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2637         (BO->getOpcode() == Instruction::UDiv ||
2638          BO->getOpcode() == Instruction::SDiv)) {
2639       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2640
2641       Instruction *Rem;
2642       if (BO->getOpcode() == Instruction::UDiv)
2643         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2644       else
2645         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2646
2647       InsertNewInstBefore(Rem, I);
2648       Rem->takeName(BO);
2649
2650       if (Op1BO == Op1)
2651         return BinaryOperator::CreateSub(Op0BO, Rem);
2652       else
2653         return BinaryOperator::CreateSub(Rem, Op0BO);
2654     }
2655   }
2656
2657   if (I.getType() == Type::Int1Ty)
2658     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2659
2660   // If one of the operands of the multiply is a cast from a boolean value, then
2661   // we know the bool is either zero or one, so this is a 'masking' multiply.
2662   // See if we can simplify things based on how the boolean was originally
2663   // formed.
2664   CastInst *BoolCast = 0;
2665   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2666     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2667       BoolCast = CI;
2668   if (!BoolCast)
2669     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2670       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2671         BoolCast = CI;
2672   if (BoolCast) {
2673     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2674       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2675       const Type *SCOpTy = SCIOp0->getType();
2676       bool TIS = false;
2677       
2678       // If the icmp is true iff the sign bit of X is set, then convert this
2679       // multiply into a shift/and combination.
2680       if (isa<ConstantInt>(SCIOp1) &&
2681           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2682           TIS) {
2683         // Shift the X value right to turn it into "all signbits".
2684         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2685                                           SCOpTy->getPrimitiveSizeInBits()-1);
2686         Value *V =
2687           InsertNewInstBefore(
2688             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2689                                             BoolCast->getOperand(0)->getName()+
2690                                             ".mask"), I);
2691
2692         // If the multiply type is not the same as the source type, sign extend
2693         // or truncate to the multiply type.
2694         if (I.getType() != V->getType()) {
2695           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2696           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2697           Instruction::CastOps opcode = 
2698             (SrcBits == DstBits ? Instruction::BitCast : 
2699              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2700           V = InsertCastBefore(opcode, V, I.getType(), I);
2701         }
2702
2703         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2704         return BinaryOperator::CreateAnd(V, OtherOp);
2705       }
2706     }
2707   }
2708
2709   return Changed ? &I : 0;
2710 }
2711
2712 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2713 /// instruction.
2714 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2715   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2716   
2717   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2718   int NonNullOperand = -1;
2719   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2720     if (ST->isNullValue())
2721       NonNullOperand = 2;
2722   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2723   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2724     if (ST->isNullValue())
2725       NonNullOperand = 1;
2726   
2727   if (NonNullOperand == -1)
2728     return false;
2729   
2730   Value *SelectCond = SI->getOperand(0);
2731   
2732   // Change the div/rem to use 'Y' instead of the select.
2733   I.setOperand(1, SI->getOperand(NonNullOperand));
2734   
2735   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2736   // problem.  However, the select, or the condition of the select may have
2737   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2738   // propagate the known value for the select into other uses of it, and
2739   // propagate a known value of the condition into its other users.
2740   
2741   // If the select and condition only have a single use, don't bother with this,
2742   // early exit.
2743   if (SI->use_empty() && SelectCond->hasOneUse())
2744     return true;
2745   
2746   // Scan the current block backward, looking for other uses of SI.
2747   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2748   
2749   while (BBI != BBFront) {
2750     --BBI;
2751     // If we found a call to a function, we can't assume it will return, so
2752     // information from below it cannot be propagated above it.
2753     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2754       break;
2755     
2756     // Replace uses of the select or its condition with the known values.
2757     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2758          I != E; ++I) {
2759       if (*I == SI) {
2760         *I = SI->getOperand(NonNullOperand);
2761         AddToWorkList(BBI);
2762       } else if (*I == SelectCond) {
2763         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2764                                    ConstantInt::getFalse();
2765         AddToWorkList(BBI);
2766       }
2767     }
2768     
2769     // If we past the instruction, quit looking for it.
2770     if (&*BBI == SI)
2771       SI = 0;
2772     if (&*BBI == SelectCond)
2773       SelectCond = 0;
2774     
2775     // If we ran out of things to eliminate, break out of the loop.
2776     if (SelectCond == 0 && SI == 0)
2777       break;
2778     
2779   }
2780   return true;
2781 }
2782
2783
2784 /// This function implements the transforms on div instructions that work
2785 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2786 /// used by the visitors to those instructions.
2787 /// @brief Transforms common to all three div instructions
2788 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2789   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2790
2791   // undef / X -> 0        for integer.
2792   // undef / X -> undef    for FP (the undef could be a snan).
2793   if (isa<UndefValue>(Op0)) {
2794     if (Op0->getType()->isFPOrFPVector())
2795       return ReplaceInstUsesWith(I, Op0);
2796     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2797   }
2798
2799   // X / undef -> undef
2800   if (isa<UndefValue>(Op1))
2801     return ReplaceInstUsesWith(I, Op1);
2802
2803   return 0;
2804 }
2805
2806 /// This function implements the transforms common to both integer division
2807 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2808 /// division instructions.
2809 /// @brief Common integer divide transforms
2810 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2811   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2812
2813   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2814   if (Op0 == Op1) {
2815     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2816       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2817       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2818       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2819     }
2820
2821     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2822     return ReplaceInstUsesWith(I, CI);
2823   }
2824   
2825   if (Instruction *Common = commonDivTransforms(I))
2826     return Common;
2827   
2828   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2829   // This does not apply for fdiv.
2830   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2831     return &I;
2832
2833   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2834     // div X, 1 == X
2835     if (RHS->equalsInt(1))
2836       return ReplaceInstUsesWith(I, Op0);
2837
2838     // (X / C1) / C2  -> X / (C1*C2)
2839     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2840       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2841         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2842           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2843             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2844           else 
2845             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2846                                           Multiply(RHS, LHSRHS));
2847         }
2848
2849     if (!RHS->isZero()) { // avoid X udiv 0
2850       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2851         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2852           return R;
2853       if (isa<PHINode>(Op0))
2854         if (Instruction *NV = FoldOpIntoPhi(I))
2855           return NV;
2856     }
2857   }
2858
2859   // 0 / X == 0, we don't need to preserve faults!
2860   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2861     if (LHS->equalsInt(0))
2862       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2863
2864   // It can't be division by zero, hence it must be division by one.
2865   if (I.getType() == Type::Int1Ty)
2866     return ReplaceInstUsesWith(I, Op0);
2867
2868   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2869     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2870       // div X, 1 == X
2871       if (X->isOne())
2872         return ReplaceInstUsesWith(I, Op0);
2873   }
2874
2875   return 0;
2876 }
2877
2878 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2879   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2880
2881   // Handle the integer div common cases
2882   if (Instruction *Common = commonIDivTransforms(I))
2883     return Common;
2884
2885   // X udiv C^2 -> X >> C
2886   // Check to see if this is an unsigned division with an exact power of 2,
2887   // if so, convert to a right shift.
2888   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2889     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2890       return BinaryOperator::CreateLShr(Op0, 
2891                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2892   }
2893
2894   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2895   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2896     if (RHSI->getOpcode() == Instruction::Shl &&
2897         isa<ConstantInt>(RHSI->getOperand(0))) {
2898       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2899       if (C1.isPowerOf2()) {
2900         Value *N = RHSI->getOperand(1);
2901         const Type *NTy = N->getType();
2902         if (uint32_t C2 = C1.logBase2()) {
2903           Constant *C2V = ConstantInt::get(NTy, C2);
2904           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2905         }
2906         return BinaryOperator::CreateLShr(Op0, N);
2907       }
2908     }
2909   }
2910   
2911   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2912   // where C1&C2 are powers of two.
2913   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2914     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2915       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2916         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2917         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2918           // Compute the shift amounts
2919           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2920           // Construct the "on true" case of the select
2921           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2922           Instruction *TSI = BinaryOperator::CreateLShr(
2923                                                  Op0, TC, SI->getName()+".t");
2924           TSI = InsertNewInstBefore(TSI, I);
2925   
2926           // Construct the "on false" case of the select
2927           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2928           Instruction *FSI = BinaryOperator::CreateLShr(
2929                                                  Op0, FC, SI->getName()+".f");
2930           FSI = InsertNewInstBefore(FSI, I);
2931
2932           // construct the select instruction and return it.
2933           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2934         }
2935       }
2936   return 0;
2937 }
2938
2939 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2940   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2941
2942   // Handle the integer div common cases
2943   if (Instruction *Common = commonIDivTransforms(I))
2944     return Common;
2945
2946   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2947     // sdiv X, -1 == -X
2948     if (RHS->isAllOnesValue())
2949       return BinaryOperator::CreateNeg(Op0);
2950
2951     // -X/C -> X/-C
2952     if (Value *LHSNeg = dyn_castNegVal(Op0))
2953       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2954   }
2955
2956   // If the sign bits of both operands are zero (i.e. we can prove they are
2957   // unsigned inputs), turn this into a udiv.
2958   if (I.getType()->isInteger()) {
2959     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2960     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2961       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2962       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2963     }
2964   }      
2965   
2966   return 0;
2967 }
2968
2969 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2970   return commonDivTransforms(I);
2971 }
2972
2973 /// This function implements the transforms on rem instructions that work
2974 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2975 /// is used by the visitors to those instructions.
2976 /// @brief Transforms common to all three rem instructions
2977 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2978   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2979
2980   // 0 % X == 0 for integer, we don't need to preserve faults!
2981   if (Constant *LHS = dyn_cast<Constant>(Op0))
2982     if (LHS->isNullValue())
2983       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2984
2985   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2986     if (I.getType()->isFPOrFPVector())
2987       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2988     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2989   }
2990   if (isa<UndefValue>(Op1))
2991     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2992
2993   // Handle cases involving: rem X, (select Cond, Y, Z)
2994   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2995     return &I;
2996
2997   return 0;
2998 }
2999
3000 /// This function implements the transforms common to both integer remainder
3001 /// instructions (urem and srem). It is called by the visitors to those integer
3002 /// remainder instructions.
3003 /// @brief Common integer remainder transforms
3004 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3005   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3006
3007   if (Instruction *common = commonRemTransforms(I))
3008     return common;
3009
3010   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3011     // X % 0 == undef, we don't need to preserve faults!
3012     if (RHS->equalsInt(0))
3013       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3014     
3015     if (RHS->equalsInt(1))  // X % 1 == 0
3016       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3017
3018     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3019       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3020         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3021           return R;
3022       } else if (isa<PHINode>(Op0I)) {
3023         if (Instruction *NV = FoldOpIntoPhi(I))
3024           return NV;
3025       }
3026
3027       // See if we can fold away this rem instruction.
3028       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3029       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3030       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3031                                KnownZero, KnownOne))
3032         return &I;
3033     }
3034   }
3035
3036   return 0;
3037 }
3038
3039 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3040   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3041
3042   if (Instruction *common = commonIRemTransforms(I))
3043     return common;
3044   
3045   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3046     // X urem C^2 -> X and C
3047     // Check to see if this is an unsigned remainder with an exact power of 2,
3048     // if so, convert to a bitwise and.
3049     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3050       if (C->getValue().isPowerOf2())
3051         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3052   }
3053
3054   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3055     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3056     if (RHSI->getOpcode() == Instruction::Shl &&
3057         isa<ConstantInt>(RHSI->getOperand(0))) {
3058       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3059         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3060         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3061                                                                    "tmp"), I);
3062         return BinaryOperator::CreateAnd(Op0, Add);
3063       }
3064     }
3065   }
3066
3067   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3068   // where C1&C2 are powers of two.
3069   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3070     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3071       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3072         // STO == 0 and SFO == 0 handled above.
3073         if ((STO->getValue().isPowerOf2()) && 
3074             (SFO->getValue().isPowerOf2())) {
3075           Value *TrueAnd = InsertNewInstBefore(
3076             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3077           Value *FalseAnd = InsertNewInstBefore(
3078             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3079           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3080         }
3081       }
3082   }
3083   
3084   return 0;
3085 }
3086
3087 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3088   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3089
3090   // Handle the integer rem common cases
3091   if (Instruction *common = commonIRemTransforms(I))
3092     return common;
3093   
3094   if (Value *RHSNeg = dyn_castNegVal(Op1))
3095     if (!isa<Constant>(RHSNeg) ||
3096         (isa<ConstantInt>(RHSNeg) &&
3097          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3098       // X % -Y -> X % Y
3099       AddUsesToWorkList(I);
3100       I.setOperand(1, RHSNeg);
3101       return &I;
3102     }
3103
3104   // If the sign bits of both operands are zero (i.e. we can prove they are
3105   // unsigned inputs), turn this into a urem.
3106   if (I.getType()->isInteger()) {
3107     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3108     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3109       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3110       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3111     }
3112   }
3113
3114   return 0;
3115 }
3116
3117 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3118   return commonRemTransforms(I);
3119 }
3120
3121 // isOneBitSet - Return true if there is exactly one bit set in the specified
3122 // constant.
3123 static bool isOneBitSet(const ConstantInt *CI) {
3124   return CI->getValue().isPowerOf2();
3125 }
3126
3127 // isHighOnes - Return true if the constant is of the form 1+0+.
3128 // This is the same as lowones(~X).
3129 static bool isHighOnes(const ConstantInt *CI) {
3130   return (~CI->getValue() + 1).isPowerOf2();
3131 }
3132
3133 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3134 /// are carefully arranged to allow folding of expressions such as:
3135 ///
3136 ///      (A < B) | (A > B) --> (A != B)
3137 ///
3138 /// Note that this is only valid if the first and second predicates have the
3139 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3140 ///
3141 /// Three bits are used to represent the condition, as follows:
3142 ///   0  A > B
3143 ///   1  A == B
3144 ///   2  A < B
3145 ///
3146 /// <=>  Value  Definition
3147 /// 000     0   Always false
3148 /// 001     1   A >  B
3149 /// 010     2   A == B
3150 /// 011     3   A >= B
3151 /// 100     4   A <  B
3152 /// 101     5   A != B
3153 /// 110     6   A <= B
3154 /// 111     7   Always true
3155 ///  
3156 static unsigned getICmpCode(const ICmpInst *ICI) {
3157   switch (ICI->getPredicate()) {
3158     // False -> 0
3159   case ICmpInst::ICMP_UGT: return 1;  // 001
3160   case ICmpInst::ICMP_SGT: return 1;  // 001
3161   case ICmpInst::ICMP_EQ:  return 2;  // 010
3162   case ICmpInst::ICMP_UGE: return 3;  // 011
3163   case ICmpInst::ICMP_SGE: return 3;  // 011
3164   case ICmpInst::ICMP_ULT: return 4;  // 100
3165   case ICmpInst::ICMP_SLT: return 4;  // 100
3166   case ICmpInst::ICMP_NE:  return 5;  // 101
3167   case ICmpInst::ICMP_ULE: return 6;  // 110
3168   case ICmpInst::ICMP_SLE: return 6;  // 110
3169     // True -> 7
3170   default:
3171     assert(0 && "Invalid ICmp predicate!");
3172     return 0;
3173   }
3174 }
3175
3176 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3177 /// predicate into a three bit mask. It also returns whether it is an ordered
3178 /// predicate by reference.
3179 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3180   isOrdered = false;
3181   switch (CC) {
3182   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3183   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3184   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3185   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3186   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3187   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3188   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3189   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3190   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3191   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3192   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3193   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3194   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3195   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3196     // True -> 7
3197   default:
3198     // Not expecting FCMP_FALSE and FCMP_TRUE;
3199     assert(0 && "Unexpected FCmp predicate!");
3200     return 0;
3201   }
3202 }
3203
3204 /// getICmpValue - This is the complement of getICmpCode, which turns an
3205 /// opcode and two operands into either a constant true or false, or a brand 
3206 /// new ICmp instruction. The sign is passed in to determine which kind
3207 /// of predicate to use in the new icmp instruction.
3208 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3209   switch (code) {
3210   default: assert(0 && "Illegal ICmp code!");
3211   case  0: return ConstantInt::getFalse();
3212   case  1: 
3213     if (sign)
3214       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3215     else
3216       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3217   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3218   case  3: 
3219     if (sign)
3220       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3221     else
3222       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3223   case  4: 
3224     if (sign)
3225       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3226     else
3227       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3228   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3229   case  6: 
3230     if (sign)
3231       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3232     else
3233       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3234   case  7: return ConstantInt::getTrue();
3235   }
3236 }
3237
3238 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3239 /// opcode and two operands into either a FCmp instruction. isordered is passed
3240 /// in to determine which kind of predicate to use in the new fcmp instruction.
3241 static Value *getFCmpValue(bool isordered, unsigned code,
3242                            Value *LHS, Value *RHS) {
3243   switch (code) {
3244   default: assert(0 && "Illegal FCmp code!");
3245   case  0:
3246     if (isordered)
3247       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3248     else
3249       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3250   case  1: 
3251     if (isordered)
3252       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3253     else
3254       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3255   case  2: 
3256     if (isordered)
3257       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3258     else
3259       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3260   case  3: 
3261     if (isordered)
3262       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3263     else
3264       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3265   case  4: 
3266     if (isordered)
3267       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3268     else
3269       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3270   case  5: 
3271     if (isordered)
3272       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3273     else
3274       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3275   case  6: 
3276     if (isordered)
3277       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3278     else
3279       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3280   case  7: return ConstantInt::getTrue();
3281   }
3282 }
3283
3284 /// PredicatesFoldable - Return true if both predicates match sign or if at
3285 /// least one of them is an equality comparison (which is signless).
3286 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3287   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3288          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3289          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3290 }
3291
3292 namespace { 
3293 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3294 struct FoldICmpLogical {
3295   InstCombiner &IC;
3296   Value *LHS, *RHS;
3297   ICmpInst::Predicate pred;
3298   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3299     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3300       pred(ICI->getPredicate()) {}
3301   bool shouldApply(Value *V) const {
3302     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3303       if (PredicatesFoldable(pred, ICI->getPredicate()))
3304         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3305                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3306     return false;
3307   }
3308   Instruction *apply(Instruction &Log) const {
3309     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3310     if (ICI->getOperand(0) != LHS) {
3311       assert(ICI->getOperand(1) == LHS);
3312       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3313     }
3314
3315     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3316     unsigned LHSCode = getICmpCode(ICI);
3317     unsigned RHSCode = getICmpCode(RHSICI);
3318     unsigned Code;
3319     switch (Log.getOpcode()) {
3320     case Instruction::And: Code = LHSCode & RHSCode; break;
3321     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3322     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3323     default: assert(0 && "Illegal logical opcode!"); return 0;
3324     }
3325
3326     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3327                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3328       
3329     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3330     if (Instruction *I = dyn_cast<Instruction>(RV))
3331       return I;
3332     // Otherwise, it's a constant boolean value...
3333     return IC.ReplaceInstUsesWith(Log, RV);
3334   }
3335 };
3336 } // end anonymous namespace
3337
3338 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3339 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3340 // guaranteed to be a binary operator.
3341 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3342                                     ConstantInt *OpRHS,
3343                                     ConstantInt *AndRHS,
3344                                     BinaryOperator &TheAnd) {
3345   Value *X = Op->getOperand(0);
3346   Constant *Together = 0;
3347   if (!Op->isShift())
3348     Together = And(AndRHS, OpRHS);
3349
3350   switch (Op->getOpcode()) {
3351   case Instruction::Xor:
3352     if (Op->hasOneUse()) {
3353       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3354       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3355       InsertNewInstBefore(And, TheAnd);
3356       And->takeName(Op);
3357       return BinaryOperator::CreateXor(And, Together);
3358     }
3359     break;
3360   case Instruction::Or:
3361     if (Together == AndRHS) // (X | C) & C --> C
3362       return ReplaceInstUsesWith(TheAnd, AndRHS);
3363
3364     if (Op->hasOneUse() && Together != OpRHS) {
3365       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3366       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3367       InsertNewInstBefore(Or, TheAnd);
3368       Or->takeName(Op);
3369       return BinaryOperator::CreateAnd(Or, AndRHS);
3370     }
3371     break;
3372   case Instruction::Add:
3373     if (Op->hasOneUse()) {
3374       // Adding a one to a single bit bit-field should be turned into an XOR
3375       // of the bit.  First thing to check is to see if this AND is with a
3376       // single bit constant.
3377       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3378
3379       // If there is only one bit set...
3380       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3381         // Ok, at this point, we know that we are masking the result of the
3382         // ADD down to exactly one bit.  If the constant we are adding has
3383         // no bits set below this bit, then we can eliminate the ADD.
3384         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3385
3386         // Check to see if any bits below the one bit set in AndRHSV are set.
3387         if ((AddRHS & (AndRHSV-1)) == 0) {
3388           // If not, the only thing that can effect the output of the AND is
3389           // the bit specified by AndRHSV.  If that bit is set, the effect of
3390           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3391           // no effect.
3392           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3393             TheAnd.setOperand(0, X);
3394             return &TheAnd;
3395           } else {
3396             // Pull the XOR out of the AND.
3397             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3398             InsertNewInstBefore(NewAnd, TheAnd);
3399             NewAnd->takeName(Op);
3400             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3401           }
3402         }
3403       }
3404     }
3405     break;
3406
3407   case Instruction::Shl: {
3408     // We know that the AND will not produce any of the bits shifted in, so if
3409     // the anded constant includes them, clear them now!
3410     //
3411     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3412     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3413     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3414     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3415
3416     if (CI->getValue() == ShlMask) { 
3417     // Masking out bits that the shift already masks
3418       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3419     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3420       TheAnd.setOperand(1, CI);
3421       return &TheAnd;
3422     }
3423     break;
3424   }
3425   case Instruction::LShr:
3426   {
3427     // We know that the AND will not produce any of the bits shifted in, so if
3428     // the anded constant includes them, clear them now!  This only applies to
3429     // unsigned shifts, because a signed shr may bring in set bits!
3430     //
3431     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3432     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3433     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3434     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3435
3436     if (CI->getValue() == ShrMask) {   
3437     // Masking out bits that the shift already masks.
3438       return ReplaceInstUsesWith(TheAnd, Op);
3439     } else if (CI != AndRHS) {
3440       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3441       return &TheAnd;
3442     }
3443     break;
3444   }
3445   case Instruction::AShr:
3446     // Signed shr.
3447     // See if this is shifting in some sign extension, then masking it out
3448     // with an and.
3449     if (Op->hasOneUse()) {
3450       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3451       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3452       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3453       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3454       if (C == AndRHS) {          // Masking out bits shifted in.
3455         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3456         // Make the argument unsigned.
3457         Value *ShVal = Op->getOperand(0);
3458         ShVal = InsertNewInstBefore(
3459             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3460                                    Op->getName()), TheAnd);
3461         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3462       }
3463     }
3464     break;
3465   }
3466   return 0;
3467 }
3468
3469
3470 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3471 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3472 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3473 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3474 /// insert new instructions.
3475 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3476                                            bool isSigned, bool Inside, 
3477                                            Instruction &IB) {
3478   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3479             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3480          "Lo is not <= Hi in range emission code!");
3481     
3482   if (Inside) {
3483     if (Lo == Hi)  // Trivially false.
3484       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3485
3486     // V >= Min && V < Hi --> V < Hi
3487     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3488       ICmpInst::Predicate pred = (isSigned ? 
3489         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3490       return new ICmpInst(pred, V, Hi);
3491     }
3492
3493     // Emit V-Lo <u Hi-Lo
3494     Constant *NegLo = ConstantExpr::getNeg(Lo);
3495     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3496     InsertNewInstBefore(Add, IB);
3497     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3498     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3499   }
3500
3501   if (Lo == Hi)  // Trivially true.
3502     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3503
3504   // V < Min || V >= Hi -> V > Hi-1
3505   Hi = SubOne(cast<ConstantInt>(Hi));
3506   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3507     ICmpInst::Predicate pred = (isSigned ? 
3508         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3509     return new ICmpInst(pred, V, Hi);
3510   }
3511
3512   // Emit V-Lo >u Hi-1-Lo
3513   // Note that Hi has already had one subtracted from it, above.
3514   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3515   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3516   InsertNewInstBefore(Add, IB);
3517   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3518   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3519 }
3520
3521 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3522 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3523 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3524 // not, since all 1s are not contiguous.
3525 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3526   const APInt& V = Val->getValue();
3527   uint32_t BitWidth = Val->getType()->getBitWidth();
3528   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3529
3530   // look for the first zero bit after the run of ones
3531   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3532   // look for the first non-zero bit
3533   ME = V.getActiveBits(); 
3534   return true;
3535 }
3536
3537 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3538 /// where isSub determines whether the operator is a sub.  If we can fold one of
3539 /// the following xforms:
3540 /// 
3541 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3542 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3543 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3544 ///
3545 /// return (A +/- B).
3546 ///
3547 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3548                                         ConstantInt *Mask, bool isSub,
3549                                         Instruction &I) {
3550   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3551   if (!LHSI || LHSI->getNumOperands() != 2 ||
3552       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3553
3554   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3555
3556   switch (LHSI->getOpcode()) {
3557   default: return 0;
3558   case Instruction::And:
3559     if (And(N, Mask) == Mask) {
3560       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3561       if ((Mask->getValue().countLeadingZeros() + 
3562            Mask->getValue().countPopulation()) == 
3563           Mask->getValue().getBitWidth())
3564         break;
3565
3566       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3567       // part, we don't need any explicit masks to take them out of A.  If that
3568       // is all N is, ignore it.
3569       uint32_t MB = 0, ME = 0;
3570       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3571         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3572         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3573         if (MaskedValueIsZero(RHS, Mask))
3574           break;
3575       }
3576     }
3577     return 0;
3578   case Instruction::Or:
3579   case Instruction::Xor:
3580     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3581     if ((Mask->getValue().countLeadingZeros() + 
3582          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3583         && And(N, Mask)->isZero())
3584       break;
3585     return 0;
3586   }
3587   
3588   Instruction *New;
3589   if (isSub)
3590     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3591   else
3592     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3593   return InsertNewInstBefore(New, I);
3594 }
3595
3596 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3597 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3598                                           ICmpInst *LHS, ICmpInst *RHS) {
3599   Value *Val, *Val2;
3600   ConstantInt *LHSCst, *RHSCst;
3601   ICmpInst::Predicate LHSCC, RHSCC;
3602   
3603   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3604   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3605       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3606     return 0;
3607   
3608   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3609   // where C is a power of 2
3610   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3611       LHSCst->getValue().isPowerOf2()) {
3612     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3613     InsertNewInstBefore(NewOr, I);
3614     return new ICmpInst(LHSCC, NewOr, LHSCst);
3615   }
3616   
3617   // From here on, we only handle:
3618   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3619   if (Val != Val2) return 0;
3620   
3621   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3622   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3623       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3624       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3625       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3626     return 0;
3627   
3628   // We can't fold (ugt x, C) & (sgt x, C2).
3629   if (!PredicatesFoldable(LHSCC, RHSCC))
3630     return 0;
3631     
3632   // Ensure that the larger constant is on the RHS.
3633   bool ShouldSwap;
3634   if (ICmpInst::isSignedPredicate(LHSCC) ||
3635       (ICmpInst::isEquality(LHSCC) && 
3636        ICmpInst::isSignedPredicate(RHSCC)))
3637     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3638   else
3639     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3640     
3641   if (ShouldSwap) {
3642     std::swap(LHS, RHS);
3643     std::swap(LHSCst, RHSCst);
3644     std::swap(LHSCC, RHSCC);
3645   }
3646
3647   // At this point, we know we have have two icmp instructions
3648   // comparing a value against two constants and and'ing the result
3649   // together.  Because of the above check, we know that we only have
3650   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3651   // (from the FoldICmpLogical check above), that the two constants 
3652   // are not equal and that the larger constant is on the RHS
3653   assert(LHSCst != RHSCst && "Compares not folded above?");
3654
3655   switch (LHSCC) {
3656   default: assert(0 && "Unknown integer condition code!");
3657   case ICmpInst::ICMP_EQ:
3658     switch (RHSCC) {
3659     default: assert(0 && "Unknown integer condition code!");
3660     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3661     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3662     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3663       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3664     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3665     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3666     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3667       return ReplaceInstUsesWith(I, LHS);
3668     }
3669   case ICmpInst::ICMP_NE:
3670     switch (RHSCC) {
3671     default: assert(0 && "Unknown integer condition code!");
3672     case ICmpInst::ICMP_ULT:
3673       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3674         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3675       break;                        // (X != 13 & X u< 15) -> no change
3676     case ICmpInst::ICMP_SLT:
3677       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3678         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3679       break;                        // (X != 13 & X s< 15) -> no change
3680     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3681     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3682     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3683       return ReplaceInstUsesWith(I, RHS);
3684     case ICmpInst::ICMP_NE:
3685       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3686         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3687         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3688                                                      Val->getName()+".off");
3689         InsertNewInstBefore(Add, I);
3690         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3691                             ConstantInt::get(Add->getType(), 1));
3692       }
3693       break;                        // (X != 13 & X != 15) -> no change
3694     }
3695     break;
3696   case ICmpInst::ICMP_ULT:
3697     switch (RHSCC) {
3698     default: assert(0 && "Unknown integer condition code!");
3699     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3700     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3701       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3702     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3703       break;
3704     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3705     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3706       return ReplaceInstUsesWith(I, LHS);
3707     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3708       break;
3709     }
3710     break;
3711   case ICmpInst::ICMP_SLT:
3712     switch (RHSCC) {
3713     default: assert(0 && "Unknown integer condition code!");
3714     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3715     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3716       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3717     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3718       break;
3719     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3720     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3721       return ReplaceInstUsesWith(I, LHS);
3722     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3723       break;
3724     }
3725     break;
3726   case ICmpInst::ICMP_UGT:
3727     switch (RHSCC) {
3728     default: assert(0 && "Unknown integer condition code!");
3729     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3730     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3731       return ReplaceInstUsesWith(I, RHS);
3732     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3733       break;
3734     case ICmpInst::ICMP_NE:
3735       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3736         return new ICmpInst(LHSCC, Val, RHSCst);
3737       break;                        // (X u> 13 & X != 15) -> no change
3738     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3739       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3740     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3741       break;
3742     }
3743     break;
3744   case ICmpInst::ICMP_SGT:
3745     switch (RHSCC) {
3746     default: assert(0 && "Unknown integer condition code!");
3747     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3748     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3749       return ReplaceInstUsesWith(I, RHS);
3750     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3751       break;
3752     case ICmpInst::ICMP_NE:
3753       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3754         return new ICmpInst(LHSCC, Val, RHSCst);
3755       break;                        // (X s> 13 & X != 15) -> no change
3756     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3757       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3758     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3759       break;
3760     }
3761     break;
3762   }
3763  
3764   return 0;
3765 }
3766
3767
3768 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3769   bool Changed = SimplifyCommutative(I);
3770   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3771
3772   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3773     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3774
3775   // and X, X = X
3776   if (Op0 == Op1)
3777     return ReplaceInstUsesWith(I, Op1);
3778
3779   // See if we can simplify any instructions used by the instruction whose sole 
3780   // purpose is to compute bits we don't care about.
3781   if (!isa<VectorType>(I.getType())) {
3782     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3783     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3784     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3785                              KnownZero, KnownOne))
3786       return &I;
3787   } else {
3788     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3789       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3790         return ReplaceInstUsesWith(I, I.getOperand(0));
3791     } else if (isa<ConstantAggregateZero>(Op1)) {
3792       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3793     }
3794   }
3795   
3796   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3797     const APInt& AndRHSMask = AndRHS->getValue();
3798     APInt NotAndRHS(~AndRHSMask);
3799
3800     // Optimize a variety of ((val OP C1) & C2) combinations...
3801     if (isa<BinaryOperator>(Op0)) {
3802       Instruction *Op0I = cast<Instruction>(Op0);
3803       Value *Op0LHS = Op0I->getOperand(0);
3804       Value *Op0RHS = Op0I->getOperand(1);
3805       switch (Op0I->getOpcode()) {
3806       case Instruction::Xor:
3807       case Instruction::Or:
3808         // If the mask is only needed on one incoming arm, push it up.
3809         if (Op0I->hasOneUse()) {
3810           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3811             // Not masking anything out for the LHS, move to RHS.
3812             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3813                                                    Op0RHS->getName()+".masked");
3814             InsertNewInstBefore(NewRHS, I);
3815             return BinaryOperator::Create(
3816                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3817           }
3818           if (!isa<Constant>(Op0RHS) &&
3819               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3820             // Not masking anything out for the RHS, move to LHS.
3821             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3822                                                    Op0LHS->getName()+".masked");
3823             InsertNewInstBefore(NewLHS, I);
3824             return BinaryOperator::Create(
3825                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3826           }
3827         }
3828
3829         break;
3830       case Instruction::Add:
3831         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3832         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3833         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3834         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3835           return BinaryOperator::CreateAnd(V, AndRHS);
3836         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3837           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3838         break;
3839
3840       case Instruction::Sub:
3841         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3842         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3843         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3844         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3845           return BinaryOperator::CreateAnd(V, AndRHS);
3846
3847         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3848         // has 1's for all bits that the subtraction with A might affect.
3849         if (Op0I->hasOneUse()) {
3850           uint32_t BitWidth = AndRHSMask.getBitWidth();
3851           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3852           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3853
3854           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3855           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3856               MaskedValueIsZero(Op0LHS, Mask)) {
3857             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3858             InsertNewInstBefore(NewNeg, I);
3859             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3860           }
3861         }
3862         break;
3863
3864       case Instruction::Shl:
3865       case Instruction::LShr:
3866         // (1 << x) & 1 --> zext(x == 0)
3867         // (1 >> x) & 1 --> zext(x == 0)
3868         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3869           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3870                                            Constant::getNullValue(I.getType()));
3871           InsertNewInstBefore(NewICmp, I);
3872           return new ZExtInst(NewICmp, I.getType());
3873         }
3874         break;
3875       }
3876
3877       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3878         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3879           return Res;
3880     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3881       // If this is an integer truncation or change from signed-to-unsigned, and
3882       // if the source is an and/or with immediate, transform it.  This
3883       // frequently occurs for bitfield accesses.
3884       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3885         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3886             CastOp->getNumOperands() == 2)
3887           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3888             if (CastOp->getOpcode() == Instruction::And) {
3889               // Change: and (cast (and X, C1) to T), C2
3890               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3891               // This will fold the two constants together, which may allow 
3892               // other simplifications.
3893               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3894                 CastOp->getOperand(0), I.getType(), 
3895                 CastOp->getName()+".shrunk");
3896               NewCast = InsertNewInstBefore(NewCast, I);
3897               // trunc_or_bitcast(C1)&C2
3898               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3899               C3 = ConstantExpr::getAnd(C3, AndRHS);
3900               return BinaryOperator::CreateAnd(NewCast, C3);
3901             } else if (CastOp->getOpcode() == Instruction::Or) {
3902               // Change: and (cast (or X, C1) to T), C2
3903               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3904               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3905               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3906                 return ReplaceInstUsesWith(I, AndRHS);
3907             }
3908           }
3909       }
3910     }
3911
3912     // Try to fold constant and into select arguments.
3913     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3914       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3915         return R;
3916     if (isa<PHINode>(Op0))
3917       if (Instruction *NV = FoldOpIntoPhi(I))
3918         return NV;
3919   }
3920
3921   Value *Op0NotVal = dyn_castNotVal(Op0);
3922   Value *Op1NotVal = dyn_castNotVal(Op1);
3923
3924   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3925     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3926
3927   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3928   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3929     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3930                                                I.getName()+".demorgan");
3931     InsertNewInstBefore(Or, I);
3932     return BinaryOperator::CreateNot(Or);
3933   }
3934   
3935   {
3936     Value *A = 0, *B = 0, *C = 0, *D = 0;
3937     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3938       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3939         return ReplaceInstUsesWith(I, Op1);
3940     
3941       // (A|B) & ~(A&B) -> A^B
3942       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3943         if ((A == C && B == D) || (A == D && B == C))
3944           return BinaryOperator::CreateXor(A, B);
3945       }
3946     }
3947     
3948     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3949       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3950         return ReplaceInstUsesWith(I, Op0);
3951
3952       // ~(A&B) & (A|B) -> A^B
3953       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3954         if ((A == C && B == D) || (A == D && B == C))
3955           return BinaryOperator::CreateXor(A, B);
3956       }
3957     }
3958     
3959     if (Op0->hasOneUse() &&
3960         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3961       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3962         I.swapOperands();     // Simplify below
3963         std::swap(Op0, Op1);
3964       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3965         cast<BinaryOperator>(Op0)->swapOperands();
3966         I.swapOperands();     // Simplify below
3967         std::swap(Op0, Op1);
3968       }
3969     }
3970     if (Op1->hasOneUse() &&
3971         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3972       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3973         cast<BinaryOperator>(Op1)->swapOperands();
3974         std::swap(A, B);
3975       }
3976       if (A == Op0) {                                // A&(A^B) -> A & ~B
3977         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3978         InsertNewInstBefore(NotB, I);
3979         return BinaryOperator::CreateAnd(A, NotB);
3980       }
3981     }
3982   }
3983   
3984   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3985     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3986     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3987       return R;
3988
3989     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
3990       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
3991         return Res;
3992   }
3993
3994   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3995   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3996     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3997       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3998         const Type *SrcTy = Op0C->getOperand(0)->getType();
3999         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4000             // Only do this if the casts both really cause code to be generated.
4001             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4002                               I.getType(), TD) &&
4003             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4004                               I.getType(), TD)) {
4005           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4006                                                          Op1C->getOperand(0),
4007                                                          I.getName());
4008           InsertNewInstBefore(NewOp, I);
4009           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4010         }
4011       }
4012     
4013   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4014   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4015     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4016       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4017           SI0->getOperand(1) == SI1->getOperand(1) &&
4018           (SI0->hasOneUse() || SI1->hasOneUse())) {
4019         Instruction *NewOp =
4020           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4021                                                         SI1->getOperand(0),
4022                                                         SI0->getName()), I);
4023         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4024                                       SI1->getOperand(1));
4025       }
4026   }
4027
4028   // If and'ing two fcmp, try combine them into one.
4029   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4030     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4031       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4032           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4033         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4034         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4035           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4036             // If either of the constants are nans, then the whole thing returns
4037             // false.
4038             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4039               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4040             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4041                                 RHS->getOperand(0));
4042           }
4043       } else {
4044         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4045         FCmpInst::Predicate Op0CC, Op1CC;
4046         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4047             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4048           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4049             // Swap RHS operands to match LHS.
4050             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4051             std::swap(Op1LHS, Op1RHS);
4052           }
4053           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4054             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4055             if (Op0CC == Op1CC)
4056               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4057             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4058                      Op1CC == FCmpInst::FCMP_FALSE)
4059               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4060             else if (Op0CC == FCmpInst::FCMP_TRUE)
4061               return ReplaceInstUsesWith(I, Op1);
4062             else if (Op1CC == FCmpInst::FCMP_TRUE)
4063               return ReplaceInstUsesWith(I, Op0);
4064             bool Op0Ordered;
4065             bool Op1Ordered;
4066             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4067             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4068             if (Op1Pred == 0) {
4069               std::swap(Op0, Op1);
4070               std::swap(Op0Pred, Op1Pred);
4071               std::swap(Op0Ordered, Op1Ordered);
4072             }
4073             if (Op0Pred == 0) {
4074               // uno && ueq -> uno && (uno || eq) -> ueq
4075               // ord && olt -> ord && (ord && lt) -> olt
4076               if (Op0Ordered == Op1Ordered)
4077                 return ReplaceInstUsesWith(I, Op1);
4078               // uno && oeq -> uno && (ord && eq) -> false
4079               // uno && ord -> false
4080               if (!Op0Ordered)
4081                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4082               // ord && ueq -> ord && (uno || eq) -> oeq
4083               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4084                                                     Op0LHS, Op0RHS));
4085             }
4086           }
4087         }
4088       }
4089     }
4090   }
4091
4092   return Changed ? &I : 0;
4093 }
4094
4095 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4096 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4097 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4098 /// the expression came from the corresponding "byte swapped" byte in some other
4099 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4100 /// we know that the expression deposits the low byte of %X into the high byte
4101 /// of the bswap result and that all other bytes are zero.  This expression is
4102 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4103 /// match.
4104 ///
4105 /// This function returns true if the match was unsuccessful and false if so.
4106 /// On entry to the function the "OverallLeftShift" is a signed integer value
4107 /// indicating the number of bytes that the subexpression is later shifted.  For
4108 /// example, if the expression is later right shifted by 16 bits, the
4109 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4110 /// byte of ByteValues is actually being set.
4111 ///
4112 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4113 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4114 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4115 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4116 /// always in the local (OverallLeftShift) coordinate space.
4117 ///
4118 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4119                               SmallVector<Value*, 8> &ByteValues) {
4120   if (Instruction *I = dyn_cast<Instruction>(V)) {
4121     // If this is an or instruction, it may be an inner node of the bswap.
4122     if (I->getOpcode() == Instruction::Or) {
4123       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4124                                ByteValues) ||
4125              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4126                                ByteValues);
4127     }
4128   
4129     // If this is a logical shift by a constant multiple of 8, recurse with
4130     // OverallLeftShift and ByteMask adjusted.
4131     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4132       unsigned ShAmt = 
4133         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4134       // Ensure the shift amount is defined and of a byte value.
4135       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4136         return true;
4137
4138       unsigned ByteShift = ShAmt >> 3;
4139       if (I->getOpcode() == Instruction::Shl) {
4140         // X << 2 -> collect(X, +2)
4141         OverallLeftShift += ByteShift;
4142         ByteMask >>= ByteShift;
4143       } else {
4144         // X >>u 2 -> collect(X, -2)
4145         OverallLeftShift -= ByteShift;
4146         ByteMask <<= ByteShift;
4147         ByteMask &= (~0U >> (32-ByteValues.size()));
4148       }
4149
4150       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4151       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4152
4153       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4154                                ByteValues);
4155     }
4156
4157     // If this is a logical 'and' with a mask that clears bytes, clear the
4158     // corresponding bytes in ByteMask.
4159     if (I->getOpcode() == Instruction::And &&
4160         isa<ConstantInt>(I->getOperand(1))) {
4161       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4162       unsigned NumBytes = ByteValues.size();
4163       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4164       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4165       
4166       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4167         // If this byte is masked out by a later operation, we don't care what
4168         // the and mask is.
4169         if ((ByteMask & (1 << i)) == 0)
4170           continue;
4171         
4172         // If the AndMask is all zeros for this byte, clear the bit.
4173         APInt MaskB = AndMask & Byte;
4174         if (MaskB == 0) {
4175           ByteMask &= ~(1U << i);
4176           continue;
4177         }
4178         
4179         // If the AndMask is not all ones for this byte, it's not a bytezap.
4180         if (MaskB != Byte)
4181           return true;
4182
4183         // Otherwise, this byte is kept.
4184       }
4185
4186       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4187                                ByteValues);
4188     }
4189   }
4190   
4191   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4192   // the input value to the bswap.  Some observations: 1) if more than one byte
4193   // is demanded from this input, then it could not be successfully assembled
4194   // into a byteswap.  At least one of the two bytes would not be aligned with
4195   // their ultimate destination.
4196   if (!isPowerOf2_32(ByteMask)) return true;
4197   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4198   
4199   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4200   // is demanded, it needs to go into byte 0 of the result.  This means that the
4201   // byte needs to be shifted until it lands in the right byte bucket.  The
4202   // shift amount depends on the position: if the byte is coming from the high
4203   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4204   // low part, it must be shifted left.
4205   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4206   if (InputByteNo < ByteValues.size()/2) {
4207     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4208       return true;
4209   } else {
4210     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4211       return true;
4212   }
4213   
4214   // If the destination byte value is already defined, the values are or'd
4215   // together, which isn't a bswap (unless it's an or of the same bits).
4216   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4217     return true;
4218   ByteValues[DestByteNo] = V;
4219   return false;
4220 }
4221
4222 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4223 /// If so, insert the new bswap intrinsic and return it.
4224 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4225   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4226   if (!ITy || ITy->getBitWidth() % 16 || 
4227       // ByteMask only allows up to 32-byte values.
4228       ITy->getBitWidth() > 32*8) 
4229     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4230   
4231   /// ByteValues - For each byte of the result, we keep track of which value
4232   /// defines each byte.
4233   SmallVector<Value*, 8> ByteValues;
4234   ByteValues.resize(ITy->getBitWidth()/8);
4235     
4236   // Try to find all the pieces corresponding to the bswap.
4237   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4238   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4239     return 0;
4240   
4241   // Check to see if all of the bytes come from the same value.
4242   Value *V = ByteValues[0];
4243   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4244   
4245   // Check to make sure that all of the bytes come from the same value.
4246   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4247     if (ByteValues[i] != V)
4248       return 0;
4249   const Type *Tys[] = { ITy };
4250   Module *M = I.getParent()->getParent()->getParent();
4251   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4252   return CallInst::Create(F, V);
4253 }
4254
4255 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4256 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4257 /// we can simplify this expression to "cond ? C : D or B".
4258 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4259                                          Value *C, Value *D) {
4260   // If A is not a select of -1/0, this cannot match.
4261   Value *Cond = 0;
4262   if (!match(A, m_SelectCst(m_Value(Cond), -1, 0)))
4263     return 0;
4264
4265   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4266   if (match(D, m_SelectCst(m_Specific(Cond), 0, -1)))
4267     return SelectInst::Create(Cond, C, B);
4268   if (match(D, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4269     return SelectInst::Create(Cond, C, B);
4270   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4271   if (match(B, m_SelectCst(m_Specific(Cond), 0, -1)))
4272     return SelectInst::Create(Cond, C, D);
4273   if (match(B, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4274     return SelectInst::Create(Cond, C, D);
4275   return 0;
4276 }
4277
4278 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4279 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4280                                          ICmpInst *LHS, ICmpInst *RHS) {
4281   Value *Val, *Val2;
4282   ConstantInt *LHSCst, *RHSCst;
4283   ICmpInst::Predicate LHSCC, RHSCC;
4284   
4285   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4286   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4287       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4288     return 0;
4289   
4290   // From here on, we only handle:
4291   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4292   if (Val != Val2) return 0;
4293   
4294   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4295   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4296       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4297       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4298       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4299     return 0;
4300   
4301   // We can't fold (ugt x, C) | (sgt x, C2).
4302   if (!PredicatesFoldable(LHSCC, RHSCC))
4303     return 0;
4304   
4305   // Ensure that the larger constant is on the RHS.
4306   bool ShouldSwap;
4307   if (ICmpInst::isSignedPredicate(LHSCC) ||
4308       (ICmpInst::isEquality(LHSCC) && 
4309        ICmpInst::isSignedPredicate(RHSCC)))
4310     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4311   else
4312     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4313   
4314   if (ShouldSwap) {
4315     std::swap(LHS, RHS);
4316     std::swap(LHSCst, RHSCst);
4317     std::swap(LHSCC, RHSCC);
4318   }
4319   
4320   // At this point, we know we have have two icmp instructions
4321   // comparing a value against two constants and or'ing the result
4322   // together.  Because of the above check, we know that we only have
4323   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4324   // FoldICmpLogical check above), that the two constants are not
4325   // equal.
4326   assert(LHSCst != RHSCst && "Compares not folded above?");
4327
4328   switch (LHSCC) {
4329   default: assert(0 && "Unknown integer condition code!");
4330   case ICmpInst::ICMP_EQ:
4331     switch (RHSCC) {
4332     default: assert(0 && "Unknown integer condition code!");
4333     case ICmpInst::ICMP_EQ:
4334       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4335         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4336         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4337                                                      Val->getName()+".off");
4338         InsertNewInstBefore(Add, I);
4339         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4340         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4341       }
4342       break;                         // (X == 13 | X == 15) -> no change
4343     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4344     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4345       break;
4346     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4347     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4348     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4349       return ReplaceInstUsesWith(I, RHS);
4350     }
4351     break;
4352   case ICmpInst::ICMP_NE:
4353     switch (RHSCC) {
4354     default: assert(0 && "Unknown integer condition code!");
4355     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4356     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4357     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4358       return ReplaceInstUsesWith(I, LHS);
4359     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4360     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4361     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4362       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4363     }
4364     break;
4365   case ICmpInst::ICMP_ULT:
4366     switch (RHSCC) {
4367     default: assert(0 && "Unknown integer condition code!");
4368     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4369       break;
4370     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4371       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4372       // this can cause overflow.
4373       if (RHSCst->isMaxValue(false))
4374         return ReplaceInstUsesWith(I, LHS);
4375       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4376     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4377       break;
4378     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4379     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4380       return ReplaceInstUsesWith(I, RHS);
4381     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4382       break;
4383     }
4384     break;
4385   case ICmpInst::ICMP_SLT:
4386     switch (RHSCC) {
4387     default: assert(0 && "Unknown integer condition code!");
4388     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4389       break;
4390     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4391       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4392       // this can cause overflow.
4393       if (RHSCst->isMaxValue(true))
4394         return ReplaceInstUsesWith(I, LHS);
4395       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4396     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4397       break;
4398     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4399     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4400       return ReplaceInstUsesWith(I, RHS);
4401     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4402       break;
4403     }
4404     break;
4405   case ICmpInst::ICMP_UGT:
4406     switch (RHSCC) {
4407     default: assert(0 && "Unknown integer condition code!");
4408     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4409     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4410       return ReplaceInstUsesWith(I, LHS);
4411     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4412       break;
4413     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4414     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4415       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4416     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4417       break;
4418     }
4419     break;
4420   case ICmpInst::ICMP_SGT:
4421     switch (RHSCC) {
4422     default: assert(0 && "Unknown integer condition code!");
4423     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4424     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4425       return ReplaceInstUsesWith(I, LHS);
4426     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4427       break;
4428     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4429     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4430       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4431     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4432       break;
4433     }
4434     break;
4435   }
4436   return 0;
4437 }
4438
4439 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4440   bool Changed = SimplifyCommutative(I);
4441   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4442
4443   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4444     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4445
4446   // or X, X = X
4447   if (Op0 == Op1)
4448     return ReplaceInstUsesWith(I, Op0);
4449
4450   // See if we can simplify any instructions used by the instruction whose sole 
4451   // purpose is to compute bits we don't care about.
4452   if (!isa<VectorType>(I.getType())) {
4453     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4454     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4455     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4456                              KnownZero, KnownOne))
4457       return &I;
4458   } else if (isa<ConstantAggregateZero>(Op1)) {
4459     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4460   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4461     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4462       return ReplaceInstUsesWith(I, I.getOperand(1));
4463   }
4464     
4465
4466   
4467   // or X, -1 == -1
4468   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4469     ConstantInt *C1 = 0; Value *X = 0;
4470     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4471     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4472       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4473       InsertNewInstBefore(Or, I);
4474       Or->takeName(Op0);
4475       return BinaryOperator::CreateAnd(Or, 
4476                ConstantInt::get(RHS->getValue() | C1->getValue()));
4477     }
4478
4479     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4480     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4481       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4482       InsertNewInstBefore(Or, I);
4483       Or->takeName(Op0);
4484       return BinaryOperator::CreateXor(Or,
4485                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4486     }
4487
4488     // Try to fold constant and into select arguments.
4489     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4490       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4491         return R;
4492     if (isa<PHINode>(Op0))
4493       if (Instruction *NV = FoldOpIntoPhi(I))
4494         return NV;
4495   }
4496
4497   Value *A = 0, *B = 0;
4498   ConstantInt *C1 = 0, *C2 = 0;
4499
4500   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4501     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4502       return ReplaceInstUsesWith(I, Op1);
4503   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4504     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4505       return ReplaceInstUsesWith(I, Op0);
4506
4507   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4508   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4509   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4510       match(Op1, m_Or(m_Value(), m_Value())) ||
4511       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4512        match(Op1, m_Shift(m_Value(), m_Value())))) {
4513     if (Instruction *BSwap = MatchBSwap(I))
4514       return BSwap;
4515   }
4516   
4517   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4518   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4519       MaskedValueIsZero(Op1, C1->getValue())) {
4520     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4521     InsertNewInstBefore(NOr, I);
4522     NOr->takeName(Op0);
4523     return BinaryOperator::CreateXor(NOr, C1);
4524   }
4525
4526   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4527   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4528       MaskedValueIsZero(Op0, C1->getValue())) {
4529     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4530     InsertNewInstBefore(NOr, I);
4531     NOr->takeName(Op0);
4532     return BinaryOperator::CreateXor(NOr, C1);
4533   }
4534
4535   // (A & C)|(B & D)
4536   Value *C = 0, *D = 0;
4537   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4538       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4539     Value *V1 = 0, *V2 = 0, *V3 = 0;
4540     C1 = dyn_cast<ConstantInt>(C);
4541     C2 = dyn_cast<ConstantInt>(D);
4542     if (C1 && C2) {  // (A & C1)|(B & C2)
4543       // If we have: ((V + N) & C1) | (V & C2)
4544       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4545       // replace with V+N.
4546       if (C1->getValue() == ~C2->getValue()) {
4547         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4548             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4549           // Add commutes, try both ways.
4550           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4551             return ReplaceInstUsesWith(I, A);
4552           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4553             return ReplaceInstUsesWith(I, A);
4554         }
4555         // Or commutes, try both ways.
4556         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4557             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4558           // Add commutes, try both ways.
4559           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4560             return ReplaceInstUsesWith(I, B);
4561           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4562             return ReplaceInstUsesWith(I, B);
4563         }
4564       }
4565       V1 = 0; V2 = 0; V3 = 0;
4566     }
4567     
4568     // Check to see if we have any common things being and'ed.  If so, find the
4569     // terms for V1 & (V2|V3).
4570     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4571       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4572         V1 = A, V2 = C, V3 = D;
4573       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4574         V1 = A, V2 = B, V3 = C;
4575       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4576         V1 = C, V2 = A, V3 = D;
4577       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4578         V1 = C, V2 = A, V3 = B;
4579       
4580       if (V1) {
4581         Value *Or =
4582           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4583         return BinaryOperator::CreateAnd(V1, Or);
4584       }
4585     }
4586
4587     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4588     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4589       return Match;
4590     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4591       return Match;
4592     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4593       return Match;
4594     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4595       return Match;
4596   }
4597   
4598   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4599   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4600     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4601       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4602           SI0->getOperand(1) == SI1->getOperand(1) &&
4603           (SI0->hasOneUse() || SI1->hasOneUse())) {
4604         Instruction *NewOp =
4605         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4606                                                      SI1->getOperand(0),
4607                                                      SI0->getName()), I);
4608         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4609                                       SI1->getOperand(1));
4610       }
4611   }
4612
4613   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4614     if (A == Op1)   // ~A | A == -1
4615       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4616   } else {
4617     A = 0;
4618   }
4619   // Note, A is still live here!
4620   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4621     if (Op0 == B)
4622       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4623
4624     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4625     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4626       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4627                                               I.getName()+".demorgan"), I);
4628       return BinaryOperator::CreateNot(And);
4629     }
4630   }
4631
4632   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4633   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4634     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4635       return R;
4636
4637     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4638       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4639         return Res;
4640   }
4641     
4642   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4643   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4644     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4645       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4646         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4647             !isa<ICmpInst>(Op1C->getOperand(0))) {
4648           const Type *SrcTy = Op0C->getOperand(0)->getType();
4649           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4650               // Only do this if the casts both really cause code to be
4651               // generated.
4652               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4653                                 I.getType(), TD) &&
4654               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4655                                 I.getType(), TD)) {
4656             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4657                                                           Op1C->getOperand(0),
4658                                                           I.getName());
4659             InsertNewInstBefore(NewOp, I);
4660             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4661           }
4662         }
4663       }
4664   }
4665   
4666     
4667   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4668   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4669     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4670       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4671           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4672           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4673         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4674           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4675             // If either of the constants are nans, then the whole thing returns
4676             // true.
4677             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4678               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4679             
4680             // Otherwise, no need to compare the two constants, compare the
4681             // rest.
4682             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4683                                 RHS->getOperand(0));
4684           }
4685       } else {
4686         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4687         FCmpInst::Predicate Op0CC, Op1CC;
4688         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4689             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4690           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4691             // Swap RHS operands to match LHS.
4692             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4693             std::swap(Op1LHS, Op1RHS);
4694           }
4695           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4696             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4697             if (Op0CC == Op1CC)
4698               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4699             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4700                      Op1CC == FCmpInst::FCMP_TRUE)
4701               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4702             else if (Op0CC == FCmpInst::FCMP_FALSE)
4703               return ReplaceInstUsesWith(I, Op1);
4704             else if (Op1CC == FCmpInst::FCMP_FALSE)
4705               return ReplaceInstUsesWith(I, Op0);
4706             bool Op0Ordered;
4707             bool Op1Ordered;
4708             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4709             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4710             if (Op0Ordered == Op1Ordered) {
4711               // If both are ordered or unordered, return a new fcmp with
4712               // or'ed predicates.
4713               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4714                                        Op0LHS, Op0RHS);
4715               if (Instruction *I = dyn_cast<Instruction>(RV))
4716                 return I;
4717               // Otherwise, it's a constant boolean value...
4718               return ReplaceInstUsesWith(I, RV);
4719             }
4720           }
4721         }
4722       }
4723     }
4724   }
4725
4726   return Changed ? &I : 0;
4727 }
4728
4729 namespace {
4730
4731 // XorSelf - Implements: X ^ X --> 0
4732 struct XorSelf {
4733   Value *RHS;
4734   XorSelf(Value *rhs) : RHS(rhs) {}
4735   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4736   Instruction *apply(BinaryOperator &Xor) const {
4737     return &Xor;
4738   }
4739 };
4740
4741 }
4742
4743 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4744   bool Changed = SimplifyCommutative(I);
4745   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4746
4747   if (isa<UndefValue>(Op1)) {
4748     if (isa<UndefValue>(Op0))
4749       // Handle undef ^ undef -> 0 special case. This is a common
4750       // idiom (misuse).
4751       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4752     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4753   }
4754
4755   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4756   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4757     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4758     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4759   }
4760   
4761   // See if we can simplify any instructions used by the instruction whose sole 
4762   // purpose is to compute bits we don't care about.
4763   if (!isa<VectorType>(I.getType())) {
4764     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4765     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4766     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4767                              KnownZero, KnownOne))
4768       return &I;
4769   } else if (isa<ConstantAggregateZero>(Op1)) {
4770     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4771   }
4772
4773   // Is this a ~ operation?
4774   if (Value *NotOp = dyn_castNotVal(&I)) {
4775     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4776     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4777     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4778       if (Op0I->getOpcode() == Instruction::And || 
4779           Op0I->getOpcode() == Instruction::Or) {
4780         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4781         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4782           Instruction *NotY =
4783             BinaryOperator::CreateNot(Op0I->getOperand(1),
4784                                       Op0I->getOperand(1)->getName()+".not");
4785           InsertNewInstBefore(NotY, I);
4786           if (Op0I->getOpcode() == Instruction::And)
4787             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4788           else
4789             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4790         }
4791       }
4792     }
4793   }
4794   
4795   
4796   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4797     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4798     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4799       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4800         return new ICmpInst(ICI->getInversePredicate(),
4801                             ICI->getOperand(0), ICI->getOperand(1));
4802
4803       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4804         return new FCmpInst(FCI->getInversePredicate(),
4805                             FCI->getOperand(0), FCI->getOperand(1));
4806     }
4807
4808     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4809     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4810       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4811         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4812           Instruction::CastOps Opcode = Op0C->getOpcode();
4813           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4814             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4815                                              Op0C->getDestTy())) {
4816               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4817                                      CI->getOpcode(), CI->getInversePredicate(),
4818                                      CI->getOperand(0), CI->getOperand(1)), I);
4819               NewCI->takeName(CI);
4820               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4821             }
4822           }
4823         }
4824       }
4825     }
4826
4827     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4828       // ~(c-X) == X-c-1 == X+(-c-1)
4829       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4830         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4831           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4832           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4833                                               ConstantInt::get(I.getType(), 1));
4834           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4835         }
4836           
4837       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4838         if (Op0I->getOpcode() == Instruction::Add) {
4839           // ~(X-c) --> (-c-1)-X
4840           if (RHS->isAllOnesValue()) {
4841             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4842             return BinaryOperator::CreateSub(
4843                            ConstantExpr::getSub(NegOp0CI,
4844                                              ConstantInt::get(I.getType(), 1)),
4845                                           Op0I->getOperand(0));
4846           } else if (RHS->getValue().isSignBit()) {
4847             // (X + C) ^ signbit -> (X + C + signbit)
4848             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4849             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4850
4851           }
4852         } else if (Op0I->getOpcode() == Instruction::Or) {
4853           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4854           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4855             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4856             // Anything in both C1 and C2 is known to be zero, remove it from
4857             // NewRHS.
4858             Constant *CommonBits = And(Op0CI, RHS);
4859             NewRHS = ConstantExpr::getAnd(NewRHS, 
4860                                           ConstantExpr::getNot(CommonBits));
4861             AddToWorkList(Op0I);
4862             I.setOperand(0, Op0I->getOperand(0));
4863             I.setOperand(1, NewRHS);
4864             return &I;
4865           }
4866         }
4867       }
4868     }
4869
4870     // Try to fold constant and into select arguments.
4871     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4872       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4873         return R;
4874     if (isa<PHINode>(Op0))
4875       if (Instruction *NV = FoldOpIntoPhi(I))
4876         return NV;
4877   }
4878
4879   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4880     if (X == Op1)
4881       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4882
4883   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4884     if (X == Op0)
4885       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4886
4887   
4888   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4889   if (Op1I) {
4890     Value *A, *B;
4891     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4892       if (A == Op0) {              // B^(B|A) == (A|B)^B
4893         Op1I->swapOperands();
4894         I.swapOperands();
4895         std::swap(Op0, Op1);
4896       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4897         I.swapOperands();     // Simplified below.
4898         std::swap(Op0, Op1);
4899       }
4900     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4901       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
4902     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4903       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
4904     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4905       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4906         Op1I->swapOperands();
4907         std::swap(A, B);
4908       }
4909       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4910         I.swapOperands();     // Simplified below.
4911         std::swap(Op0, Op1);
4912       }
4913     }
4914   }
4915   
4916   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4917   if (Op0I) {
4918     Value *A, *B;
4919     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4920       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4921         std::swap(A, B);
4922       if (B == Op1) {                                // (A|B)^B == A & ~B
4923         Instruction *NotB =
4924           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4925         return BinaryOperator::CreateAnd(A, NotB);
4926       }
4927     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
4928       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
4929     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
4930       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
4931     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4932       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4933         std::swap(A, B);
4934       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4935           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4936         Instruction *N =
4937           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4938         return BinaryOperator::CreateAnd(N, Op1);
4939       }
4940     }
4941   }
4942   
4943   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4944   if (Op0I && Op1I && Op0I->isShift() && 
4945       Op0I->getOpcode() == Op1I->getOpcode() && 
4946       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4947       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4948     Instruction *NewOp =
4949       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4950                                                     Op1I->getOperand(0),
4951                                                     Op0I->getName()), I);
4952     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4953                                   Op1I->getOperand(1));
4954   }
4955     
4956   if (Op0I && Op1I) {
4957     Value *A, *B, *C, *D;
4958     // (A & B)^(A | B) -> A ^ B
4959     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4960         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4961       if ((A == C && B == D) || (A == D && B == C)) 
4962         return BinaryOperator::CreateXor(A, B);
4963     }
4964     // (A | B)^(A & B) -> A ^ B
4965     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4966         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4967       if ((A == C && B == D) || (A == D && B == C)) 
4968         return BinaryOperator::CreateXor(A, B);
4969     }
4970     
4971     // (A & B)^(C & D)
4972     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4973         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4974         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4975       // (X & Y)^(X & Y) -> (Y^Z) & X
4976       Value *X = 0, *Y = 0, *Z = 0;
4977       if (A == C)
4978         X = A, Y = B, Z = D;
4979       else if (A == D)
4980         X = A, Y = B, Z = C;
4981       else if (B == C)
4982         X = B, Y = A, Z = D;
4983       else if (B == D)
4984         X = B, Y = A, Z = C;
4985       
4986       if (X) {
4987         Instruction *NewOp =
4988         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4989         return BinaryOperator::CreateAnd(NewOp, X);
4990       }
4991     }
4992   }
4993     
4994   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4995   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4996     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4997       return R;
4998
4999   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5000   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5001     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5002       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5003         const Type *SrcTy = Op0C->getOperand(0)->getType();
5004         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5005             // Only do this if the casts both really cause code to be generated.
5006             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5007                               I.getType(), TD) &&
5008             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5009                               I.getType(), TD)) {
5010           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5011                                                          Op1C->getOperand(0),
5012                                                          I.getName());
5013           InsertNewInstBefore(NewOp, I);
5014           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5015         }
5016       }
5017   }
5018
5019   return Changed ? &I : 0;
5020 }
5021
5022 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5023 /// overflowed for this type.
5024 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5025                             ConstantInt *In2, bool IsSigned = false) {
5026   Result = cast<ConstantInt>(Add(In1, In2));
5027
5028   if (IsSigned)
5029     if (In2->getValue().isNegative())
5030       return Result->getValue().sgt(In1->getValue());
5031     else
5032       return Result->getValue().slt(In1->getValue());
5033   else
5034     return Result->getValue().ult(In1->getValue());
5035 }
5036
5037 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5038 /// overflowed for this type.
5039 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5040                             ConstantInt *In2, bool IsSigned = false) {
5041   Result = cast<ConstantInt>(Subtract(In1, In2));
5042
5043   if (IsSigned)
5044     if (In2->getValue().isNegative())
5045       return Result->getValue().slt(In1->getValue());
5046     else
5047       return Result->getValue().sgt(In1->getValue());
5048   else
5049     return Result->getValue().ugt(In1->getValue());
5050 }
5051
5052 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5053 /// code necessary to compute the offset from the base pointer (without adding
5054 /// in the base pointer).  Return the result as a signed integer of intptr size.
5055 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5056   TargetData &TD = IC.getTargetData();
5057   gep_type_iterator GTI = gep_type_begin(GEP);
5058   const Type *IntPtrTy = TD.getIntPtrType();
5059   Value *Result = Constant::getNullValue(IntPtrTy);
5060
5061   // Build a mask for high order bits.
5062   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5063   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5064
5065   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5066        ++i, ++GTI) {
5067     Value *Op = *i;
5068     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5069     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5070       if (OpC->isZero()) continue;
5071       
5072       // Handle a struct index, which adds its field offset to the pointer.
5073       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5074         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5075         
5076         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5077           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5078         else
5079           Result = IC.InsertNewInstBefore(
5080                    BinaryOperator::CreateAdd(Result,
5081                                              ConstantInt::get(IntPtrTy, Size),
5082                                              GEP->getName()+".offs"), I);
5083         continue;
5084       }
5085       
5086       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5087       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5088       Scale = ConstantExpr::getMul(OC, Scale);
5089       if (Constant *RC = dyn_cast<Constant>(Result))
5090         Result = ConstantExpr::getAdd(RC, Scale);
5091       else {
5092         // Emit an add instruction.
5093         Result = IC.InsertNewInstBefore(
5094            BinaryOperator::CreateAdd(Result, Scale,
5095                                      GEP->getName()+".offs"), I);
5096       }
5097       continue;
5098     }
5099     // Convert to correct type.
5100     if (Op->getType() != IntPtrTy) {
5101       if (Constant *OpC = dyn_cast<Constant>(Op))
5102         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5103       else
5104         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5105                                                  Op->getName()+".c"), I);
5106     }
5107     if (Size != 1) {
5108       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5109       if (Constant *OpC = dyn_cast<Constant>(Op))
5110         Op = ConstantExpr::getMul(OpC, Scale);
5111       else    // We'll let instcombine(mul) convert this to a shl if possible.
5112         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5113                                                   GEP->getName()+".idx"), I);
5114     }
5115
5116     // Emit an add instruction.
5117     if (isa<Constant>(Op) && isa<Constant>(Result))
5118       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5119                                     cast<Constant>(Result));
5120     else
5121       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5122                                                   GEP->getName()+".offs"), I);
5123   }
5124   return Result;
5125 }
5126
5127
5128 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5129 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5130 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5131 /// complex, and scales are involved.  The above expression would also be legal
5132 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5133 /// later form is less amenable to optimization though, and we are allowed to
5134 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5135 ///
5136 /// If we can't emit an optimized form for this expression, this returns null.
5137 /// 
5138 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5139                                           InstCombiner &IC) {
5140   TargetData &TD = IC.getTargetData();
5141   gep_type_iterator GTI = gep_type_begin(GEP);
5142
5143   // Check to see if this gep only has a single variable index.  If so, and if
5144   // any constant indices are a multiple of its scale, then we can compute this
5145   // in terms of the scale of the variable index.  For example, if the GEP
5146   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5147   // because the expression will cross zero at the same point.
5148   unsigned i, e = GEP->getNumOperands();
5149   int64_t Offset = 0;
5150   for (i = 1; i != e; ++i, ++GTI) {
5151     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5152       // Compute the aggregate offset of constant indices.
5153       if (CI->isZero()) continue;
5154
5155       // Handle a struct index, which adds its field offset to the pointer.
5156       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5157         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5158       } else {
5159         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5160         Offset += Size*CI->getSExtValue();
5161       }
5162     } else {
5163       // Found our variable index.
5164       break;
5165     }
5166   }
5167   
5168   // If there are no variable indices, we must have a constant offset, just
5169   // evaluate it the general way.
5170   if (i == e) return 0;
5171   
5172   Value *VariableIdx = GEP->getOperand(i);
5173   // Determine the scale factor of the variable element.  For example, this is
5174   // 4 if the variable index is into an array of i32.
5175   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5176   
5177   // Verify that there are no other variable indices.  If so, emit the hard way.
5178   for (++i, ++GTI; i != e; ++i, ++GTI) {
5179     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5180     if (!CI) return 0;
5181    
5182     // Compute the aggregate offset of constant indices.
5183     if (CI->isZero()) continue;
5184     
5185     // Handle a struct index, which adds its field offset to the pointer.
5186     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5187       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5188     } else {
5189       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5190       Offset += Size*CI->getSExtValue();
5191     }
5192   }
5193   
5194   // Okay, we know we have a single variable index, which must be a
5195   // pointer/array/vector index.  If there is no offset, life is simple, return
5196   // the index.
5197   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5198   if (Offset == 0) {
5199     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5200     // we don't need to bother extending: the extension won't affect where the
5201     // computation crosses zero.
5202     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5203       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5204                                   VariableIdx->getNameStart(), &I);
5205     return VariableIdx;
5206   }
5207   
5208   // Otherwise, there is an index.  The computation we will do will be modulo
5209   // the pointer size, so get it.
5210   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5211   
5212   Offset &= PtrSizeMask;
5213   VariableScale &= PtrSizeMask;
5214
5215   // To do this transformation, any constant index must be a multiple of the
5216   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5217   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5218   // multiple of the variable scale.
5219   int64_t NewOffs = Offset / (int64_t)VariableScale;
5220   if (Offset != NewOffs*(int64_t)VariableScale)
5221     return 0;
5222
5223   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5224   const Type *IntPtrTy = TD.getIntPtrType();
5225   if (VariableIdx->getType() != IntPtrTy)
5226     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5227                                               true /*SExt*/, 
5228                                               VariableIdx->getNameStart(), &I);
5229   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5230   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5231 }
5232
5233
5234 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5235 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5236 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5237                                        ICmpInst::Predicate Cond,
5238                                        Instruction &I) {
5239   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5240
5241   // Look through bitcasts.
5242   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5243     RHS = BCI->getOperand(0);
5244
5245   Value *PtrBase = GEPLHS->getOperand(0);
5246   if (PtrBase == RHS) {
5247     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5248     // This transformation (ignoring the base and scales) is valid because we
5249     // know pointers can't overflow.  See if we can output an optimized form.
5250     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5251     
5252     // If not, synthesize the offset the hard way.
5253     if (Offset == 0)
5254       Offset = EmitGEPOffset(GEPLHS, I, *this);
5255     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5256                         Constant::getNullValue(Offset->getType()));
5257   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5258     // If the base pointers are different, but the indices are the same, just
5259     // compare the base pointer.
5260     if (PtrBase != GEPRHS->getOperand(0)) {
5261       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5262       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5263                         GEPRHS->getOperand(0)->getType();
5264       if (IndicesTheSame)
5265         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5266           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5267             IndicesTheSame = false;
5268             break;
5269           }
5270
5271       // If all indices are the same, just compare the base pointers.
5272       if (IndicesTheSame)
5273         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5274                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5275
5276       // Otherwise, the base pointers are different and the indices are
5277       // different, bail out.
5278       return 0;
5279     }
5280
5281     // If one of the GEPs has all zero indices, recurse.
5282     bool AllZeros = true;
5283     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5284       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5285           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5286         AllZeros = false;
5287         break;
5288       }
5289     if (AllZeros)
5290       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5291                           ICmpInst::getSwappedPredicate(Cond), I);
5292
5293     // If the other GEP has all zero indices, recurse.
5294     AllZeros = true;
5295     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5296       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5297           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5298         AllZeros = false;
5299         break;
5300       }
5301     if (AllZeros)
5302       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5303
5304     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5305       // If the GEPs only differ by one index, compare it.
5306       unsigned NumDifferences = 0;  // Keep track of # differences.
5307       unsigned DiffOperand = 0;     // The operand that differs.
5308       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5309         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5310           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5311                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5312             // Irreconcilable differences.
5313             NumDifferences = 2;
5314             break;
5315           } else {
5316             if (NumDifferences++) break;
5317             DiffOperand = i;
5318           }
5319         }
5320
5321       if (NumDifferences == 0)   // SAME GEP?
5322         return ReplaceInstUsesWith(I, // No comparison is needed here.
5323                                    ConstantInt::get(Type::Int1Ty,
5324                                              ICmpInst::isTrueWhenEqual(Cond)));
5325
5326       else if (NumDifferences == 1) {
5327         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5328         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5329         // Make sure we do a signed comparison here.
5330         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5331       }
5332     }
5333
5334     // Only lower this if the icmp is the only user of the GEP or if we expect
5335     // the result to fold to a constant!
5336     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5337         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5338       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5339       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5340       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5341       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5342     }
5343   }
5344   return 0;
5345 }
5346
5347 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5348 ///
5349 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5350                                                 Instruction *LHSI,
5351                                                 Constant *RHSC) {
5352   if (!isa<ConstantFP>(RHSC)) return 0;
5353   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5354   
5355   // Get the width of the mantissa.  We don't want to hack on conversions that
5356   // might lose information from the integer, e.g. "i64 -> float"
5357   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5358   if (MantissaWidth == -1) return 0;  // Unknown.
5359   
5360   // Check to see that the input is converted from an integer type that is small
5361   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5362   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5363   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5364   
5365   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5366   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5367   if (LHSUnsigned)
5368     ++InputSize;
5369   
5370   // If the conversion would lose info, don't hack on this.
5371   if ((int)InputSize > MantissaWidth)
5372     return 0;
5373   
5374   // Otherwise, we can potentially simplify the comparison.  We know that it
5375   // will always come through as an integer value and we know the constant is
5376   // not a NAN (it would have been previously simplified).
5377   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5378   
5379   ICmpInst::Predicate Pred;
5380   switch (I.getPredicate()) {
5381   default: assert(0 && "Unexpected predicate!");
5382   case FCmpInst::FCMP_UEQ:
5383   case FCmpInst::FCMP_OEQ:
5384     Pred = ICmpInst::ICMP_EQ;
5385     break;
5386   case FCmpInst::FCMP_UGT:
5387   case FCmpInst::FCMP_OGT:
5388     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5389     break;
5390   case FCmpInst::FCMP_UGE:
5391   case FCmpInst::FCMP_OGE:
5392     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5393     break;
5394   case FCmpInst::FCMP_ULT:
5395   case FCmpInst::FCMP_OLT:
5396     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5397     break;
5398   case FCmpInst::FCMP_ULE:
5399   case FCmpInst::FCMP_OLE:
5400     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5401     break;
5402   case FCmpInst::FCMP_UNE:
5403   case FCmpInst::FCMP_ONE:
5404     Pred = ICmpInst::ICMP_NE;
5405     break;
5406   case FCmpInst::FCMP_ORD:
5407     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5408   case FCmpInst::FCMP_UNO:
5409     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5410   }
5411   
5412   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5413   
5414   // Now we know that the APFloat is a normal number, zero or inf.
5415   
5416   // See if the FP constant is too large for the integer.  For example,
5417   // comparing an i8 to 300.0.
5418   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5419   
5420   if (!LHSUnsigned) {
5421     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5422     // and large values.
5423     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5424     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5425                           APFloat::rmNearestTiesToEven);
5426     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5427       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5428           Pred == ICmpInst::ICMP_SLE)
5429         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5430       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5431     }
5432   } else {
5433     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5434     // +INF and large values.
5435     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5436     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5437                           APFloat::rmNearestTiesToEven);
5438     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5439       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5440           Pred == ICmpInst::ICMP_ULE)
5441         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5442       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5443     }
5444   }
5445   
5446   if (!LHSUnsigned) {
5447     // See if the RHS value is < SignedMin.
5448     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5449     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5450                           APFloat::rmNearestTiesToEven);
5451     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5452       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5453           Pred == ICmpInst::ICMP_SGE)
5454         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5455       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5456     }
5457   }
5458
5459   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5460   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5461   // casting the FP value to the integer value and back, checking for equality.
5462   // Don't do this for zero, because -0.0 is not fractional.
5463   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5464   if (!RHS.isZero() &&
5465       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5466     // If we had a comparison against a fractional value, we have to adjust the
5467     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5468     // at this point.
5469     switch (Pred) {
5470     default: assert(0 && "Unexpected integer comparison!");
5471     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5472       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5473     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5474       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5475     case ICmpInst::ICMP_ULE:
5476       // (float)int <= 4.4   --> int <= 4
5477       // (float)int <= -4.4  --> false
5478       if (RHS.isNegative())
5479         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5480       break;
5481     case ICmpInst::ICMP_SLE:
5482       // (float)int <= 4.4   --> int <= 4
5483       // (float)int <= -4.4  --> int < -4
5484       if (RHS.isNegative())
5485         Pred = ICmpInst::ICMP_SLT;
5486       break;
5487     case ICmpInst::ICMP_ULT:
5488       // (float)int < -4.4   --> false
5489       // (float)int < 4.4    --> int <= 4
5490       if (RHS.isNegative())
5491         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5492       Pred = ICmpInst::ICMP_ULE;
5493       break;
5494     case ICmpInst::ICMP_SLT:
5495       // (float)int < -4.4   --> int < -4
5496       // (float)int < 4.4    --> int <= 4
5497       if (!RHS.isNegative())
5498         Pred = ICmpInst::ICMP_SLE;
5499       break;
5500     case ICmpInst::ICMP_UGT:
5501       // (float)int > 4.4    --> int > 4
5502       // (float)int > -4.4   --> true
5503       if (RHS.isNegative())
5504         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5505       break;
5506     case ICmpInst::ICMP_SGT:
5507       // (float)int > 4.4    --> int > 4
5508       // (float)int > -4.4   --> int >= -4
5509       if (RHS.isNegative())
5510         Pred = ICmpInst::ICMP_SGE;
5511       break;
5512     case ICmpInst::ICMP_UGE:
5513       // (float)int >= -4.4   --> true
5514       // (float)int >= 4.4    --> int > 4
5515       if (!RHS.isNegative())
5516         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5517       Pred = ICmpInst::ICMP_UGT;
5518       break;
5519     case ICmpInst::ICMP_SGE:
5520       // (float)int >= -4.4   --> int >= -4
5521       // (float)int >= 4.4    --> int > 4
5522       if (!RHS.isNegative())
5523         Pred = ICmpInst::ICMP_SGT;
5524       break;
5525     }
5526   }
5527
5528   // Lower this FP comparison into an appropriate integer version of the
5529   // comparison.
5530   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5531 }
5532
5533 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5534   bool Changed = SimplifyCompare(I);
5535   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5536
5537   // Fold trivial predicates.
5538   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5539     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5540   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5541     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5542   
5543   // Simplify 'fcmp pred X, X'
5544   if (Op0 == Op1) {
5545     switch (I.getPredicate()) {
5546     default: assert(0 && "Unknown predicate!");
5547     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5548     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5549     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5550       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5551     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5552     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5553     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5554       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5555       
5556     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5557     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5558     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5559     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5560       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5561       I.setPredicate(FCmpInst::FCMP_UNO);
5562       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5563       return &I;
5564       
5565     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5566     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5567     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5568     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5569       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5570       I.setPredicate(FCmpInst::FCMP_ORD);
5571       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5572       return &I;
5573     }
5574   }
5575     
5576   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5577     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5578
5579   // Handle fcmp with constant RHS
5580   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5581     // If the constant is a nan, see if we can fold the comparison based on it.
5582     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5583       if (CFP->getValueAPF().isNaN()) {
5584         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5585           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5586         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5587                "Comparison must be either ordered or unordered!");
5588         // True if unordered.
5589         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5590       }
5591     }
5592     
5593     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5594       switch (LHSI->getOpcode()) {
5595       case Instruction::PHI:
5596         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5597         // block.  If in the same block, we're encouraging jump threading.  If
5598         // not, we are just pessimizing the code by making an i1 phi.
5599         if (LHSI->getParent() == I.getParent())
5600           if (Instruction *NV = FoldOpIntoPhi(I))
5601             return NV;
5602         break;
5603       case Instruction::SIToFP:
5604       case Instruction::UIToFP:
5605         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5606           return NV;
5607         break;
5608       case Instruction::Select:
5609         // If either operand of the select is a constant, we can fold the
5610         // comparison into the select arms, which will cause one to be
5611         // constant folded and the select turned into a bitwise or.
5612         Value *Op1 = 0, *Op2 = 0;
5613         if (LHSI->hasOneUse()) {
5614           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5615             // Fold the known value into the constant operand.
5616             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5617             // Insert a new FCmp of the other select operand.
5618             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5619                                                       LHSI->getOperand(2), RHSC,
5620                                                       I.getName()), I);
5621           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5622             // Fold the known value into the constant operand.
5623             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5624             // Insert a new FCmp of the other select operand.
5625             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5626                                                       LHSI->getOperand(1), RHSC,
5627                                                       I.getName()), I);
5628           }
5629         }
5630
5631         if (Op1)
5632           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5633         break;
5634       }
5635   }
5636
5637   return Changed ? &I : 0;
5638 }
5639
5640 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5641   bool Changed = SimplifyCompare(I);
5642   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5643   const Type *Ty = Op0->getType();
5644
5645   // icmp X, X
5646   if (Op0 == Op1)
5647     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5648                                                    I.isTrueWhenEqual()));
5649
5650   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5651     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5652   
5653   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5654   // addresses never equal each other!  We already know that Op0 != Op1.
5655   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5656        isa<ConstantPointerNull>(Op0)) &&
5657       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5658        isa<ConstantPointerNull>(Op1)))
5659     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5660                                                    !I.isTrueWhenEqual()));
5661
5662   // icmp's with boolean values can always be turned into bitwise operations
5663   if (Ty == Type::Int1Ty) {
5664     switch (I.getPredicate()) {
5665     default: assert(0 && "Invalid icmp instruction!");
5666     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5667       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5668       InsertNewInstBefore(Xor, I);
5669       return BinaryOperator::CreateNot(Xor);
5670     }
5671     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5672       return BinaryOperator::CreateXor(Op0, Op1);
5673
5674     case ICmpInst::ICMP_UGT:
5675       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5676       // FALL THROUGH
5677     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5678       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5679       InsertNewInstBefore(Not, I);
5680       return BinaryOperator::CreateAnd(Not, Op1);
5681     }
5682     case ICmpInst::ICMP_SGT:
5683       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5684       // FALL THROUGH
5685     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5686       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5687       InsertNewInstBefore(Not, I);
5688       return BinaryOperator::CreateAnd(Not, Op0);
5689     }
5690     case ICmpInst::ICMP_UGE:
5691       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5692       // FALL THROUGH
5693     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5694       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5695       InsertNewInstBefore(Not, I);
5696       return BinaryOperator::CreateOr(Not, Op1);
5697     }
5698     case ICmpInst::ICMP_SGE:
5699       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5700       // FALL THROUGH
5701     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5702       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5703       InsertNewInstBefore(Not, I);
5704       return BinaryOperator::CreateOr(Not, Op0);
5705     }
5706     }
5707   }
5708
5709   // See if we are doing a comparison with a constant.
5710   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5711     Value *A, *B;
5712     
5713     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5714     if (I.isEquality() && CI->isNullValue() &&
5715         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5716       // (icmp cond A B) if cond is equality
5717       return new ICmpInst(I.getPredicate(), A, B);
5718     }
5719     
5720     // If we have an icmp le or icmp ge instruction, turn it into the
5721     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5722     // them being folded in the code below.
5723     switch (I.getPredicate()) {
5724     default: break;
5725     case ICmpInst::ICMP_ULE:
5726       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5727         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5728       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5729     case ICmpInst::ICMP_SLE:
5730       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5731         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5732       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5733     case ICmpInst::ICMP_UGE:
5734       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5735         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5736       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5737     case ICmpInst::ICMP_SGE:
5738       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5739         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5740       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5741     }
5742     
5743     // See if we can fold the comparison based on range information we can get
5744     // by checking whether bits are known to be zero or one in the input.
5745     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5746     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5747     
5748     // If this comparison is a normal comparison, it demands all
5749     // bits, if it is a sign bit comparison, it only demands the sign bit.
5750     bool UnusedBit;
5751     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5752     
5753     if (SimplifyDemandedBits(Op0, 
5754                              isSignBit ? APInt::getSignBit(BitWidth)
5755                                        : APInt::getAllOnesValue(BitWidth),
5756                              KnownZero, KnownOne, 0))
5757       return &I;
5758         
5759     // Given the known and unknown bits, compute a range that the LHS could be
5760     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5761     // EQ and NE we use unsigned values.
5762     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5763     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5764       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5765     else
5766       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5767     
5768     // If Min and Max are known to be the same, then SimplifyDemandedBits
5769     // figured out that the LHS is a constant.  Just constant fold this now so
5770     // that code below can assume that Min != Max.
5771     if (Min == Max)
5772       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5773                                                           ConstantInt::get(Min),
5774                                                           CI));
5775     
5776     // Based on the range information we know about the LHS, see if we can
5777     // simplify this comparison.  For example, (x&4) < 8  is always true.
5778     const APInt &RHSVal = CI->getValue();
5779     switch (I.getPredicate()) {  // LE/GE have been folded already.
5780     default: assert(0 && "Unknown icmp opcode!");
5781     case ICmpInst::ICMP_EQ:
5782       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5783         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5784       break;
5785     case ICmpInst::ICMP_NE:
5786       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5787         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5788       break;
5789     case ICmpInst::ICMP_ULT:
5790       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5791         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5792       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5793         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5794       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5795         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5796       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5797         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5798         
5799       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5800       if (CI->isMinValue(true))
5801         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5802                             ConstantInt::getAllOnesValue(Op0->getType()));
5803       break;
5804     case ICmpInst::ICMP_UGT:
5805       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5806         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5807       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5808         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5809         
5810       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5811         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5812       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5813         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5814       
5815       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5816       if (CI->isMaxValue(true))
5817         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5818                             ConstantInt::getNullValue(Op0->getType()));
5819       break;
5820     case ICmpInst::ICMP_SLT:
5821       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5822         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5823       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5824         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5825       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5826         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5827       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5828         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5829       break;
5830     case ICmpInst::ICMP_SGT: 
5831       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5832         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5833       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5834         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5835         
5836       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5837         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5838       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5839         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5840       break;
5841     }
5842   }
5843
5844   // Test if the ICmpInst instruction is used exclusively by a select as
5845   // part of a minimum or maximum operation. If so, refrain from doing
5846   // any other folding. This helps out other analyses which understand
5847   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5848   // and CodeGen. And in this case, at least one of the comparison
5849   // operands has at least one user besides the compare (the select),
5850   // which would often largely negate the benefit of folding anyway.
5851   if (I.hasOneUse())
5852     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5853       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5854           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5855         return 0;
5856
5857   // See if we are doing a comparison between a constant and an instruction that
5858   // can be folded into the comparison.
5859   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5860     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5861     // instruction, see if that instruction also has constants so that the 
5862     // instruction can be folded into the icmp 
5863     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5864       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5865         return Res;
5866   }
5867
5868   // Handle icmp with constant (but not simple integer constant) RHS
5869   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5870     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5871       switch (LHSI->getOpcode()) {
5872       case Instruction::GetElementPtr:
5873         if (RHSC->isNullValue()) {
5874           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5875           bool isAllZeros = true;
5876           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5877             if (!isa<Constant>(LHSI->getOperand(i)) ||
5878                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5879               isAllZeros = false;
5880               break;
5881             }
5882           if (isAllZeros)
5883             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5884                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5885         }
5886         break;
5887
5888       case Instruction::PHI:
5889         // Only fold icmp into the PHI if the phi and fcmp are in the same
5890         // block.  If in the same block, we're encouraging jump threading.  If
5891         // not, we are just pessimizing the code by making an i1 phi.
5892         if (LHSI->getParent() == I.getParent())
5893           if (Instruction *NV = FoldOpIntoPhi(I))
5894             return NV;
5895         break;
5896       case Instruction::Select: {
5897         // If either operand of the select is a constant, we can fold the
5898         // comparison into the select arms, which will cause one to be
5899         // constant folded and the select turned into a bitwise or.
5900         Value *Op1 = 0, *Op2 = 0;
5901         if (LHSI->hasOneUse()) {
5902           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5903             // Fold the known value into the constant operand.
5904             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5905             // Insert a new ICmp of the other select operand.
5906             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5907                                                    LHSI->getOperand(2), RHSC,
5908                                                    I.getName()), I);
5909           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5910             // Fold the known value into the constant operand.
5911             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5912             // Insert a new ICmp of the other select operand.
5913             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5914                                                    LHSI->getOperand(1), RHSC,
5915                                                    I.getName()), I);
5916           }
5917         }
5918
5919         if (Op1)
5920           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5921         break;
5922       }
5923       case Instruction::Malloc:
5924         // If we have (malloc != null), and if the malloc has a single use, we
5925         // can assume it is successful and remove the malloc.
5926         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5927           AddToWorkList(LHSI);
5928           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5929                                                          !I.isTrueWhenEqual()));
5930         }
5931         break;
5932       }
5933   }
5934
5935   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5936   if (User *GEP = dyn_castGetElementPtr(Op0))
5937     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5938       return NI;
5939   if (User *GEP = dyn_castGetElementPtr(Op1))
5940     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5941                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5942       return NI;
5943
5944   // Test to see if the operands of the icmp are casted versions of other
5945   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5946   // now.
5947   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5948     if (isa<PointerType>(Op0->getType()) && 
5949         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5950       // We keep moving the cast from the left operand over to the right
5951       // operand, where it can often be eliminated completely.
5952       Op0 = CI->getOperand(0);
5953
5954       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5955       // so eliminate it as well.
5956       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5957         Op1 = CI2->getOperand(0);
5958
5959       // If Op1 is a constant, we can fold the cast into the constant.
5960       if (Op0->getType() != Op1->getType()) {
5961         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5962           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5963         } else {
5964           // Otherwise, cast the RHS right before the icmp
5965           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5966         }
5967       }
5968       return new ICmpInst(I.getPredicate(), Op0, Op1);
5969     }
5970   }
5971   
5972   if (isa<CastInst>(Op0)) {
5973     // Handle the special case of: icmp (cast bool to X), <cst>
5974     // This comes up when you have code like
5975     //   int X = A < B;
5976     //   if (X) ...
5977     // For generality, we handle any zero-extension of any operand comparison
5978     // with a constant or another cast from the same type.
5979     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5980       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5981         return R;
5982   }
5983   
5984   // See if it's the same type of instruction on the left and right.
5985   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5986     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
5987       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5988           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5989           I.isEquality()) {
5990         switch (Op0I->getOpcode()) {
5991         default: break;
5992         case Instruction::Add:
5993         case Instruction::Sub:
5994         case Instruction::Xor:
5995           // a+x icmp eq/ne b+x --> a icmp b
5996           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5997                               Op1I->getOperand(0));
5998           break;
5999         case Instruction::Mul:
6000           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6001             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6002             // Mask = -1 >> count-trailing-zeros(Cst).
6003             if (!CI->isZero() && !CI->isOne()) {
6004               const APInt &AP = CI->getValue();
6005               ConstantInt *Mask = ConstantInt::get(
6006                                       APInt::getLowBitsSet(AP.getBitWidth(),
6007                                                            AP.getBitWidth() -
6008                                                       AP.countTrailingZeros()));
6009               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6010                                                             Mask);
6011               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6012                                                             Mask);
6013               InsertNewInstBefore(And1, I);
6014               InsertNewInstBefore(And2, I);
6015               return new ICmpInst(I.getPredicate(), And1, And2);
6016             }
6017           }
6018           break;
6019         }
6020       }
6021     }
6022   }
6023   
6024   // ~x < ~y --> y < x
6025   { Value *A, *B;
6026     if (match(Op0, m_Not(m_Value(A))) &&
6027         match(Op1, m_Not(m_Value(B))))
6028       return new ICmpInst(I.getPredicate(), B, A);
6029   }
6030   
6031   if (I.isEquality()) {
6032     Value *A, *B, *C, *D;
6033     
6034     // -x == -y --> x == y
6035     if (match(Op0, m_Neg(m_Value(A))) &&
6036         match(Op1, m_Neg(m_Value(B))))
6037       return new ICmpInst(I.getPredicate(), A, B);
6038     
6039     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6040       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6041         Value *OtherVal = A == Op1 ? B : A;
6042         return new ICmpInst(I.getPredicate(), OtherVal,
6043                             Constant::getNullValue(A->getType()));
6044       }
6045
6046       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6047         // A^c1 == C^c2 --> A == C^(c1^c2)
6048         ConstantInt *C1, *C2;
6049         if (match(B, m_ConstantInt(C1)) &&
6050             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6051           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6052           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6053           return new ICmpInst(I.getPredicate(), A,
6054                               InsertNewInstBefore(Xor, I));
6055         }
6056         
6057         // A^B == A^D -> B == D
6058         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6059         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6060         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6061         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6062       }
6063     }
6064     
6065     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6066         (A == Op0 || B == Op0)) {
6067       // A == (A^B)  ->  B == 0
6068       Value *OtherVal = A == Op0 ? B : A;
6069       return new ICmpInst(I.getPredicate(), OtherVal,
6070                           Constant::getNullValue(A->getType()));
6071     }
6072
6073     // (A-B) == A  ->  B == 0
6074     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6075       return new ICmpInst(I.getPredicate(), B, 
6076                           Constant::getNullValue(B->getType()));
6077
6078     // A == (A-B)  ->  B == 0
6079     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6080       return new ICmpInst(I.getPredicate(), B,
6081                           Constant::getNullValue(B->getType()));
6082     
6083     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6084     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6085         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6086         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6087       Value *X = 0, *Y = 0, *Z = 0;
6088       
6089       if (A == C) {
6090         X = B; Y = D; Z = A;
6091       } else if (A == D) {
6092         X = B; Y = C; Z = A;
6093       } else if (B == C) {
6094         X = A; Y = D; Z = B;
6095       } else if (B == D) {
6096         X = A; Y = C; Z = B;
6097       }
6098       
6099       if (X) {   // Build (X^Y) & Z
6100         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6101         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6102         I.setOperand(0, Op1);
6103         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6104         return &I;
6105       }
6106     }
6107   }
6108   return Changed ? &I : 0;
6109 }
6110
6111
6112 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6113 /// and CmpRHS are both known to be integer constants.
6114 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6115                                           ConstantInt *DivRHS) {
6116   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6117   const APInt &CmpRHSV = CmpRHS->getValue();
6118   
6119   // FIXME: If the operand types don't match the type of the divide 
6120   // then don't attempt this transform. The code below doesn't have the
6121   // logic to deal with a signed divide and an unsigned compare (and
6122   // vice versa). This is because (x /s C1) <s C2  produces different 
6123   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6124   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6125   // work. :(  The if statement below tests that condition and bails 
6126   // if it finds it. 
6127   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6128   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6129     return 0;
6130   if (DivRHS->isZero())
6131     return 0; // The ProdOV computation fails on divide by zero.
6132   if (DivIsSigned && DivRHS->isAllOnesValue())
6133     return 0; // The overflow computation also screws up here
6134   if (DivRHS->isOne())
6135     return 0; // Not worth bothering, and eliminates some funny cases
6136               // with INT_MIN.
6137
6138   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6139   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6140   // C2 (CI). By solving for X we can turn this into a range check 
6141   // instead of computing a divide. 
6142   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6143
6144   // Determine if the product overflows by seeing if the product is
6145   // not equal to the divide. Make sure we do the same kind of divide
6146   // as in the LHS instruction that we're folding. 
6147   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6148                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6149
6150   // Get the ICmp opcode
6151   ICmpInst::Predicate Pred = ICI.getPredicate();
6152
6153   // Figure out the interval that is being checked.  For example, a comparison
6154   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6155   // Compute this interval based on the constants involved and the signedness of
6156   // the compare/divide.  This computes a half-open interval, keeping track of
6157   // whether either value in the interval overflows.  After analysis each
6158   // overflow variable is set to 0 if it's corresponding bound variable is valid
6159   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6160   int LoOverflow = 0, HiOverflow = 0;
6161   ConstantInt *LoBound = 0, *HiBound = 0;
6162   
6163   if (!DivIsSigned) {  // udiv
6164     // e.g. X/5 op 3  --> [15, 20)
6165     LoBound = Prod;
6166     HiOverflow = LoOverflow = ProdOV;
6167     if (!HiOverflow)
6168       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6169   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6170     if (CmpRHSV == 0) {       // (X / pos) op 0
6171       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6172       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6173       HiBound = DivRHS;
6174     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6175       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6176       HiOverflow = LoOverflow = ProdOV;
6177       if (!HiOverflow)
6178         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6179     } else {                       // (X / pos) op neg
6180       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6181       HiBound = AddOne(Prod);
6182       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6183       if (!LoOverflow) {
6184         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6185         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6186                                      true) ? -1 : 0;
6187        }
6188     }
6189   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6190     if (CmpRHSV == 0) {       // (X / neg) op 0
6191       // e.g. X/-5 op 0  --> [-4, 5)
6192       LoBound = AddOne(DivRHS);
6193       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6194       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6195         HiOverflow = 1;            // [INTMIN+1, overflow)
6196         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6197       }
6198     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6199       // e.g. X/-5 op 3  --> [-19, -14)
6200       HiBound = AddOne(Prod);
6201       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6202       if (!LoOverflow)
6203         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6204     } else {                       // (X / neg) op neg
6205       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6206       LoOverflow = HiOverflow = ProdOV;
6207       if (!HiOverflow)
6208         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6209     }
6210     
6211     // Dividing by a negative swaps the condition.  LT <-> GT
6212     Pred = ICmpInst::getSwappedPredicate(Pred);
6213   }
6214
6215   Value *X = DivI->getOperand(0);
6216   switch (Pred) {
6217   default: assert(0 && "Unhandled icmp opcode!");
6218   case ICmpInst::ICMP_EQ:
6219     if (LoOverflow && HiOverflow)
6220       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6221     else if (HiOverflow)
6222       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6223                           ICmpInst::ICMP_UGE, X, LoBound);
6224     else if (LoOverflow)
6225       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6226                           ICmpInst::ICMP_ULT, X, HiBound);
6227     else
6228       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6229   case ICmpInst::ICMP_NE:
6230     if (LoOverflow && HiOverflow)
6231       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6232     else if (HiOverflow)
6233       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6234                           ICmpInst::ICMP_ULT, X, LoBound);
6235     else if (LoOverflow)
6236       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6237                           ICmpInst::ICMP_UGE, X, HiBound);
6238     else
6239       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6240   case ICmpInst::ICMP_ULT:
6241   case ICmpInst::ICMP_SLT:
6242     if (LoOverflow == +1)   // Low bound is greater than input range.
6243       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6244     if (LoOverflow == -1)   // Low bound is less than input range.
6245       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6246     return new ICmpInst(Pred, X, LoBound);
6247   case ICmpInst::ICMP_UGT:
6248   case ICmpInst::ICMP_SGT:
6249     if (HiOverflow == +1)       // High bound greater than input range.
6250       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6251     else if (HiOverflow == -1)  // High bound less than input range.
6252       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6253     if (Pred == ICmpInst::ICMP_UGT)
6254       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6255     else
6256       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6257   }
6258 }
6259
6260
6261 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6262 ///
6263 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6264                                                           Instruction *LHSI,
6265                                                           ConstantInt *RHS) {
6266   const APInt &RHSV = RHS->getValue();
6267   
6268   switch (LHSI->getOpcode()) {
6269   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6270     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6271       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6272       // fold the xor.
6273       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6274           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6275         Value *CompareVal = LHSI->getOperand(0);
6276         
6277         // If the sign bit of the XorCST is not set, there is no change to
6278         // the operation, just stop using the Xor.
6279         if (!XorCST->getValue().isNegative()) {
6280           ICI.setOperand(0, CompareVal);
6281           AddToWorkList(LHSI);
6282           return &ICI;
6283         }
6284         
6285         // Was the old condition true if the operand is positive?
6286         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6287         
6288         // If so, the new one isn't.
6289         isTrueIfPositive ^= true;
6290         
6291         if (isTrueIfPositive)
6292           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6293         else
6294           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6295       }
6296     }
6297     break;
6298   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6299     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6300         LHSI->getOperand(0)->hasOneUse()) {
6301       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6302       
6303       // If the LHS is an AND of a truncating cast, we can widen the
6304       // and/compare to be the input width without changing the value
6305       // produced, eliminating a cast.
6306       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6307         // We can do this transformation if either the AND constant does not
6308         // have its sign bit set or if it is an equality comparison. 
6309         // Extending a relational comparison when we're checking the sign
6310         // bit would not work.
6311         if (Cast->hasOneUse() &&
6312             (ICI.isEquality() ||
6313              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6314           uint32_t BitWidth = 
6315             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6316           APInt NewCST = AndCST->getValue();
6317           NewCST.zext(BitWidth);
6318           APInt NewCI = RHSV;
6319           NewCI.zext(BitWidth);
6320           Instruction *NewAnd = 
6321             BinaryOperator::CreateAnd(Cast->getOperand(0),
6322                                       ConstantInt::get(NewCST),LHSI->getName());
6323           InsertNewInstBefore(NewAnd, ICI);
6324           return new ICmpInst(ICI.getPredicate(), NewAnd,
6325                               ConstantInt::get(NewCI));
6326         }
6327       }
6328       
6329       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6330       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6331       // happens a LOT in code produced by the C front-end, for bitfield
6332       // access.
6333       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6334       if (Shift && !Shift->isShift())
6335         Shift = 0;
6336       
6337       ConstantInt *ShAmt;
6338       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6339       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6340       const Type *AndTy = AndCST->getType();          // Type of the and.
6341       
6342       // We can fold this as long as we can't shift unknown bits
6343       // into the mask.  This can only happen with signed shift
6344       // rights, as they sign-extend.
6345       if (ShAmt) {
6346         bool CanFold = Shift->isLogicalShift();
6347         if (!CanFold) {
6348           // To test for the bad case of the signed shr, see if any
6349           // of the bits shifted in could be tested after the mask.
6350           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6351           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6352           
6353           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6354           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6355                AndCST->getValue()) == 0)
6356             CanFold = true;
6357         }
6358         
6359         if (CanFold) {
6360           Constant *NewCst;
6361           if (Shift->getOpcode() == Instruction::Shl)
6362             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6363           else
6364             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6365           
6366           // Check to see if we are shifting out any of the bits being
6367           // compared.
6368           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6369             // If we shifted bits out, the fold is not going to work out.
6370             // As a special case, check to see if this means that the
6371             // result is always true or false now.
6372             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6373               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6374             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6375               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6376           } else {
6377             ICI.setOperand(1, NewCst);
6378             Constant *NewAndCST;
6379             if (Shift->getOpcode() == Instruction::Shl)
6380               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6381             else
6382               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6383             LHSI->setOperand(1, NewAndCST);
6384             LHSI->setOperand(0, Shift->getOperand(0));
6385             AddToWorkList(Shift); // Shift is dead.
6386             AddUsesToWorkList(ICI);
6387             return &ICI;
6388           }
6389         }
6390       }
6391       
6392       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6393       // preferable because it allows the C<<Y expression to be hoisted out
6394       // of a loop if Y is invariant and X is not.
6395       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6396           ICI.isEquality() && !Shift->isArithmeticShift() &&
6397           isa<Instruction>(Shift->getOperand(0))) {
6398         // Compute C << Y.
6399         Value *NS;
6400         if (Shift->getOpcode() == Instruction::LShr) {
6401           NS = BinaryOperator::CreateShl(AndCST, 
6402                                          Shift->getOperand(1), "tmp");
6403         } else {
6404           // Insert a logical shift.
6405           NS = BinaryOperator::CreateLShr(AndCST,
6406                                           Shift->getOperand(1), "tmp");
6407         }
6408         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6409         
6410         // Compute X & (C << Y).
6411         Instruction *NewAnd = 
6412           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6413         InsertNewInstBefore(NewAnd, ICI);
6414         
6415         ICI.setOperand(0, NewAnd);
6416         return &ICI;
6417       }
6418     }
6419     break;
6420     
6421   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6422     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6423     if (!ShAmt) break;
6424     
6425     uint32_t TypeBits = RHSV.getBitWidth();
6426     
6427     // Check that the shift amount is in range.  If not, don't perform
6428     // undefined shifts.  When the shift is visited it will be
6429     // simplified.
6430     if (ShAmt->uge(TypeBits))
6431       break;
6432     
6433     if (ICI.isEquality()) {
6434       // If we are comparing against bits always shifted out, the
6435       // comparison cannot succeed.
6436       Constant *Comp =
6437         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6438       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6439         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6440         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6441         return ReplaceInstUsesWith(ICI, Cst);
6442       }
6443       
6444       if (LHSI->hasOneUse()) {
6445         // Otherwise strength reduce the shift into an and.
6446         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6447         Constant *Mask =
6448           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6449         
6450         Instruction *AndI =
6451           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6452                                     Mask, LHSI->getName()+".mask");
6453         Value *And = InsertNewInstBefore(AndI, ICI);
6454         return new ICmpInst(ICI.getPredicate(), And,
6455                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6456       }
6457     }
6458     
6459     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6460     bool TrueIfSigned = false;
6461     if (LHSI->hasOneUse() &&
6462         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6463       // (X << 31) <s 0  --> (X&1) != 0
6464       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6465                                            (TypeBits-ShAmt->getZExtValue()-1));
6466       Instruction *AndI =
6467         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6468                                   Mask, LHSI->getName()+".mask");
6469       Value *And = InsertNewInstBefore(AndI, ICI);
6470       
6471       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6472                           And, Constant::getNullValue(And->getType()));
6473     }
6474     break;
6475   }
6476     
6477   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6478   case Instruction::AShr: {
6479     // Only handle equality comparisons of shift-by-constant.
6480     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6481     if (!ShAmt || !ICI.isEquality()) break;
6482
6483     // Check that the shift amount is in range.  If not, don't perform
6484     // undefined shifts.  When the shift is visited it will be
6485     // simplified.
6486     uint32_t TypeBits = RHSV.getBitWidth();
6487     if (ShAmt->uge(TypeBits))
6488       break;
6489     
6490     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6491       
6492     // If we are comparing against bits always shifted out, the
6493     // comparison cannot succeed.
6494     APInt Comp = RHSV << ShAmtVal;
6495     if (LHSI->getOpcode() == Instruction::LShr)
6496       Comp = Comp.lshr(ShAmtVal);
6497     else
6498       Comp = Comp.ashr(ShAmtVal);
6499     
6500     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6501       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6502       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6503       return ReplaceInstUsesWith(ICI, Cst);
6504     }
6505     
6506     // Otherwise, check to see if the bits shifted out are known to be zero.
6507     // If so, we can compare against the unshifted value:
6508     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6509     if (LHSI->hasOneUse() &&
6510         MaskedValueIsZero(LHSI->getOperand(0), 
6511                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6512       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6513                           ConstantExpr::getShl(RHS, ShAmt));
6514     }
6515       
6516     if (LHSI->hasOneUse()) {
6517       // Otherwise strength reduce the shift into an and.
6518       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6519       Constant *Mask = ConstantInt::get(Val);
6520       
6521       Instruction *AndI =
6522         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6523                                   Mask, LHSI->getName()+".mask");
6524       Value *And = InsertNewInstBefore(AndI, ICI);
6525       return new ICmpInst(ICI.getPredicate(), And,
6526                           ConstantExpr::getShl(RHS, ShAmt));
6527     }
6528     break;
6529   }
6530     
6531   case Instruction::SDiv:
6532   case Instruction::UDiv:
6533     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6534     // Fold this div into the comparison, producing a range check. 
6535     // Determine, based on the divide type, what the range is being 
6536     // checked.  If there is an overflow on the low or high side, remember 
6537     // it, otherwise compute the range [low, hi) bounding the new value.
6538     // See: InsertRangeTest above for the kinds of replacements possible.
6539     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6540       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6541                                           DivRHS))
6542         return R;
6543     break;
6544
6545   case Instruction::Add:
6546     // Fold: icmp pred (add, X, C1), C2
6547
6548     if (!ICI.isEquality()) {
6549       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6550       if (!LHSC) break;
6551       const APInt &LHSV = LHSC->getValue();
6552
6553       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6554                             .subtract(LHSV);
6555
6556       if (ICI.isSignedPredicate()) {
6557         if (CR.getLower().isSignBit()) {
6558           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6559                               ConstantInt::get(CR.getUpper()));
6560         } else if (CR.getUpper().isSignBit()) {
6561           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6562                               ConstantInt::get(CR.getLower()));
6563         }
6564       } else {
6565         if (CR.getLower().isMinValue()) {
6566           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6567                               ConstantInt::get(CR.getUpper()));
6568         } else if (CR.getUpper().isMinValue()) {
6569           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6570                               ConstantInt::get(CR.getLower()));
6571         }
6572       }
6573     }
6574     break;
6575   }
6576   
6577   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6578   if (ICI.isEquality()) {
6579     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6580     
6581     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6582     // the second operand is a constant, simplify a bit.
6583     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6584       switch (BO->getOpcode()) {
6585       case Instruction::SRem:
6586         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6587         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6588           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6589           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6590             Instruction *NewRem =
6591               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6592                                          BO->getName());
6593             InsertNewInstBefore(NewRem, ICI);
6594             return new ICmpInst(ICI.getPredicate(), NewRem, 
6595                                 Constant::getNullValue(BO->getType()));
6596           }
6597         }
6598         break;
6599       case Instruction::Add:
6600         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6601         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6602           if (BO->hasOneUse())
6603             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6604                                 Subtract(RHS, BOp1C));
6605         } else if (RHSV == 0) {
6606           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6607           // efficiently invertible, or if the add has just this one use.
6608           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6609           
6610           if (Value *NegVal = dyn_castNegVal(BOp1))
6611             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6612           else if (Value *NegVal = dyn_castNegVal(BOp0))
6613             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6614           else if (BO->hasOneUse()) {
6615             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6616             InsertNewInstBefore(Neg, ICI);
6617             Neg->takeName(BO);
6618             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6619           }
6620         }
6621         break;
6622       case Instruction::Xor:
6623         // For the xor case, we can xor two constants together, eliminating
6624         // the explicit xor.
6625         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6626           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6627                               ConstantExpr::getXor(RHS, BOC));
6628         
6629         // FALLTHROUGH
6630       case Instruction::Sub:
6631         // Replace (([sub|xor] A, B) != 0) with (A != B)
6632         if (RHSV == 0)
6633           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6634                               BO->getOperand(1));
6635         break;
6636         
6637       case Instruction::Or:
6638         // If bits are being or'd in that are not present in the constant we
6639         // are comparing against, then the comparison could never succeed!
6640         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6641           Constant *NotCI = ConstantExpr::getNot(RHS);
6642           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6643             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6644                                                              isICMP_NE));
6645         }
6646         break;
6647         
6648       case Instruction::And:
6649         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6650           // If bits are being compared against that are and'd out, then the
6651           // comparison can never succeed!
6652           if ((RHSV & ~BOC->getValue()) != 0)
6653             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6654                                                              isICMP_NE));
6655           
6656           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6657           if (RHS == BOC && RHSV.isPowerOf2())
6658             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6659                                 ICmpInst::ICMP_NE, LHSI,
6660                                 Constant::getNullValue(RHS->getType()));
6661           
6662           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6663           if (BOC->getValue().isSignBit()) {
6664             Value *X = BO->getOperand(0);
6665             Constant *Zero = Constant::getNullValue(X->getType());
6666             ICmpInst::Predicate pred = isICMP_NE ? 
6667               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6668             return new ICmpInst(pred, X, Zero);
6669           }
6670           
6671           // ((X & ~7) == 0) --> X < 8
6672           if (RHSV == 0 && isHighOnes(BOC)) {
6673             Value *X = BO->getOperand(0);
6674             Constant *NegX = ConstantExpr::getNeg(BOC);
6675             ICmpInst::Predicate pred = isICMP_NE ? 
6676               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6677             return new ICmpInst(pred, X, NegX);
6678           }
6679         }
6680       default: break;
6681       }
6682     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6683       // Handle icmp {eq|ne} <intrinsic>, intcst.
6684       if (II->getIntrinsicID() == Intrinsic::bswap) {
6685         AddToWorkList(II);
6686         ICI.setOperand(0, II->getOperand(1));
6687         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6688         return &ICI;
6689       }
6690     }
6691   } else {  // Not a ICMP_EQ/ICMP_NE
6692             // If the LHS is a cast from an integral value of the same size, 
6693             // then since we know the RHS is a constant, try to simlify.
6694     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6695       Value *CastOp = Cast->getOperand(0);
6696       const Type *SrcTy = CastOp->getType();
6697       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6698       if (SrcTy->isInteger() && 
6699           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6700         // If this is an unsigned comparison, try to make the comparison use
6701         // smaller constant values.
6702         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6703           // X u< 128 => X s> -1
6704           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6705                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6706         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6707                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6708           // X u> 127 => X s< 0
6709           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6710                               Constant::getNullValue(SrcTy));
6711         }
6712       }
6713     }
6714   }
6715   return 0;
6716 }
6717
6718 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6719 /// We only handle extending casts so far.
6720 ///
6721 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6722   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6723   Value *LHSCIOp        = LHSCI->getOperand(0);
6724   const Type *SrcTy     = LHSCIOp->getType();
6725   const Type *DestTy    = LHSCI->getType();
6726   Value *RHSCIOp;
6727
6728   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6729   // integer type is the same size as the pointer type.
6730   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6731       getTargetData().getPointerSizeInBits() == 
6732          cast<IntegerType>(DestTy)->getBitWidth()) {
6733     Value *RHSOp = 0;
6734     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6735       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6736     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6737       RHSOp = RHSC->getOperand(0);
6738       // If the pointer types don't match, insert a bitcast.
6739       if (LHSCIOp->getType() != RHSOp->getType())
6740         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6741     }
6742
6743     if (RHSOp)
6744       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6745   }
6746   
6747   // The code below only handles extension cast instructions, so far.
6748   // Enforce this.
6749   if (LHSCI->getOpcode() != Instruction::ZExt &&
6750       LHSCI->getOpcode() != Instruction::SExt)
6751     return 0;
6752
6753   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6754   bool isSignedCmp = ICI.isSignedPredicate();
6755
6756   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6757     // Not an extension from the same type?
6758     RHSCIOp = CI->getOperand(0);
6759     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6760       return 0;
6761     
6762     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6763     // and the other is a zext), then we can't handle this.
6764     if (CI->getOpcode() != LHSCI->getOpcode())
6765       return 0;
6766
6767     // Deal with equality cases early.
6768     if (ICI.isEquality())
6769       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6770
6771     // A signed comparison of sign extended values simplifies into a
6772     // signed comparison.
6773     if (isSignedCmp && isSignedExt)
6774       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6775
6776     // The other three cases all fold into an unsigned comparison.
6777     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6778   }
6779
6780   // If we aren't dealing with a constant on the RHS, exit early
6781   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6782   if (!CI)
6783     return 0;
6784
6785   // Compute the constant that would happen if we truncated to SrcTy then
6786   // reextended to DestTy.
6787   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6788   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6789
6790   // If the re-extended constant didn't change...
6791   if (Res2 == CI) {
6792     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6793     // For example, we might have:
6794     //    %A = sext short %X to uint
6795     //    %B = icmp ugt uint %A, 1330
6796     // It is incorrect to transform this into 
6797     //    %B = icmp ugt short %X, 1330 
6798     // because %A may have negative value. 
6799     //
6800     // However, we allow this when the compare is EQ/NE, because they are
6801     // signless.
6802     if (isSignedExt == isSignedCmp || ICI.isEquality())
6803       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6804     return 0;
6805   }
6806
6807   // The re-extended constant changed so the constant cannot be represented 
6808   // in the shorter type. Consequently, we cannot emit a simple comparison.
6809
6810   // First, handle some easy cases. We know the result cannot be equal at this
6811   // point so handle the ICI.isEquality() cases
6812   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6813     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6814   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6815     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6816
6817   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6818   // should have been folded away previously and not enter in here.
6819   Value *Result;
6820   if (isSignedCmp) {
6821     // We're performing a signed comparison.
6822     if (cast<ConstantInt>(CI)->getValue().isNegative())
6823       Result = ConstantInt::getFalse();          // X < (small) --> false
6824     else
6825       Result = ConstantInt::getTrue();           // X < (large) --> true
6826   } else {
6827     // We're performing an unsigned comparison.
6828     if (isSignedExt) {
6829       // We're performing an unsigned comp with a sign extended value.
6830       // This is true if the input is >= 0. [aka >s -1]
6831       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6832       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6833                                    NegOne, ICI.getName()), ICI);
6834     } else {
6835       // Unsigned extend & unsigned compare -> always true.
6836       Result = ConstantInt::getTrue();
6837     }
6838   }
6839
6840   // Finally, return the value computed.
6841   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6842       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6843     return ReplaceInstUsesWith(ICI, Result);
6844
6845   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6846           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6847          "ICmp should be folded!");
6848   if (Constant *CI = dyn_cast<Constant>(Result))
6849     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6850   return BinaryOperator::CreateNot(Result);
6851 }
6852
6853 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6854   return commonShiftTransforms(I);
6855 }
6856
6857 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6858   return commonShiftTransforms(I);
6859 }
6860
6861 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6862   if (Instruction *R = commonShiftTransforms(I))
6863     return R;
6864   
6865   Value *Op0 = I.getOperand(0);
6866   
6867   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6868   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6869     if (CSI->isAllOnesValue())
6870       return ReplaceInstUsesWith(I, CSI);
6871   
6872   // See if we can turn a signed shr into an unsigned shr.
6873   if (!isa<VectorType>(I.getType()) &&
6874       MaskedValueIsZero(Op0,
6875                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6876     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6877   
6878   return 0;
6879 }
6880
6881 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6882   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6883   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6884
6885   // shl X, 0 == X and shr X, 0 == X
6886   // shl 0, X == 0 and shr 0, X == 0
6887   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6888       Op0 == Constant::getNullValue(Op0->getType()))
6889     return ReplaceInstUsesWith(I, Op0);
6890   
6891   if (isa<UndefValue>(Op0)) {            
6892     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6893       return ReplaceInstUsesWith(I, Op0);
6894     else                                    // undef << X -> 0, undef >>u X -> 0
6895       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6896   }
6897   if (isa<UndefValue>(Op1)) {
6898     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6899       return ReplaceInstUsesWith(I, Op0);          
6900     else                                     // X << undef, X >>u undef -> 0
6901       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6902   }
6903
6904   // Try to fold constant and into select arguments.
6905   if (isa<Constant>(Op0))
6906     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6907       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6908         return R;
6909
6910   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6911     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6912       return Res;
6913   return 0;
6914 }
6915
6916 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6917                                                BinaryOperator &I) {
6918   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6919
6920   // See if we can simplify any instructions used by the instruction whose sole 
6921   // purpose is to compute bits we don't care about.
6922   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6923   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6924   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6925                            KnownZero, KnownOne))
6926     return &I;
6927   
6928   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6929   // of a signed value.
6930   //
6931   if (Op1->uge(TypeBits)) {
6932     if (I.getOpcode() != Instruction::AShr)
6933       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6934     else {
6935       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6936       return &I;
6937     }
6938   }
6939   
6940   // ((X*C1) << C2) == (X * (C1 << C2))
6941   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6942     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6943       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6944         return BinaryOperator::CreateMul(BO->getOperand(0),
6945                                          ConstantExpr::getShl(BOOp, Op1));
6946   
6947   // Try to fold constant and into select arguments.
6948   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6949     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6950       return R;
6951   if (isa<PHINode>(Op0))
6952     if (Instruction *NV = FoldOpIntoPhi(I))
6953       return NV;
6954   
6955   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6956   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6957     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6958     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6959     // place.  Don't try to do this transformation in this case.  Also, we
6960     // require that the input operand is a shift-by-constant so that we have
6961     // confidence that the shifts will get folded together.  We could do this
6962     // xform in more cases, but it is unlikely to be profitable.
6963     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6964         isa<ConstantInt>(TrOp->getOperand(1))) {
6965       // Okay, we'll do this xform.  Make the shift of shift.
6966       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6967       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6968                                                 I.getName());
6969       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6970
6971       // For logical shifts, the truncation has the effect of making the high
6972       // part of the register be zeros.  Emulate this by inserting an AND to
6973       // clear the top bits as needed.  This 'and' will usually be zapped by
6974       // other xforms later if dead.
6975       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6976       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6977       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6978       
6979       // The mask we constructed says what the trunc would do if occurring
6980       // between the shifts.  We want to know the effect *after* the second
6981       // shift.  We know that it is a logical shift by a constant, so adjust the
6982       // mask as appropriate.
6983       if (I.getOpcode() == Instruction::Shl)
6984         MaskV <<= Op1->getZExtValue();
6985       else {
6986         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6987         MaskV = MaskV.lshr(Op1->getZExtValue());
6988       }
6989
6990       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6991                                                    TI->getName());
6992       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6993
6994       // Return the value truncated to the interesting size.
6995       return new TruncInst(And, I.getType());
6996     }
6997   }
6998   
6999   if (Op0->hasOneUse()) {
7000     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7001       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7002       Value *V1, *V2;
7003       ConstantInt *CC;
7004       switch (Op0BO->getOpcode()) {
7005         default: break;
7006         case Instruction::Add:
7007         case Instruction::And:
7008         case Instruction::Or:
7009         case Instruction::Xor: {
7010           // These operators commute.
7011           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7012           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7013               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7014             Instruction *YS = BinaryOperator::CreateShl(
7015                                             Op0BO->getOperand(0), Op1,
7016                                             Op0BO->getName());
7017             InsertNewInstBefore(YS, I); // (Y << C)
7018             Instruction *X = 
7019               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7020                                      Op0BO->getOperand(1)->getName());
7021             InsertNewInstBefore(X, I);  // (X + (Y << C))
7022             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7023             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7024                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7025           }
7026           
7027           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7028           Value *Op0BOOp1 = Op0BO->getOperand(1);
7029           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7030               match(Op0BOOp1, 
7031                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7032                           m_ConstantInt(CC))) &&
7033               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7034             Instruction *YS = BinaryOperator::CreateShl(
7035                                                      Op0BO->getOperand(0), Op1,
7036                                                      Op0BO->getName());
7037             InsertNewInstBefore(YS, I); // (Y << C)
7038             Instruction *XM =
7039               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7040                                         V1->getName()+".mask");
7041             InsertNewInstBefore(XM, I); // X & (CC << C)
7042             
7043             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7044           }
7045         }
7046           
7047         // FALL THROUGH.
7048         case Instruction::Sub: {
7049           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7050           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7051               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7052             Instruction *YS = BinaryOperator::CreateShl(
7053                                                      Op0BO->getOperand(1), Op1,
7054                                                      Op0BO->getName());
7055             InsertNewInstBefore(YS, I); // (Y << C)
7056             Instruction *X =
7057               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7058                                      Op0BO->getOperand(0)->getName());
7059             InsertNewInstBefore(X, I);  // (X + (Y << C))
7060             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7061             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7062                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7063           }
7064           
7065           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7066           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7067               match(Op0BO->getOperand(0),
7068                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7069                           m_ConstantInt(CC))) && V2 == Op1 &&
7070               cast<BinaryOperator>(Op0BO->getOperand(0))
7071                   ->getOperand(0)->hasOneUse()) {
7072             Instruction *YS = BinaryOperator::CreateShl(
7073                                                      Op0BO->getOperand(1), Op1,
7074                                                      Op0BO->getName());
7075             InsertNewInstBefore(YS, I); // (Y << C)
7076             Instruction *XM =
7077               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7078                                         V1->getName()+".mask");
7079             InsertNewInstBefore(XM, I); // X & (CC << C)
7080             
7081             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7082           }
7083           
7084           break;
7085         }
7086       }
7087       
7088       
7089       // If the operand is an bitwise operator with a constant RHS, and the
7090       // shift is the only use, we can pull it out of the shift.
7091       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7092         bool isValid = true;     // Valid only for And, Or, Xor
7093         bool highBitSet = false; // Transform if high bit of constant set?
7094         
7095         switch (Op0BO->getOpcode()) {
7096           default: isValid = false; break;   // Do not perform transform!
7097           case Instruction::Add:
7098             isValid = isLeftShift;
7099             break;
7100           case Instruction::Or:
7101           case Instruction::Xor:
7102             highBitSet = false;
7103             break;
7104           case Instruction::And:
7105             highBitSet = true;
7106             break;
7107         }
7108         
7109         // If this is a signed shift right, and the high bit is modified
7110         // by the logical operation, do not perform the transformation.
7111         // The highBitSet boolean indicates the value of the high bit of
7112         // the constant which would cause it to be modified for this
7113         // operation.
7114         //
7115         if (isValid && I.getOpcode() == Instruction::AShr)
7116           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7117         
7118         if (isValid) {
7119           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7120           
7121           Instruction *NewShift =
7122             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7123           InsertNewInstBefore(NewShift, I);
7124           NewShift->takeName(Op0BO);
7125           
7126           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7127                                         NewRHS);
7128         }
7129       }
7130     }
7131   }
7132   
7133   // Find out if this is a shift of a shift by a constant.
7134   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7135   if (ShiftOp && !ShiftOp->isShift())
7136     ShiftOp = 0;
7137   
7138   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7139     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7140     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7141     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7142     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7143     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7144     Value *X = ShiftOp->getOperand(0);
7145     
7146     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7147     if (AmtSum > TypeBits)
7148       AmtSum = TypeBits;
7149     
7150     const IntegerType *Ty = cast<IntegerType>(I.getType());
7151     
7152     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7153     if (I.getOpcode() == ShiftOp->getOpcode()) {
7154       return BinaryOperator::Create(I.getOpcode(), X,
7155                                     ConstantInt::get(Ty, AmtSum));
7156     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7157                I.getOpcode() == Instruction::AShr) {
7158       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7159       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7160     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7161                I.getOpcode() == Instruction::LShr) {
7162       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7163       Instruction *Shift =
7164         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7165       InsertNewInstBefore(Shift, I);
7166
7167       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7168       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7169     }
7170     
7171     // Okay, if we get here, one shift must be left, and the other shift must be
7172     // right.  See if the amounts are equal.
7173     if (ShiftAmt1 == ShiftAmt2) {
7174       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7175       if (I.getOpcode() == Instruction::Shl) {
7176         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7177         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7178       }
7179       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7180       if (I.getOpcode() == Instruction::LShr) {
7181         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7182         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7183       }
7184       // We can simplify ((X << C) >>s C) into a trunc + sext.
7185       // NOTE: we could do this for any C, but that would make 'unusual' integer
7186       // types.  For now, just stick to ones well-supported by the code
7187       // generators.
7188       const Type *SExtType = 0;
7189       switch (Ty->getBitWidth() - ShiftAmt1) {
7190       case 1  :
7191       case 8  :
7192       case 16 :
7193       case 32 :
7194       case 64 :
7195       case 128:
7196         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7197         break;
7198       default: break;
7199       }
7200       if (SExtType) {
7201         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7202         InsertNewInstBefore(NewTrunc, I);
7203         return new SExtInst(NewTrunc, Ty);
7204       }
7205       // Otherwise, we can't handle it yet.
7206     } else if (ShiftAmt1 < ShiftAmt2) {
7207       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7208       
7209       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7210       if (I.getOpcode() == Instruction::Shl) {
7211         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7212                ShiftOp->getOpcode() == Instruction::AShr);
7213         Instruction *Shift =
7214           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7215         InsertNewInstBefore(Shift, I);
7216         
7217         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7218         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7219       }
7220       
7221       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7222       if (I.getOpcode() == Instruction::LShr) {
7223         assert(ShiftOp->getOpcode() == Instruction::Shl);
7224         Instruction *Shift =
7225           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7226         InsertNewInstBefore(Shift, I);
7227         
7228         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7229         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7230       }
7231       
7232       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7233     } else {
7234       assert(ShiftAmt2 < ShiftAmt1);
7235       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7236
7237       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7238       if (I.getOpcode() == Instruction::Shl) {
7239         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7240                ShiftOp->getOpcode() == Instruction::AShr);
7241         Instruction *Shift =
7242           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7243                                  ConstantInt::get(Ty, ShiftDiff));
7244         InsertNewInstBefore(Shift, I);
7245         
7246         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7247         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7248       }
7249       
7250       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7251       if (I.getOpcode() == Instruction::LShr) {
7252         assert(ShiftOp->getOpcode() == Instruction::Shl);
7253         Instruction *Shift =
7254           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7255         InsertNewInstBefore(Shift, I);
7256         
7257         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7258         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7259       }
7260       
7261       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7262     }
7263   }
7264   return 0;
7265 }
7266
7267
7268 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7269 /// expression.  If so, decompose it, returning some value X, such that Val is
7270 /// X*Scale+Offset.
7271 ///
7272 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7273                                         int &Offset) {
7274   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7275   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7276     Offset = CI->getZExtValue();
7277     Scale  = 0;
7278     return ConstantInt::get(Type::Int32Ty, 0);
7279   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7280     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7281       if (I->getOpcode() == Instruction::Shl) {
7282         // This is a value scaled by '1 << the shift amt'.
7283         Scale = 1U << RHS->getZExtValue();
7284         Offset = 0;
7285         return I->getOperand(0);
7286       } else if (I->getOpcode() == Instruction::Mul) {
7287         // This value is scaled by 'RHS'.
7288         Scale = RHS->getZExtValue();
7289         Offset = 0;
7290         return I->getOperand(0);
7291       } else if (I->getOpcode() == Instruction::Add) {
7292         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7293         // where C1 is divisible by C2.
7294         unsigned SubScale;
7295         Value *SubVal = 
7296           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7297         Offset += RHS->getZExtValue();
7298         Scale = SubScale;
7299         return SubVal;
7300       }
7301     }
7302   }
7303
7304   // Otherwise, we can't look past this.
7305   Scale = 1;
7306   Offset = 0;
7307   return Val;
7308 }
7309
7310
7311 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7312 /// try to eliminate the cast by moving the type information into the alloc.
7313 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7314                                                    AllocationInst &AI) {
7315   const PointerType *PTy = cast<PointerType>(CI.getType());
7316   
7317   // Remove any uses of AI that are dead.
7318   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7319   
7320   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7321     Instruction *User = cast<Instruction>(*UI++);
7322     if (isInstructionTriviallyDead(User)) {
7323       while (UI != E && *UI == User)
7324         ++UI; // If this instruction uses AI more than once, don't break UI.
7325       
7326       ++NumDeadInst;
7327       DOUT << "IC: DCE: " << *User;
7328       EraseInstFromFunction(*User);
7329     }
7330   }
7331   
7332   // Get the type really allocated and the type casted to.
7333   const Type *AllocElTy = AI.getAllocatedType();
7334   const Type *CastElTy = PTy->getElementType();
7335   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7336
7337   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7338   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7339   if (CastElTyAlign < AllocElTyAlign) return 0;
7340
7341   // If the allocation has multiple uses, only promote it if we are strictly
7342   // increasing the alignment of the resultant allocation.  If we keep it the
7343   // same, we open the door to infinite loops of various kinds.
7344   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7345
7346   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7347   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7348   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7349
7350   // See if we can satisfy the modulus by pulling a scale out of the array
7351   // size argument.
7352   unsigned ArraySizeScale;
7353   int ArrayOffset;
7354   Value *NumElements = // See if the array size is a decomposable linear expr.
7355     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7356  
7357   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7358   // do the xform.
7359   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7360       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7361
7362   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7363   Value *Amt = 0;
7364   if (Scale == 1) {
7365     Amt = NumElements;
7366   } else {
7367     // If the allocation size is constant, form a constant mul expression
7368     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7369     if (isa<ConstantInt>(NumElements))
7370       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7371     // otherwise multiply the amount and the number of elements
7372     else if (Scale != 1) {
7373       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7374       Amt = InsertNewInstBefore(Tmp, AI);
7375     }
7376   }
7377   
7378   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7379     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7380     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7381     Amt = InsertNewInstBefore(Tmp, AI);
7382   }
7383   
7384   AllocationInst *New;
7385   if (isa<MallocInst>(AI))
7386     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7387   else
7388     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7389   InsertNewInstBefore(New, AI);
7390   New->takeName(&AI);
7391   
7392   // If the allocation has multiple uses, insert a cast and change all things
7393   // that used it to use the new cast.  This will also hack on CI, but it will
7394   // die soon.
7395   if (!AI.hasOneUse()) {
7396     AddUsesToWorkList(AI);
7397     // New is the allocation instruction, pointer typed. AI is the original
7398     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7399     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7400     InsertNewInstBefore(NewCast, AI);
7401     AI.replaceAllUsesWith(NewCast);
7402   }
7403   return ReplaceInstUsesWith(CI, New);
7404 }
7405
7406 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7407 /// and return it as type Ty without inserting any new casts and without
7408 /// changing the computed value.  This is used by code that tries to decide
7409 /// whether promoting or shrinking integer operations to wider or smaller types
7410 /// will allow us to eliminate a truncate or extend.
7411 ///
7412 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7413 /// extension operation if Ty is larger.
7414 ///
7415 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7416 /// should return true if trunc(V) can be computed by computing V in the smaller
7417 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7418 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7419 /// efficiently truncated.
7420 ///
7421 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7422 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7423 /// the final result.
7424 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7425                                               unsigned CastOpc,
7426                                               int &NumCastsRemoved) {
7427   // We can always evaluate constants in another type.
7428   if (isa<ConstantInt>(V))
7429     return true;
7430   
7431   Instruction *I = dyn_cast<Instruction>(V);
7432   if (!I) return false;
7433   
7434   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7435   
7436   // If this is an extension or truncate, we can often eliminate it.
7437   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7438     // If this is a cast from the destination type, we can trivially eliminate
7439     // it, and this will remove a cast overall.
7440     if (I->getOperand(0)->getType() == Ty) {
7441       // If the first operand is itself a cast, and is eliminable, do not count
7442       // this as an eliminable cast.  We would prefer to eliminate those two
7443       // casts first.
7444       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7445         ++NumCastsRemoved;
7446       return true;
7447     }
7448   }
7449
7450   // We can't extend or shrink something that has multiple uses: doing so would
7451   // require duplicating the instruction in general, which isn't profitable.
7452   if (!I->hasOneUse()) return false;
7453
7454   switch (I->getOpcode()) {
7455   case Instruction::Add:
7456   case Instruction::Sub:
7457   case Instruction::Mul:
7458   case Instruction::And:
7459   case Instruction::Or:
7460   case Instruction::Xor:
7461     // These operators can all arbitrarily be extended or truncated.
7462     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7463                                       NumCastsRemoved) &&
7464            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7465                                       NumCastsRemoved);
7466
7467   case Instruction::Shl:
7468     // If we are truncating the result of this SHL, and if it's a shift of a
7469     // constant amount, we can always perform a SHL in a smaller type.
7470     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7471       uint32_t BitWidth = Ty->getBitWidth();
7472       if (BitWidth < OrigTy->getBitWidth() && 
7473           CI->getLimitedValue(BitWidth) < BitWidth)
7474         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7475                                           NumCastsRemoved);
7476     }
7477     break;
7478   case Instruction::LShr:
7479     // If this is a truncate of a logical shr, we can truncate it to a smaller
7480     // lshr iff we know that the bits we would otherwise be shifting in are
7481     // already zeros.
7482     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7483       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7484       uint32_t BitWidth = Ty->getBitWidth();
7485       if (BitWidth < OrigBitWidth &&
7486           MaskedValueIsZero(I->getOperand(0),
7487             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7488           CI->getLimitedValue(BitWidth) < BitWidth) {
7489         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7490                                           NumCastsRemoved);
7491       }
7492     }
7493     break;
7494   case Instruction::ZExt:
7495   case Instruction::SExt:
7496   case Instruction::Trunc:
7497     // If this is the same kind of case as our original (e.g. zext+zext), we
7498     // can safely replace it.  Note that replacing it does not reduce the number
7499     // of casts in the input.
7500     if (I->getOpcode() == CastOpc)
7501       return true;
7502     break;
7503   case Instruction::Select: {
7504     SelectInst *SI = cast<SelectInst>(I);
7505     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7506                                       NumCastsRemoved) &&
7507            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7508                                       NumCastsRemoved);
7509   }
7510   case Instruction::PHI: {
7511     // We can change a phi if we can change all operands.
7512     PHINode *PN = cast<PHINode>(I);
7513     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7514       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7515                                       NumCastsRemoved))
7516         return false;
7517     return true;
7518   }
7519   default:
7520     // TODO: Can handle more cases here.
7521     break;
7522   }
7523   
7524   return false;
7525 }
7526
7527 /// EvaluateInDifferentType - Given an expression that 
7528 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7529 /// evaluate the expression.
7530 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7531                                              bool isSigned) {
7532   if (Constant *C = dyn_cast<Constant>(V))
7533     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7534
7535   // Otherwise, it must be an instruction.
7536   Instruction *I = cast<Instruction>(V);
7537   Instruction *Res = 0;
7538   switch (I->getOpcode()) {
7539   case Instruction::Add:
7540   case Instruction::Sub:
7541   case Instruction::Mul:
7542   case Instruction::And:
7543   case Instruction::Or:
7544   case Instruction::Xor:
7545   case Instruction::AShr:
7546   case Instruction::LShr:
7547   case Instruction::Shl: {
7548     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7549     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7550     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7551                                  LHS, RHS);
7552     break;
7553   }    
7554   case Instruction::Trunc:
7555   case Instruction::ZExt:
7556   case Instruction::SExt:
7557     // If the source type of the cast is the type we're trying for then we can
7558     // just return the source.  There's no need to insert it because it is not
7559     // new.
7560     if (I->getOperand(0)->getType() == Ty)
7561       return I->getOperand(0);
7562     
7563     // Otherwise, must be the same type of cast, so just reinsert a new one.
7564     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7565                            Ty);
7566     break;
7567   case Instruction::Select: {
7568     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7569     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7570     Res = SelectInst::Create(I->getOperand(0), True, False);
7571     break;
7572   }
7573   case Instruction::PHI: {
7574     PHINode *OPN = cast<PHINode>(I);
7575     PHINode *NPN = PHINode::Create(Ty);
7576     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7577       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7578       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7579     }
7580     Res = NPN;
7581     break;
7582   }
7583   default: 
7584     // TODO: Can handle more cases here.
7585     assert(0 && "Unreachable!");
7586     break;
7587   }
7588   
7589   Res->takeName(I);
7590   return InsertNewInstBefore(Res, *I);
7591 }
7592
7593 /// @brief Implement the transforms common to all CastInst visitors.
7594 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7595   Value *Src = CI.getOperand(0);
7596
7597   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7598   // eliminate it now.
7599   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7600     if (Instruction::CastOps opc = 
7601         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7602       // The first cast (CSrc) is eliminable so we need to fix up or replace
7603       // the second cast (CI). CSrc will then have a good chance of being dead.
7604       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7605     }
7606   }
7607
7608   // If we are casting a select then fold the cast into the select
7609   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7610     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7611       return NV;
7612
7613   // If we are casting a PHI then fold the cast into the PHI
7614   if (isa<PHINode>(Src))
7615     if (Instruction *NV = FoldOpIntoPhi(CI))
7616       return NV;
7617   
7618   return 0;
7619 }
7620
7621 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7622 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7623   Value *Src = CI.getOperand(0);
7624   
7625   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7626     // If casting the result of a getelementptr instruction with no offset, turn
7627     // this into a cast of the original pointer!
7628     if (GEP->hasAllZeroIndices()) {
7629       // Changing the cast operand is usually not a good idea but it is safe
7630       // here because the pointer operand is being replaced with another 
7631       // pointer operand so the opcode doesn't need to change.
7632       AddToWorkList(GEP);
7633       CI.setOperand(0, GEP->getOperand(0));
7634       return &CI;
7635     }
7636     
7637     // If the GEP has a single use, and the base pointer is a bitcast, and the
7638     // GEP computes a constant offset, see if we can convert these three
7639     // instructions into fewer.  This typically happens with unions and other
7640     // non-type-safe code.
7641     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7642       if (GEP->hasAllConstantIndices()) {
7643         // We are guaranteed to get a constant from EmitGEPOffset.
7644         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7645         int64_t Offset = OffsetV->getSExtValue();
7646         
7647         // Get the base pointer input of the bitcast, and the type it points to.
7648         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7649         const Type *GEPIdxTy =
7650           cast<PointerType>(OrigBase->getType())->getElementType();
7651         if (GEPIdxTy->isSized()) {
7652           SmallVector<Value*, 8> NewIndices;
7653           
7654           // Start with the index over the outer type.  Note that the type size
7655           // might be zero (even if the offset isn't zero) if the indexed type
7656           // is something like [0 x {int, int}]
7657           const Type *IntPtrTy = TD->getIntPtrType();
7658           int64_t FirstIdx = 0;
7659           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7660             FirstIdx = Offset/TySize;
7661             Offset %= TySize;
7662           
7663             // Handle silly modulus not returning values values [0..TySize).
7664             if (Offset < 0) {
7665               --FirstIdx;
7666               Offset += TySize;
7667               assert(Offset >= 0);
7668             }
7669             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7670           }
7671           
7672           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7673
7674           // Index into the types.  If we fail, set OrigBase to null.
7675           while (Offset) {
7676             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7677               const StructLayout *SL = TD->getStructLayout(STy);
7678               if (Offset < (int64_t)SL->getSizeInBytes()) {
7679                 unsigned Elt = SL->getElementContainingOffset(Offset);
7680                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7681               
7682                 Offset -= SL->getElementOffset(Elt);
7683                 GEPIdxTy = STy->getElementType(Elt);
7684               } else {
7685                 // Otherwise, we can't index into this, bail out.
7686                 Offset = 0;
7687                 OrigBase = 0;
7688               }
7689             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7690               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7691               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7692                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7693                 Offset %= EltSize;
7694               } else {
7695                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7696               }
7697               GEPIdxTy = STy->getElementType();
7698             } else {
7699               // Otherwise, we can't index into this, bail out.
7700               Offset = 0;
7701               OrigBase = 0;
7702             }
7703           }
7704           if (OrigBase) {
7705             // If we were able to index down into an element, create the GEP
7706             // and bitcast the result.  This eliminates one bitcast, potentially
7707             // two.
7708             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7709                                                           NewIndices.begin(),
7710                                                           NewIndices.end(), "");
7711             InsertNewInstBefore(NGEP, CI);
7712             NGEP->takeName(GEP);
7713             
7714             if (isa<BitCastInst>(CI))
7715               return new BitCastInst(NGEP, CI.getType());
7716             assert(isa<PtrToIntInst>(CI));
7717             return new PtrToIntInst(NGEP, CI.getType());
7718           }
7719         }
7720       }      
7721     }
7722   }
7723     
7724   return commonCastTransforms(CI);
7725 }
7726
7727
7728
7729 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7730 /// integer types. This function implements the common transforms for all those
7731 /// cases.
7732 /// @brief Implement the transforms common to CastInst with integer operands
7733 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7734   if (Instruction *Result = commonCastTransforms(CI))
7735     return Result;
7736
7737   Value *Src = CI.getOperand(0);
7738   const Type *SrcTy = Src->getType();
7739   const Type *DestTy = CI.getType();
7740   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7741   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7742
7743   // See if we can simplify any instructions used by the LHS whose sole 
7744   // purpose is to compute bits we don't care about.
7745   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7746   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7747                            KnownZero, KnownOne))
7748     return &CI;
7749
7750   // If the source isn't an instruction or has more than one use then we
7751   // can't do anything more. 
7752   Instruction *SrcI = dyn_cast<Instruction>(Src);
7753   if (!SrcI || !Src->hasOneUse())
7754     return 0;
7755
7756   // Attempt to propagate the cast into the instruction for int->int casts.
7757   int NumCastsRemoved = 0;
7758   if (!isa<BitCastInst>(CI) &&
7759       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7760                                  CI.getOpcode(), NumCastsRemoved)) {
7761     // If this cast is a truncate, evaluting in a different type always
7762     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7763     // we need to do an AND to maintain the clear top-part of the computation,
7764     // so we require that the input have eliminated at least one cast.  If this
7765     // is a sign extension, we insert two new casts (to do the extension) so we
7766     // require that two casts have been eliminated.
7767     bool DoXForm;
7768     switch (CI.getOpcode()) {
7769     default:
7770       // All the others use floating point so we shouldn't actually 
7771       // get here because of the check above.
7772       assert(0 && "Unknown cast type");
7773     case Instruction::Trunc:
7774       DoXForm = true;
7775       break;
7776     case Instruction::ZExt:
7777       DoXForm = NumCastsRemoved >= 1;
7778       break;
7779     case Instruction::SExt:
7780       DoXForm = NumCastsRemoved >= 2;
7781       break;
7782     }
7783     
7784     if (DoXForm) {
7785       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7786                                            CI.getOpcode() == Instruction::SExt);
7787       assert(Res->getType() == DestTy);
7788       switch (CI.getOpcode()) {
7789       default: assert(0 && "Unknown cast type!");
7790       case Instruction::Trunc:
7791       case Instruction::BitCast:
7792         // Just replace this cast with the result.
7793         return ReplaceInstUsesWith(CI, Res);
7794       case Instruction::ZExt: {
7795         // We need to emit an AND to clear the high bits.
7796         assert(SrcBitSize < DestBitSize && "Not a zext?");
7797         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7798                                                             SrcBitSize));
7799         return BinaryOperator::CreateAnd(Res, C);
7800       }
7801       case Instruction::SExt:
7802         // We need to emit a cast to truncate, then a cast to sext.
7803         return CastInst::Create(Instruction::SExt,
7804             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7805                              CI), DestTy);
7806       }
7807     }
7808   }
7809   
7810   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7811   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7812
7813   switch (SrcI->getOpcode()) {
7814   case Instruction::Add:
7815   case Instruction::Mul:
7816   case Instruction::And:
7817   case Instruction::Or:
7818   case Instruction::Xor:
7819     // If we are discarding information, rewrite.
7820     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7821       // Don't insert two casts if they cannot be eliminated.  We allow 
7822       // two casts to be inserted if the sizes are the same.  This could 
7823       // only be converting signedness, which is a noop.
7824       if (DestBitSize == SrcBitSize || 
7825           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7826           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7827         Instruction::CastOps opcode = CI.getOpcode();
7828         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7829         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7830         return BinaryOperator::Create(
7831             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7832       }
7833     }
7834
7835     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7836     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7837         SrcI->getOpcode() == Instruction::Xor &&
7838         Op1 == ConstantInt::getTrue() &&
7839         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7840       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7841       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7842     }
7843     break;
7844   case Instruction::SDiv:
7845   case Instruction::UDiv:
7846   case Instruction::SRem:
7847   case Instruction::URem:
7848     // If we are just changing the sign, rewrite.
7849     if (DestBitSize == SrcBitSize) {
7850       // Don't insert two casts if they cannot be eliminated.  We allow 
7851       // two casts to be inserted if the sizes are the same.  This could 
7852       // only be converting signedness, which is a noop.
7853       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7854           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7855         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7856                                               Op0, DestTy, SrcI);
7857         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7858                                               Op1, DestTy, SrcI);
7859         return BinaryOperator::Create(
7860           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7861       }
7862     }
7863     break;
7864
7865   case Instruction::Shl:
7866     // Allow changing the sign of the source operand.  Do not allow 
7867     // changing the size of the shift, UNLESS the shift amount is a 
7868     // constant.  We must not change variable sized shifts to a smaller 
7869     // size, because it is undefined to shift more bits out than exist 
7870     // in the value.
7871     if (DestBitSize == SrcBitSize ||
7872         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7873       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7874           Instruction::BitCast : Instruction::Trunc);
7875       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7876       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7877       return BinaryOperator::CreateShl(Op0c, Op1c);
7878     }
7879     break;
7880   case Instruction::AShr:
7881     // If this is a signed shr, and if all bits shifted in are about to be
7882     // truncated off, turn it into an unsigned shr to allow greater
7883     // simplifications.
7884     if (DestBitSize < SrcBitSize &&
7885         isa<ConstantInt>(Op1)) {
7886       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7887       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7888         // Insert the new logical shift right.
7889         return BinaryOperator::CreateLShr(Op0, Op1);
7890       }
7891     }
7892     break;
7893   }
7894   return 0;
7895 }
7896
7897 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7898   if (Instruction *Result = commonIntCastTransforms(CI))
7899     return Result;
7900   
7901   Value *Src = CI.getOperand(0);
7902   const Type *Ty = CI.getType();
7903   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7904   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7905   
7906   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7907     switch (SrcI->getOpcode()) {
7908     default: break;
7909     case Instruction::LShr:
7910       // We can shrink lshr to something smaller if we know the bits shifted in
7911       // are already zeros.
7912       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7913         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7914         
7915         // Get a mask for the bits shifting in.
7916         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7917         Value* SrcIOp0 = SrcI->getOperand(0);
7918         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7919           if (ShAmt >= DestBitWidth)        // All zeros.
7920             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7921
7922           // Okay, we can shrink this.  Truncate the input, then return a new
7923           // shift.
7924           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7925           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7926                                        Ty, CI);
7927           return BinaryOperator::CreateLShr(V1, V2);
7928         }
7929       } else {     // This is a variable shr.
7930         
7931         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7932         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7933         // loop-invariant and CSE'd.
7934         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7935           Value *One = ConstantInt::get(SrcI->getType(), 1);
7936
7937           Value *V = InsertNewInstBefore(
7938               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7939                                      "tmp"), CI);
7940           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7941                                                             SrcI->getOperand(0),
7942                                                             "tmp"), CI);
7943           Value *Zero = Constant::getNullValue(V->getType());
7944           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7945         }
7946       }
7947       break;
7948     }
7949   }
7950   
7951   return 0;
7952 }
7953
7954 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7955 /// in order to eliminate the icmp.
7956 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7957                                              bool DoXform) {
7958   // If we are just checking for a icmp eq of a single bit and zext'ing it
7959   // to an integer, then shift the bit to the appropriate place and then
7960   // cast to integer to avoid the comparison.
7961   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7962     const APInt &Op1CV = Op1C->getValue();
7963       
7964     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7965     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7966     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7967         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7968       if (!DoXform) return ICI;
7969
7970       Value *In = ICI->getOperand(0);
7971       Value *Sh = ConstantInt::get(In->getType(),
7972                                    In->getType()->getPrimitiveSizeInBits()-1);
7973       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7974                                                         In->getName()+".lobit"),
7975                                CI);
7976       if (In->getType() != CI.getType())
7977         In = CastInst::CreateIntegerCast(In, CI.getType(),
7978                                          false/*ZExt*/, "tmp", &CI);
7979
7980       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7981         Constant *One = ConstantInt::get(In->getType(), 1);
7982         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7983                                                          In->getName()+".not"),
7984                                  CI);
7985       }
7986
7987       return ReplaceInstUsesWith(CI, In);
7988     }
7989       
7990       
7991       
7992     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7993     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7994     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7995     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7996     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7997     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7998     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7999     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8000     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8001         // This only works for EQ and NE
8002         ICI->isEquality()) {
8003       // If Op1C some other power of two, convert:
8004       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8005       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8006       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8007       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8008         
8009       APInt KnownZeroMask(~KnownZero);
8010       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8011         if (!DoXform) return ICI;
8012
8013         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8014         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8015           // (X&4) == 2 --> false
8016           // (X&4) != 2 --> true
8017           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8018           Res = ConstantExpr::getZExt(Res, CI.getType());
8019           return ReplaceInstUsesWith(CI, Res);
8020         }
8021           
8022         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8023         Value *In = ICI->getOperand(0);
8024         if (ShiftAmt) {
8025           // Perform a logical shr by shiftamt.
8026           // Insert the shift to put the result in the low bit.
8027           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8028                                   ConstantInt::get(In->getType(), ShiftAmt),
8029                                                    In->getName()+".lobit"), CI);
8030         }
8031           
8032         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8033           Constant *One = ConstantInt::get(In->getType(), 1);
8034           In = BinaryOperator::CreateXor(In, One, "tmp");
8035           InsertNewInstBefore(cast<Instruction>(In), CI);
8036         }
8037           
8038         if (CI.getType() == In->getType())
8039           return ReplaceInstUsesWith(CI, In);
8040         else
8041           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8042       }
8043     }
8044   }
8045
8046   return 0;
8047 }
8048
8049 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8050   // If one of the common conversion will work ..
8051   if (Instruction *Result = commonIntCastTransforms(CI))
8052     return Result;
8053
8054   Value *Src = CI.getOperand(0);
8055
8056   // If this is a cast of a cast
8057   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8058     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8059     // types and if the sizes are just right we can convert this into a logical
8060     // 'and' which will be much cheaper than the pair of casts.
8061     if (isa<TruncInst>(CSrc)) {
8062       // Get the sizes of the types involved
8063       Value *A = CSrc->getOperand(0);
8064       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8065       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8066       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8067       // If we're actually extending zero bits and the trunc is a no-op
8068       if (MidSize < DstSize && SrcSize == DstSize) {
8069         // Replace both of the casts with an And of the type mask.
8070         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8071         Constant *AndConst = ConstantInt::get(AndValue);
8072         Instruction *And = 
8073           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8074         // Unfortunately, if the type changed, we need to cast it back.
8075         if (And->getType() != CI.getType()) {
8076           And->setName(CSrc->getName()+".mask");
8077           InsertNewInstBefore(And, CI);
8078           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8079         }
8080         return And;
8081       }
8082     }
8083   }
8084
8085   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8086     return transformZExtICmp(ICI, CI);
8087
8088   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8089   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8090     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8091     // of the (zext icmp) will be transformed.
8092     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8093     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8094     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8095         (transformZExtICmp(LHS, CI, false) ||
8096          transformZExtICmp(RHS, CI, false))) {
8097       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8098       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8099       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8100     }
8101   }
8102
8103   return 0;
8104 }
8105
8106 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8107   if (Instruction *I = commonIntCastTransforms(CI))
8108     return I;
8109   
8110   Value *Src = CI.getOperand(0);
8111   
8112   // Canonicalize sign-extend from i1 to a select.
8113   if (Src->getType() == Type::Int1Ty)
8114     return SelectInst::Create(Src,
8115                               ConstantInt::getAllOnesValue(CI.getType()),
8116                               Constant::getNullValue(CI.getType()));
8117
8118   // See if the value being truncated is already sign extended.  If so, just
8119   // eliminate the trunc/sext pair.
8120   if (getOpcode(Src) == Instruction::Trunc) {
8121     Value *Op = cast<User>(Src)->getOperand(0);
8122     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8123     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8124     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8125     unsigned NumSignBits = ComputeNumSignBits(Op);
8126
8127     if (OpBits == DestBits) {
8128       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8129       // bits, it is already ready.
8130       if (NumSignBits > DestBits-MidBits)
8131         return ReplaceInstUsesWith(CI, Op);
8132     } else if (OpBits < DestBits) {
8133       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8134       // bits, just sext from i32.
8135       if (NumSignBits > OpBits-MidBits)
8136         return new SExtInst(Op, CI.getType(), "tmp");
8137     } else {
8138       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8139       // bits, just truncate to i32.
8140       if (NumSignBits > OpBits-MidBits)
8141         return new TruncInst(Op, CI.getType(), "tmp");
8142     }
8143   }
8144
8145   // If the input is a shl/ashr pair of a same constant, then this is a sign
8146   // extension from a smaller value.  If we could trust arbitrary bitwidth
8147   // integers, we could turn this into a truncate to the smaller bit and then
8148   // use a sext for the whole extension.  Since we don't, look deeper and check
8149   // for a truncate.  If the source and dest are the same type, eliminate the
8150   // trunc and extend and just do shifts.  For example, turn:
8151   //   %a = trunc i32 %i to i8
8152   //   %b = shl i8 %a, 6
8153   //   %c = ashr i8 %b, 6
8154   //   %d = sext i8 %c to i32
8155   // into:
8156   //   %a = shl i32 %i, 30
8157   //   %d = ashr i32 %a, 30
8158   Value *A = 0;
8159   ConstantInt *BA = 0, *CA = 0;
8160   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8161                         m_ConstantInt(CA))) &&
8162       BA == CA && isa<TruncInst>(A)) {
8163     Value *I = cast<TruncInst>(A)->getOperand(0);
8164     if (I->getType() == CI.getType()) {
8165       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8166       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8167       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8168       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8169       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8170                                                         CI.getName()), CI);
8171       return BinaryOperator::CreateAShr(I, ShAmtV);
8172     }
8173   }
8174   
8175   return 0;
8176 }
8177
8178 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8179 /// in the specified FP type without changing its value.
8180 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8181   bool losesInfo;
8182   APFloat F = CFP->getValueAPF();
8183   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8184   if (!losesInfo)
8185     return ConstantFP::get(F);
8186   return 0;
8187 }
8188
8189 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8190 /// through it until we get the source value.
8191 static Value *LookThroughFPExtensions(Value *V) {
8192   if (Instruction *I = dyn_cast<Instruction>(V))
8193     if (I->getOpcode() == Instruction::FPExt)
8194       return LookThroughFPExtensions(I->getOperand(0));
8195   
8196   // If this value is a constant, return the constant in the smallest FP type
8197   // that can accurately represent it.  This allows us to turn
8198   // (float)((double)X+2.0) into x+2.0f.
8199   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8200     if (CFP->getType() == Type::PPC_FP128Ty)
8201       return V;  // No constant folding of this.
8202     // See if the value can be truncated to float and then reextended.
8203     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8204       return V;
8205     if (CFP->getType() == Type::DoubleTy)
8206       return V;  // Won't shrink.
8207     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8208       return V;
8209     // Don't try to shrink to various long double types.
8210   }
8211   
8212   return V;
8213 }
8214
8215 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8216   if (Instruction *I = commonCastTransforms(CI))
8217     return I;
8218   
8219   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8220   // smaller than the destination type, we can eliminate the truncate by doing
8221   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8222   // many builtins (sqrt, etc).
8223   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8224   if (OpI && OpI->hasOneUse()) {
8225     switch (OpI->getOpcode()) {
8226     default: break;
8227     case Instruction::Add:
8228     case Instruction::Sub:
8229     case Instruction::Mul:
8230     case Instruction::FDiv:
8231     case Instruction::FRem:
8232       const Type *SrcTy = OpI->getType();
8233       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8234       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8235       if (LHSTrunc->getType() != SrcTy && 
8236           RHSTrunc->getType() != SrcTy) {
8237         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8238         // If the source types were both smaller than the destination type of
8239         // the cast, do this xform.
8240         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8241             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8242           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8243                                       CI.getType(), CI);
8244           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8245                                       CI.getType(), CI);
8246           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8247         }
8248       }
8249       break;  
8250     }
8251   }
8252   return 0;
8253 }
8254
8255 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8256   return commonCastTransforms(CI);
8257 }
8258
8259 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8260   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8261   if (OpI == 0)
8262     return commonCastTransforms(FI);
8263
8264   // fptoui(uitofp(X)) --> X
8265   // fptoui(sitofp(X)) --> X
8266   // This is safe if the intermediate type has enough bits in its mantissa to
8267   // accurately represent all values of X.  For example, do not do this with
8268   // i64->float->i64.  This is also safe for sitofp case, because any negative
8269   // 'X' value would cause an undefined result for the fptoui. 
8270   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8271       OpI->getOperand(0)->getType() == FI.getType() &&
8272       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8273                     OpI->getType()->getFPMantissaWidth())
8274     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8275
8276   return commonCastTransforms(FI);
8277 }
8278
8279 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8280   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8281   if (OpI == 0)
8282     return commonCastTransforms(FI);
8283   
8284   // fptosi(sitofp(X)) --> X
8285   // fptosi(uitofp(X)) --> X
8286   // This is safe if the intermediate type has enough bits in its mantissa to
8287   // accurately represent all values of X.  For example, do not do this with
8288   // i64->float->i64.  This is also safe for sitofp case, because any negative
8289   // 'X' value would cause an undefined result for the fptoui. 
8290   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8291       OpI->getOperand(0)->getType() == FI.getType() &&
8292       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8293                     OpI->getType()->getFPMantissaWidth())
8294     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8295   
8296   return commonCastTransforms(FI);
8297 }
8298
8299 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8300   return commonCastTransforms(CI);
8301 }
8302
8303 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8304   return commonCastTransforms(CI);
8305 }
8306
8307 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8308   return commonPointerCastTransforms(CI);
8309 }
8310
8311 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8312   if (Instruction *I = commonCastTransforms(CI))
8313     return I;
8314   
8315   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8316   if (!DestPointee->isSized()) return 0;
8317
8318   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8319   ConstantInt *Cst;
8320   Value *X;
8321   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8322                                     m_ConstantInt(Cst)))) {
8323     // If the source and destination operands have the same type, see if this
8324     // is a single-index GEP.
8325     if (X->getType() == CI.getType()) {
8326       // Get the size of the pointee type.
8327       uint64_t Size = TD->getABITypeSize(DestPointee);
8328
8329       // Convert the constant to intptr type.
8330       APInt Offset = Cst->getValue();
8331       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8332
8333       // If Offset is evenly divisible by Size, we can do this xform.
8334       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8335         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8336         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8337       }
8338     }
8339     // TODO: Could handle other cases, e.g. where add is indexing into field of
8340     // struct etc.
8341   } else if (CI.getOperand(0)->hasOneUse() &&
8342              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8343     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8344     // "inttoptr+GEP" instead of "add+intptr".
8345     
8346     // Get the size of the pointee type.
8347     uint64_t Size = TD->getABITypeSize(DestPointee);
8348     
8349     // Convert the constant to intptr type.
8350     APInt Offset = Cst->getValue();
8351     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8352     
8353     // If Offset is evenly divisible by Size, we can do this xform.
8354     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8355       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8356       
8357       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8358                                                             "tmp"), CI);
8359       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8360     }
8361   }
8362   return 0;
8363 }
8364
8365 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8366   // If the operands are integer typed then apply the integer transforms,
8367   // otherwise just apply the common ones.
8368   Value *Src = CI.getOperand(0);
8369   const Type *SrcTy = Src->getType();
8370   const Type *DestTy = CI.getType();
8371
8372   if (SrcTy->isInteger() && DestTy->isInteger()) {
8373     if (Instruction *Result = commonIntCastTransforms(CI))
8374       return Result;
8375   } else if (isa<PointerType>(SrcTy)) {
8376     if (Instruction *I = commonPointerCastTransforms(CI))
8377       return I;
8378   } else {
8379     if (Instruction *Result = commonCastTransforms(CI))
8380       return Result;
8381   }
8382
8383
8384   // Get rid of casts from one type to the same type. These are useless and can
8385   // be replaced by the operand.
8386   if (DestTy == Src->getType())
8387     return ReplaceInstUsesWith(CI, Src);
8388
8389   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8390     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8391     const Type *DstElTy = DstPTy->getElementType();
8392     const Type *SrcElTy = SrcPTy->getElementType();
8393     
8394     // If the address spaces don't match, don't eliminate the bitcast, which is
8395     // required for changing types.
8396     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8397       return 0;
8398     
8399     // If we are casting a malloc or alloca to a pointer to a type of the same
8400     // size, rewrite the allocation instruction to allocate the "right" type.
8401     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8402       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8403         return V;
8404     
8405     // If the source and destination are pointers, and this cast is equivalent
8406     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8407     // This can enhance SROA and other transforms that want type-safe pointers.
8408     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8409     unsigned NumZeros = 0;
8410     while (SrcElTy != DstElTy && 
8411            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8412            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8413       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8414       ++NumZeros;
8415     }
8416
8417     // If we found a path from the src to dest, create the getelementptr now.
8418     if (SrcElTy == DstElTy) {
8419       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8420       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8421                                        ((Instruction*) NULL));
8422     }
8423   }
8424
8425   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8426     if (SVI->hasOneUse()) {
8427       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8428       // a bitconvert to a vector with the same # elts.
8429       if (isa<VectorType>(DestTy) && 
8430           cast<VectorType>(DestTy)->getNumElements() ==
8431                 SVI->getType()->getNumElements() &&
8432           SVI->getType()->getNumElements() ==
8433             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8434         CastInst *Tmp;
8435         // If either of the operands is a cast from CI.getType(), then
8436         // evaluating the shuffle in the casted destination's type will allow
8437         // us to eliminate at least one cast.
8438         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8439              Tmp->getOperand(0)->getType() == DestTy) ||
8440             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8441              Tmp->getOperand(0)->getType() == DestTy)) {
8442           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8443                                                SVI->getOperand(0), DestTy, &CI);
8444           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8445                                                SVI->getOperand(1), DestTy, &CI);
8446           // Return a new shuffle vector.  Use the same element ID's, as we
8447           // know the vector types match #elts.
8448           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8449         }
8450       }
8451     }
8452   }
8453   return 0;
8454 }
8455
8456 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8457 ///   %C = or %A, %B
8458 ///   %D = select %cond, %C, %A
8459 /// into:
8460 ///   %C = select %cond, %B, 0
8461 ///   %D = or %A, %C
8462 ///
8463 /// Assuming that the specified instruction is an operand to the select, return
8464 /// a bitmask indicating which operands of this instruction are foldable if they
8465 /// equal the other incoming value of the select.
8466 ///
8467 static unsigned GetSelectFoldableOperands(Instruction *I) {
8468   switch (I->getOpcode()) {
8469   case Instruction::Add:
8470   case Instruction::Mul:
8471   case Instruction::And:
8472   case Instruction::Or:
8473   case Instruction::Xor:
8474     return 3;              // Can fold through either operand.
8475   case Instruction::Sub:   // Can only fold on the amount subtracted.
8476   case Instruction::Shl:   // Can only fold on the shift amount.
8477   case Instruction::LShr:
8478   case Instruction::AShr:
8479     return 1;
8480   default:
8481     return 0;              // Cannot fold
8482   }
8483 }
8484
8485 /// GetSelectFoldableConstant - For the same transformation as the previous
8486 /// function, return the identity constant that goes into the select.
8487 static Constant *GetSelectFoldableConstant(Instruction *I) {
8488   switch (I->getOpcode()) {
8489   default: assert(0 && "This cannot happen!"); abort();
8490   case Instruction::Add:
8491   case Instruction::Sub:
8492   case Instruction::Or:
8493   case Instruction::Xor:
8494   case Instruction::Shl:
8495   case Instruction::LShr:
8496   case Instruction::AShr:
8497     return Constant::getNullValue(I->getType());
8498   case Instruction::And:
8499     return Constant::getAllOnesValue(I->getType());
8500   case Instruction::Mul:
8501     return ConstantInt::get(I->getType(), 1);
8502   }
8503 }
8504
8505 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8506 /// have the same opcode and only one use each.  Try to simplify this.
8507 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8508                                           Instruction *FI) {
8509   if (TI->getNumOperands() == 1) {
8510     // If this is a non-volatile load or a cast from the same type,
8511     // merge.
8512     if (TI->isCast()) {
8513       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8514         return 0;
8515     } else {
8516       return 0;  // unknown unary op.
8517     }
8518
8519     // Fold this by inserting a select from the input values.
8520     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8521                                            FI->getOperand(0), SI.getName()+".v");
8522     InsertNewInstBefore(NewSI, SI);
8523     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8524                             TI->getType());
8525   }
8526
8527   // Only handle binary operators here.
8528   if (!isa<BinaryOperator>(TI))
8529     return 0;
8530
8531   // Figure out if the operations have any operands in common.
8532   Value *MatchOp, *OtherOpT, *OtherOpF;
8533   bool MatchIsOpZero;
8534   if (TI->getOperand(0) == FI->getOperand(0)) {
8535     MatchOp  = TI->getOperand(0);
8536     OtherOpT = TI->getOperand(1);
8537     OtherOpF = FI->getOperand(1);
8538     MatchIsOpZero = true;
8539   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8540     MatchOp  = TI->getOperand(1);
8541     OtherOpT = TI->getOperand(0);
8542     OtherOpF = FI->getOperand(0);
8543     MatchIsOpZero = false;
8544   } else if (!TI->isCommutative()) {
8545     return 0;
8546   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8547     MatchOp  = TI->getOperand(0);
8548     OtherOpT = TI->getOperand(1);
8549     OtherOpF = FI->getOperand(0);
8550     MatchIsOpZero = true;
8551   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8552     MatchOp  = TI->getOperand(1);
8553     OtherOpT = TI->getOperand(0);
8554     OtherOpF = FI->getOperand(1);
8555     MatchIsOpZero = true;
8556   } else {
8557     return 0;
8558   }
8559
8560   // If we reach here, they do have operations in common.
8561   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8562                                          OtherOpF, SI.getName()+".v");
8563   InsertNewInstBefore(NewSI, SI);
8564
8565   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8566     if (MatchIsOpZero)
8567       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8568     else
8569       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8570   }
8571   assert(0 && "Shouldn't get here");
8572   return 0;
8573 }
8574
8575 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8576 /// ICmpInst as its first operand.
8577 ///
8578 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8579                                                    ICmpInst *ICI) {
8580   bool Changed = false;
8581   ICmpInst::Predicate Pred = ICI->getPredicate();
8582   Value *CmpLHS = ICI->getOperand(0);
8583   Value *CmpRHS = ICI->getOperand(1);
8584   Value *TrueVal = SI.getTrueValue();
8585   Value *FalseVal = SI.getFalseValue();
8586
8587   // Check cases where the comparison is with a constant that
8588   // can be adjusted to fit the min/max idiom. We may edit ICI in
8589   // place here, so make sure the select is the only user.
8590   if (ICI->hasOneUse())
8591     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8592       switch (Pred) {
8593       default: break;
8594       case ICmpInst::ICMP_ULT:
8595       case ICmpInst::ICMP_SLT: {
8596         // X < MIN ? T : F  -->  F
8597         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8598           return ReplaceInstUsesWith(SI, FalseVal);
8599         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8600         Constant *AdjustedRHS = SubOne(CI);
8601         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8602             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8603           Pred = ICmpInst::getSwappedPredicate(Pred);
8604           CmpRHS = AdjustedRHS;
8605           std::swap(FalseVal, TrueVal);
8606           ICI->setPredicate(Pred);
8607           ICI->setOperand(1, CmpRHS);
8608           SI.setOperand(1, TrueVal);
8609           SI.setOperand(2, FalseVal);
8610           Changed = true;
8611         }
8612         break;
8613       }
8614       case ICmpInst::ICMP_UGT:
8615       case ICmpInst::ICMP_SGT: {
8616         // X > MAX ? T : F  -->  F
8617         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8618           return ReplaceInstUsesWith(SI, FalseVal);
8619         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8620         Constant *AdjustedRHS = AddOne(CI);
8621         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8622             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8623           Pred = ICmpInst::getSwappedPredicate(Pred);
8624           CmpRHS = AdjustedRHS;
8625           std::swap(FalseVal, TrueVal);
8626           ICI->setPredicate(Pred);
8627           ICI->setOperand(1, CmpRHS);
8628           SI.setOperand(1, TrueVal);
8629           SI.setOperand(2, FalseVal);
8630           Changed = true;
8631         }
8632         break;
8633       }
8634       }
8635
8636       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8637       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8638       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8639       if (match(TrueVal, m_ConstantInt(-1)) &&
8640           match(FalseVal, m_ConstantInt(0)))
8641         Pred = ICI->getPredicate();
8642       else if (match(TrueVal, m_ConstantInt(0)) &&
8643                match(FalseVal, m_ConstantInt(-1)))
8644         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8645       
8646       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8647         // If we are just checking for a icmp eq of a single bit and zext'ing it
8648         // to an integer, then shift the bit to the appropriate place and then
8649         // cast to integer to avoid the comparison.
8650         const APInt &Op1CV = CI->getValue();
8651     
8652         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8653         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8654         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8655             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8656           Value *In = ICI->getOperand(0);
8657           Value *Sh = ConstantInt::get(In->getType(),
8658                                        In->getType()->getPrimitiveSizeInBits()-1);
8659           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8660                                                           In->getName()+".lobit"),
8661                                    *ICI);
8662           if (In->getType() != SI.getType())
8663             In = CastInst::CreateIntegerCast(In, SI.getType(),
8664                                              true/*SExt*/, "tmp", ICI);
8665     
8666           if (Pred == ICmpInst::ICMP_SGT)
8667             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8668                                        In->getName()+".not"), *ICI);
8669     
8670           return ReplaceInstUsesWith(SI, In);
8671         }
8672       }
8673     }
8674
8675   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8676     // Transform (X == Y) ? X : Y  -> Y
8677     if (Pred == ICmpInst::ICMP_EQ)
8678       return ReplaceInstUsesWith(SI, FalseVal);
8679     // Transform (X != Y) ? X : Y  -> X
8680     if (Pred == ICmpInst::ICMP_NE)
8681       return ReplaceInstUsesWith(SI, TrueVal);
8682     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8683
8684   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8685     // Transform (X == Y) ? Y : X  -> X
8686     if (Pred == ICmpInst::ICMP_EQ)
8687       return ReplaceInstUsesWith(SI, FalseVal);
8688     // Transform (X != Y) ? Y : X  -> Y
8689     if (Pred == ICmpInst::ICMP_NE)
8690       return ReplaceInstUsesWith(SI, TrueVal);
8691     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8692   }
8693
8694   /// NOTE: if we wanted to, this is where to detect integer ABS
8695
8696   return Changed ? &SI : 0;
8697 }
8698
8699 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8700   Value *CondVal = SI.getCondition();
8701   Value *TrueVal = SI.getTrueValue();
8702   Value *FalseVal = SI.getFalseValue();
8703
8704   // select true, X, Y  -> X
8705   // select false, X, Y -> Y
8706   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8707     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8708
8709   // select C, X, X -> X
8710   if (TrueVal == FalseVal)
8711     return ReplaceInstUsesWith(SI, TrueVal);
8712
8713   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8714     return ReplaceInstUsesWith(SI, FalseVal);
8715   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8716     return ReplaceInstUsesWith(SI, TrueVal);
8717   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8718     if (isa<Constant>(TrueVal))
8719       return ReplaceInstUsesWith(SI, TrueVal);
8720     else
8721       return ReplaceInstUsesWith(SI, FalseVal);
8722   }
8723
8724   if (SI.getType() == Type::Int1Ty) {
8725     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8726       if (C->getZExtValue()) {
8727         // Change: A = select B, true, C --> A = or B, C
8728         return BinaryOperator::CreateOr(CondVal, FalseVal);
8729       } else {
8730         // Change: A = select B, false, C --> A = and !B, C
8731         Value *NotCond =
8732           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8733                                              "not."+CondVal->getName()), SI);
8734         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8735       }
8736     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8737       if (C->getZExtValue() == false) {
8738         // Change: A = select B, C, false --> A = and B, C
8739         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8740       } else {
8741         // Change: A = select B, C, true --> A = or !B, C
8742         Value *NotCond =
8743           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8744                                              "not."+CondVal->getName()), SI);
8745         return BinaryOperator::CreateOr(NotCond, TrueVal);
8746       }
8747     }
8748     
8749     // select a, b, a  -> a&b
8750     // select a, a, b  -> a|b
8751     if (CondVal == TrueVal)
8752       return BinaryOperator::CreateOr(CondVal, FalseVal);
8753     else if (CondVal == FalseVal)
8754       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8755   }
8756
8757   // Selecting between two integer constants?
8758   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8759     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8760       // select C, 1, 0 -> zext C to int
8761       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8762         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8763       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8764         // select C, 0, 1 -> zext !C to int
8765         Value *NotCond =
8766           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8767                                                "not."+CondVal->getName()), SI);
8768         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8769       }
8770       
8771       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8772
8773       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8774
8775         // (x <s 0) ? -1 : 0 -> ashr x, 31
8776         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8777           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8778             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8779               // The comparison constant and the result are not neccessarily the
8780               // same width. Make an all-ones value by inserting a AShr.
8781               Value *X = IC->getOperand(0);
8782               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8783               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8784               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8785                                                         ShAmt, "ones");
8786               InsertNewInstBefore(SRA, SI);
8787               
8788               // Finally, convert to the type of the select RHS.  We figure out
8789               // if this requires a SExt, Trunc or BitCast based on the sizes.
8790               Instruction::CastOps opc = Instruction::BitCast;
8791               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8792               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8793               if (SRASize < SISize)
8794                 opc = Instruction::SExt;
8795               else if (SRASize > SISize)
8796                 opc = Instruction::Trunc;
8797               return CastInst::Create(opc, SRA, SI.getType());
8798             }
8799           }
8800
8801
8802         // If one of the constants is zero (we know they can't both be) and we
8803         // have an icmp instruction with zero, and we have an 'and' with the
8804         // non-constant value, eliminate this whole mess.  This corresponds to
8805         // cases like this: ((X & 27) ? 27 : 0)
8806         if (TrueValC->isZero() || FalseValC->isZero())
8807           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8808               cast<Constant>(IC->getOperand(1))->isNullValue())
8809             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8810               if (ICA->getOpcode() == Instruction::And &&
8811                   isa<ConstantInt>(ICA->getOperand(1)) &&
8812                   (ICA->getOperand(1) == TrueValC ||
8813                    ICA->getOperand(1) == FalseValC) &&
8814                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8815                 // Okay, now we know that everything is set up, we just don't
8816                 // know whether we have a icmp_ne or icmp_eq and whether the 
8817                 // true or false val is the zero.
8818                 bool ShouldNotVal = !TrueValC->isZero();
8819                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8820                 Value *V = ICA;
8821                 if (ShouldNotVal)
8822                   V = InsertNewInstBefore(BinaryOperator::Create(
8823                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8824                 return ReplaceInstUsesWith(SI, V);
8825               }
8826       }
8827     }
8828
8829   // See if we are selecting two values based on a comparison of the two values.
8830   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8831     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8832       // Transform (X == Y) ? X : Y  -> Y
8833       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8834         // This is not safe in general for floating point:  
8835         // consider X== -0, Y== +0.
8836         // It becomes safe if either operand is a nonzero constant.
8837         ConstantFP *CFPt, *CFPf;
8838         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8839               !CFPt->getValueAPF().isZero()) ||
8840             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8841              !CFPf->getValueAPF().isZero()))
8842         return ReplaceInstUsesWith(SI, FalseVal);
8843       }
8844       // Transform (X != Y) ? X : Y  -> X
8845       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8846         return ReplaceInstUsesWith(SI, TrueVal);
8847       // NOTE: if we wanted to, this is where to detect MIN/MAX
8848
8849     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8850       // Transform (X == Y) ? Y : X  -> X
8851       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8852         // This is not safe in general for floating point:  
8853         // consider X== -0, Y== +0.
8854         // It becomes safe if either operand is a nonzero constant.
8855         ConstantFP *CFPt, *CFPf;
8856         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8857               !CFPt->getValueAPF().isZero()) ||
8858             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8859              !CFPf->getValueAPF().isZero()))
8860           return ReplaceInstUsesWith(SI, FalseVal);
8861       }
8862       // Transform (X != Y) ? Y : X  -> Y
8863       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8864         return ReplaceInstUsesWith(SI, TrueVal);
8865       // NOTE: if we wanted to, this is where to detect MIN/MAX
8866     }
8867     // NOTE: if we wanted to, this is where to detect ABS
8868   }
8869
8870   // See if we are selecting two values based on a comparison of the two values.
8871   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8872     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8873       return Result;
8874
8875   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8876     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8877       if (TI->hasOneUse() && FI->hasOneUse()) {
8878         Instruction *AddOp = 0, *SubOp = 0;
8879
8880         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8881         if (TI->getOpcode() == FI->getOpcode())
8882           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8883             return IV;
8884
8885         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8886         // even legal for FP.
8887         if (TI->getOpcode() == Instruction::Sub &&
8888             FI->getOpcode() == Instruction::Add) {
8889           AddOp = FI; SubOp = TI;
8890         } else if (FI->getOpcode() == Instruction::Sub &&
8891                    TI->getOpcode() == Instruction::Add) {
8892           AddOp = TI; SubOp = FI;
8893         }
8894
8895         if (AddOp) {
8896           Value *OtherAddOp = 0;
8897           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8898             OtherAddOp = AddOp->getOperand(1);
8899           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8900             OtherAddOp = AddOp->getOperand(0);
8901           }
8902
8903           if (OtherAddOp) {
8904             // So at this point we know we have (Y -> OtherAddOp):
8905             //        select C, (add X, Y), (sub X, Z)
8906             Value *NegVal;  // Compute -Z
8907             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8908               NegVal = ConstantExpr::getNeg(C);
8909             } else {
8910               NegVal = InsertNewInstBefore(
8911                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8912             }
8913
8914             Value *NewTrueOp = OtherAddOp;
8915             Value *NewFalseOp = NegVal;
8916             if (AddOp != TI)
8917               std::swap(NewTrueOp, NewFalseOp);
8918             Instruction *NewSel =
8919               SelectInst::Create(CondVal, NewTrueOp,
8920                                  NewFalseOp, SI.getName() + ".p");
8921
8922             NewSel = InsertNewInstBefore(NewSel, SI);
8923             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8924           }
8925         }
8926       }
8927
8928   // See if we can fold the select into one of our operands.
8929   if (SI.getType()->isInteger()) {
8930     // See the comment above GetSelectFoldableOperands for a description of the
8931     // transformation we are doing here.
8932     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8933       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8934           !isa<Constant>(FalseVal))
8935         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8936           unsigned OpToFold = 0;
8937           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8938             OpToFold = 1;
8939           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8940             OpToFold = 2;
8941           }
8942
8943           if (OpToFold) {
8944             Constant *C = GetSelectFoldableConstant(TVI);
8945             Instruction *NewSel =
8946               SelectInst::Create(SI.getCondition(),
8947                                  TVI->getOperand(2-OpToFold), C);
8948             InsertNewInstBefore(NewSel, SI);
8949             NewSel->takeName(TVI);
8950             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8951               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8952             else {
8953               assert(0 && "Unknown instruction!!");
8954             }
8955           }
8956         }
8957
8958     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8959       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8960           !isa<Constant>(TrueVal))
8961         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8962           unsigned OpToFold = 0;
8963           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8964             OpToFold = 1;
8965           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8966             OpToFold = 2;
8967           }
8968
8969           if (OpToFold) {
8970             Constant *C = GetSelectFoldableConstant(FVI);
8971             Instruction *NewSel =
8972               SelectInst::Create(SI.getCondition(), C,
8973                                  FVI->getOperand(2-OpToFold));
8974             InsertNewInstBefore(NewSel, SI);
8975             NewSel->takeName(FVI);
8976             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8977               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8978             else
8979               assert(0 && "Unknown instruction!!");
8980           }
8981         }
8982   }
8983
8984   if (BinaryOperator::isNot(CondVal)) {
8985     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8986     SI.setOperand(1, FalseVal);
8987     SI.setOperand(2, TrueVal);
8988     return &SI;
8989   }
8990
8991   return 0;
8992 }
8993
8994 /// EnforceKnownAlignment - If the specified pointer points to an object that
8995 /// we control, modify the object's alignment to PrefAlign. This isn't
8996 /// often possible though. If alignment is important, a more reliable approach
8997 /// is to simply align all global variables and allocation instructions to
8998 /// their preferred alignment from the beginning.
8999 ///
9000 static unsigned EnforceKnownAlignment(Value *V,
9001                                       unsigned Align, unsigned PrefAlign) {
9002
9003   User *U = dyn_cast<User>(V);
9004   if (!U) return Align;
9005
9006   switch (getOpcode(U)) {
9007   default: break;
9008   case Instruction::BitCast:
9009     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9010   case Instruction::GetElementPtr: {
9011     // If all indexes are zero, it is just the alignment of the base pointer.
9012     bool AllZeroOperands = true;
9013     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9014       if (!isa<Constant>(*i) ||
9015           !cast<Constant>(*i)->isNullValue()) {
9016         AllZeroOperands = false;
9017         break;
9018       }
9019
9020     if (AllZeroOperands) {
9021       // Treat this like a bitcast.
9022       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9023     }
9024     break;
9025   }
9026   }
9027
9028   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9029     // If there is a large requested alignment and we can, bump up the alignment
9030     // of the global.
9031     if (!GV->isDeclaration()) {
9032       GV->setAlignment(PrefAlign);
9033       Align = PrefAlign;
9034     }
9035   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9036     // If there is a requested alignment and if this is an alloca, round up.  We
9037     // don't do this for malloc, because some systems can't respect the request.
9038     if (isa<AllocaInst>(AI)) {
9039       AI->setAlignment(PrefAlign);
9040       Align = PrefAlign;
9041     }
9042   }
9043
9044   return Align;
9045 }
9046
9047 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9048 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9049 /// and it is more than the alignment of the ultimate object, see if we can
9050 /// increase the alignment of the ultimate object, making this check succeed.
9051 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9052                                                   unsigned PrefAlign) {
9053   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9054                       sizeof(PrefAlign) * CHAR_BIT;
9055   APInt Mask = APInt::getAllOnesValue(BitWidth);
9056   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9057   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9058   unsigned TrailZ = KnownZero.countTrailingOnes();
9059   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9060
9061   if (PrefAlign > Align)
9062     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9063   
9064     // We don't need to make any adjustment.
9065   return Align;
9066 }
9067
9068 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9069   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9070   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9071   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9072   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9073
9074   if (CopyAlign < MinAlign) {
9075     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9076     return MI;
9077   }
9078   
9079   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9080   // load/store.
9081   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9082   if (MemOpLength == 0) return 0;
9083   
9084   // Source and destination pointer types are always "i8*" for intrinsic.  See
9085   // if the size is something we can handle with a single primitive load/store.
9086   // A single load+store correctly handles overlapping memory in the memmove
9087   // case.
9088   unsigned Size = MemOpLength->getZExtValue();
9089   if (Size == 0) return MI;  // Delete this mem transfer.
9090   
9091   if (Size > 8 || (Size&(Size-1)))
9092     return 0;  // If not 1/2/4/8 bytes, exit.
9093   
9094   // Use an integer load+store unless we can find something better.
9095   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9096   
9097   // Memcpy forces the use of i8* for the source and destination.  That means
9098   // that if you're using memcpy to move one double around, you'll get a cast
9099   // from double* to i8*.  We'd much rather use a double load+store rather than
9100   // an i64 load+store, here because this improves the odds that the source or
9101   // dest address will be promotable.  See if we can find a better type than the
9102   // integer datatype.
9103   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9104     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9105     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9106       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9107       // down through these levels if so.
9108       while (!SrcETy->isSingleValueType()) {
9109         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9110           if (STy->getNumElements() == 1)
9111             SrcETy = STy->getElementType(0);
9112           else
9113             break;
9114         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9115           if (ATy->getNumElements() == 1)
9116             SrcETy = ATy->getElementType();
9117           else
9118             break;
9119         } else
9120           break;
9121       }
9122       
9123       if (SrcETy->isSingleValueType())
9124         NewPtrTy = PointerType::getUnqual(SrcETy);
9125     }
9126   }
9127   
9128   
9129   // If the memcpy/memmove provides better alignment info than we can
9130   // infer, use it.
9131   SrcAlign = std::max(SrcAlign, CopyAlign);
9132   DstAlign = std::max(DstAlign, CopyAlign);
9133   
9134   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9135   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9136   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9137   InsertNewInstBefore(L, *MI);
9138   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9139
9140   // Set the size of the copy to 0, it will be deleted on the next iteration.
9141   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9142   return MI;
9143 }
9144
9145 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9146   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9147   if (MI->getAlignment()->getZExtValue() < Alignment) {
9148     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9149     return MI;
9150   }
9151   
9152   // Extract the length and alignment and fill if they are constant.
9153   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9154   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9155   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9156     return 0;
9157   uint64_t Len = LenC->getZExtValue();
9158   Alignment = MI->getAlignment()->getZExtValue();
9159   
9160   // If the length is zero, this is a no-op
9161   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9162   
9163   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9164   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9165     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9166     
9167     Value *Dest = MI->getDest();
9168     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9169
9170     // Alignment 0 is identity for alignment 1 for memset, but not store.
9171     if (Alignment == 0) Alignment = 1;
9172     
9173     // Extract the fill value and store.
9174     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9175     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9176                                       Alignment), *MI);
9177     
9178     // Set the size of the copy to 0, it will be deleted on the next iteration.
9179     MI->setLength(Constant::getNullValue(LenC->getType()));
9180     return MI;
9181   }
9182
9183   return 0;
9184 }
9185
9186
9187 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9188 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9189 /// the heavy lifting.
9190 ///
9191 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9192   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9193   if (!II) return visitCallSite(&CI);
9194   
9195   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9196   // visitCallSite.
9197   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9198     bool Changed = false;
9199
9200     // memmove/cpy/set of zero bytes is a noop.
9201     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9202       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9203
9204       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9205         if (CI->getZExtValue() == 1) {
9206           // Replace the instruction with just byte operations.  We would
9207           // transform other cases to loads/stores, but we don't know if
9208           // alignment is sufficient.
9209         }
9210     }
9211
9212     // If we have a memmove and the source operation is a constant global,
9213     // then the source and dest pointers can't alias, so we can change this
9214     // into a call to memcpy.
9215     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9216       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9217         if (GVSrc->isConstant()) {
9218           Module *M = CI.getParent()->getParent()->getParent();
9219           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9220           const Type *Tys[1];
9221           Tys[0] = CI.getOperand(3)->getType();
9222           CI.setOperand(0, 
9223                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9224           Changed = true;
9225         }
9226
9227       // memmove(x,x,size) -> noop.
9228       if (MMI->getSource() == MMI->getDest())
9229         return EraseInstFromFunction(CI);
9230     }
9231
9232     // If we can determine a pointer alignment that is bigger than currently
9233     // set, update the alignment.
9234     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9235       if (Instruction *I = SimplifyMemTransfer(MI))
9236         return I;
9237     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9238       if (Instruction *I = SimplifyMemSet(MSI))
9239         return I;
9240     }
9241           
9242     if (Changed) return II;
9243   }
9244   
9245   switch (II->getIntrinsicID()) {
9246   default: break;
9247   case Intrinsic::bswap:
9248     // bswap(bswap(x)) -> x
9249     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9250       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9251         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9252     break;
9253   case Intrinsic::ppc_altivec_lvx:
9254   case Intrinsic::ppc_altivec_lvxl:
9255   case Intrinsic::x86_sse_loadu_ps:
9256   case Intrinsic::x86_sse2_loadu_pd:
9257   case Intrinsic::x86_sse2_loadu_dq:
9258     // Turn PPC lvx     -> load if the pointer is known aligned.
9259     // Turn X86 loadups -> load if the pointer is known aligned.
9260     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9261       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9262                                        PointerType::getUnqual(II->getType()),
9263                                        CI);
9264       return new LoadInst(Ptr);
9265     }
9266     break;
9267   case Intrinsic::ppc_altivec_stvx:
9268   case Intrinsic::ppc_altivec_stvxl:
9269     // Turn stvx -> store if the pointer is known aligned.
9270     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9271       const Type *OpPtrTy = 
9272         PointerType::getUnqual(II->getOperand(1)->getType());
9273       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9274       return new StoreInst(II->getOperand(1), Ptr);
9275     }
9276     break;
9277   case Intrinsic::x86_sse_storeu_ps:
9278   case Intrinsic::x86_sse2_storeu_pd:
9279   case Intrinsic::x86_sse2_storeu_dq:
9280     // Turn X86 storeu -> store if the pointer is known aligned.
9281     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9282       const Type *OpPtrTy = 
9283         PointerType::getUnqual(II->getOperand(2)->getType());
9284       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9285       return new StoreInst(II->getOperand(2), Ptr);
9286     }
9287     break;
9288     
9289   case Intrinsic::x86_sse_cvttss2si: {
9290     // These intrinsics only demands the 0th element of its input vector.  If
9291     // we can simplify the input based on that, do so now.
9292     uint64_t UndefElts;
9293     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9294                                               UndefElts)) {
9295       II->setOperand(1, V);
9296       return II;
9297     }
9298     break;
9299   }
9300     
9301   case Intrinsic::ppc_altivec_vperm:
9302     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9303     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9304       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9305       
9306       // Check that all of the elements are integer constants or undefs.
9307       bool AllEltsOk = true;
9308       for (unsigned i = 0; i != 16; ++i) {
9309         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9310             !isa<UndefValue>(Mask->getOperand(i))) {
9311           AllEltsOk = false;
9312           break;
9313         }
9314       }
9315       
9316       if (AllEltsOk) {
9317         // Cast the input vectors to byte vectors.
9318         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9319         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9320         Value *Result = UndefValue::get(Op0->getType());
9321         
9322         // Only extract each element once.
9323         Value *ExtractedElts[32];
9324         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9325         
9326         for (unsigned i = 0; i != 16; ++i) {
9327           if (isa<UndefValue>(Mask->getOperand(i)))
9328             continue;
9329           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9330           Idx &= 31;  // Match the hardware behavior.
9331           
9332           if (ExtractedElts[Idx] == 0) {
9333             Instruction *Elt = 
9334               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9335             InsertNewInstBefore(Elt, CI);
9336             ExtractedElts[Idx] = Elt;
9337           }
9338         
9339           // Insert this value into the result vector.
9340           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9341                                              i, "tmp");
9342           InsertNewInstBefore(cast<Instruction>(Result), CI);
9343         }
9344         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9345       }
9346     }
9347     break;
9348
9349   case Intrinsic::stackrestore: {
9350     // If the save is right next to the restore, remove the restore.  This can
9351     // happen when variable allocas are DCE'd.
9352     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9353       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9354         BasicBlock::iterator BI = SS;
9355         if (&*++BI == II)
9356           return EraseInstFromFunction(CI);
9357       }
9358     }
9359     
9360     // Scan down this block to see if there is another stack restore in the
9361     // same block without an intervening call/alloca.
9362     BasicBlock::iterator BI = II;
9363     TerminatorInst *TI = II->getParent()->getTerminator();
9364     bool CannotRemove = false;
9365     for (++BI; &*BI != TI; ++BI) {
9366       if (isa<AllocaInst>(BI)) {
9367         CannotRemove = true;
9368         break;
9369       }
9370       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9371         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9372           // If there is a stackrestore below this one, remove this one.
9373           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9374             return EraseInstFromFunction(CI);
9375           // Otherwise, ignore the intrinsic.
9376         } else {
9377           // If we found a non-intrinsic call, we can't remove the stack
9378           // restore.
9379           CannotRemove = true;
9380           break;
9381         }
9382       }
9383     }
9384     
9385     // If the stack restore is in a return/unwind block and if there are no
9386     // allocas or calls between the restore and the return, nuke the restore.
9387     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9388       return EraseInstFromFunction(CI);
9389     break;
9390   }
9391   }
9392
9393   return visitCallSite(II);
9394 }
9395
9396 // InvokeInst simplification
9397 //
9398 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9399   return visitCallSite(&II);
9400 }
9401
9402 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9403 /// passed through the varargs area, we can eliminate the use of the cast.
9404 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9405                                          const CastInst * const CI,
9406                                          const TargetData * const TD,
9407                                          const int ix) {
9408   if (!CI->isLosslessCast())
9409     return false;
9410
9411   // The size of ByVal arguments is derived from the type, so we
9412   // can't change to a type with a different size.  If the size were
9413   // passed explicitly we could avoid this check.
9414   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9415     return true;
9416
9417   const Type* SrcTy = 
9418             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9419   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9420   if (!SrcTy->isSized() || !DstTy->isSized())
9421     return false;
9422   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9423     return false;
9424   return true;
9425 }
9426
9427 // visitCallSite - Improvements for call and invoke instructions.
9428 //
9429 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9430   bool Changed = false;
9431
9432   // If the callee is a constexpr cast of a function, attempt to move the cast
9433   // to the arguments of the call/invoke.
9434   if (transformConstExprCastCall(CS)) return 0;
9435
9436   Value *Callee = CS.getCalledValue();
9437
9438   if (Function *CalleeF = dyn_cast<Function>(Callee))
9439     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9440       Instruction *OldCall = CS.getInstruction();
9441       // If the call and callee calling conventions don't match, this call must
9442       // be unreachable, as the call is undefined.
9443       new StoreInst(ConstantInt::getTrue(),
9444                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9445                                     OldCall);
9446       if (!OldCall->use_empty())
9447         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9448       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9449         return EraseInstFromFunction(*OldCall);
9450       return 0;
9451     }
9452
9453   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9454     // This instruction is not reachable, just remove it.  We insert a store to
9455     // undef so that we know that this code is not reachable, despite the fact
9456     // that we can't modify the CFG here.
9457     new StoreInst(ConstantInt::getTrue(),
9458                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9459                   CS.getInstruction());
9460
9461     if (!CS.getInstruction()->use_empty())
9462       CS.getInstruction()->
9463         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9464
9465     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9466       // Don't break the CFG, insert a dummy cond branch.
9467       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9468                          ConstantInt::getTrue(), II);
9469     }
9470     return EraseInstFromFunction(*CS.getInstruction());
9471   }
9472
9473   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9474     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9475       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9476         return transformCallThroughTrampoline(CS);
9477
9478   const PointerType *PTy = cast<PointerType>(Callee->getType());
9479   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9480   if (FTy->isVarArg()) {
9481     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9482     // See if we can optimize any arguments passed through the varargs area of
9483     // the call.
9484     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9485            E = CS.arg_end(); I != E; ++I, ++ix) {
9486       CastInst *CI = dyn_cast<CastInst>(*I);
9487       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9488         *I = CI->getOperand(0);
9489         Changed = true;
9490       }
9491     }
9492   }
9493
9494   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9495     // Inline asm calls cannot throw - mark them 'nounwind'.
9496     CS.setDoesNotThrow();
9497     Changed = true;
9498   }
9499
9500   return Changed ? CS.getInstruction() : 0;
9501 }
9502
9503 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9504 // attempt to move the cast to the arguments of the call/invoke.
9505 //
9506 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9507   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9508   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9509   if (CE->getOpcode() != Instruction::BitCast || 
9510       !isa<Function>(CE->getOperand(0)))
9511     return false;
9512   Function *Callee = cast<Function>(CE->getOperand(0));
9513   Instruction *Caller = CS.getInstruction();
9514   const AttrListPtr &CallerPAL = CS.getAttributes();
9515
9516   // Okay, this is a cast from a function to a different type.  Unless doing so
9517   // would cause a type conversion of one of our arguments, change this call to
9518   // be a direct call with arguments casted to the appropriate types.
9519   //
9520   const FunctionType *FT = Callee->getFunctionType();
9521   const Type *OldRetTy = Caller->getType();
9522   const Type *NewRetTy = FT->getReturnType();
9523
9524   if (isa<StructType>(NewRetTy))
9525     return false; // TODO: Handle multiple return values.
9526
9527   // Check to see if we are changing the return type...
9528   if (OldRetTy != NewRetTy) {
9529     if (Callee->isDeclaration() &&
9530         // Conversion is ok if changing from one pointer type to another or from
9531         // a pointer to an integer of the same size.
9532         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9533           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9534       return false;   // Cannot transform this return value.
9535
9536     if (!Caller->use_empty() &&
9537         // void -> non-void is handled specially
9538         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9539       return false;   // Cannot transform this return value.
9540
9541     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9542       Attributes RAttrs = CallerPAL.getRetAttributes();
9543       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9544         return false;   // Attribute not compatible with transformed value.
9545     }
9546
9547     // If the callsite is an invoke instruction, and the return value is used by
9548     // a PHI node in a successor, we cannot change the return type of the call
9549     // because there is no place to put the cast instruction (without breaking
9550     // the critical edge).  Bail out in this case.
9551     if (!Caller->use_empty())
9552       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9553         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9554              UI != E; ++UI)
9555           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9556             if (PN->getParent() == II->getNormalDest() ||
9557                 PN->getParent() == II->getUnwindDest())
9558               return false;
9559   }
9560
9561   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9562   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9563
9564   CallSite::arg_iterator AI = CS.arg_begin();
9565   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9566     const Type *ParamTy = FT->getParamType(i);
9567     const Type *ActTy = (*AI)->getType();
9568
9569     if (!CastInst::isCastable(ActTy, ParamTy))
9570       return false;   // Cannot transform this parameter value.
9571
9572     if (CallerPAL.getParamAttributes(i + 1) 
9573         & Attribute::typeIncompatible(ParamTy))
9574       return false;   // Attribute not compatible with transformed value.
9575
9576     // Converting from one pointer type to another or between a pointer and an
9577     // integer of the same size is safe even if we do not have a body.
9578     bool isConvertible = ActTy == ParamTy ||
9579       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9580        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9581     if (Callee->isDeclaration() && !isConvertible) return false;
9582   }
9583
9584   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9585       Callee->isDeclaration())
9586     return false;   // Do not delete arguments unless we have a function body.
9587
9588   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9589       !CallerPAL.isEmpty())
9590     // In this case we have more arguments than the new function type, but we
9591     // won't be dropping them.  Check that these extra arguments have attributes
9592     // that are compatible with being a vararg call argument.
9593     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9594       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9595         break;
9596       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9597       if (PAttrs & Attribute::VarArgsIncompatible)
9598         return false;
9599     }
9600
9601   // Okay, we decided that this is a safe thing to do: go ahead and start
9602   // inserting cast instructions as necessary...
9603   std::vector<Value*> Args;
9604   Args.reserve(NumActualArgs);
9605   SmallVector<AttributeWithIndex, 8> attrVec;
9606   attrVec.reserve(NumCommonArgs);
9607
9608   // Get any return attributes.
9609   Attributes RAttrs = CallerPAL.getRetAttributes();
9610
9611   // If the return value is not being used, the type may not be compatible
9612   // with the existing attributes.  Wipe out any problematic attributes.
9613   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9614
9615   // Add the new return attributes.
9616   if (RAttrs)
9617     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9618
9619   AI = CS.arg_begin();
9620   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9621     const Type *ParamTy = FT->getParamType(i);
9622     if ((*AI)->getType() == ParamTy) {
9623       Args.push_back(*AI);
9624     } else {
9625       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9626           false, ParamTy, false);
9627       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9628       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9629     }
9630
9631     // Add any parameter attributes.
9632     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9633       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9634   }
9635
9636   // If the function takes more arguments than the call was taking, add them
9637   // now...
9638   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9639     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9640
9641   // If we are removing arguments to the function, emit an obnoxious warning...
9642   if (FT->getNumParams() < NumActualArgs) {
9643     if (!FT->isVarArg()) {
9644       cerr << "WARNING: While resolving call to function '"
9645            << Callee->getName() << "' arguments were dropped!\n";
9646     } else {
9647       // Add all of the arguments in their promoted form to the arg list...
9648       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9649         const Type *PTy = getPromotedType((*AI)->getType());
9650         if (PTy != (*AI)->getType()) {
9651           // Must promote to pass through va_arg area!
9652           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9653                                                                 PTy, false);
9654           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9655           InsertNewInstBefore(Cast, *Caller);
9656           Args.push_back(Cast);
9657         } else {
9658           Args.push_back(*AI);
9659         }
9660
9661         // Add any parameter attributes.
9662         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9663           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9664       }
9665     }
9666   }
9667
9668   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9669     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9670
9671   if (NewRetTy == Type::VoidTy)
9672     Caller->setName("");   // Void type should not have a name.
9673
9674   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9675
9676   Instruction *NC;
9677   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9678     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9679                             Args.begin(), Args.end(),
9680                             Caller->getName(), Caller);
9681     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9682     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9683   } else {
9684     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9685                           Caller->getName(), Caller);
9686     CallInst *CI = cast<CallInst>(Caller);
9687     if (CI->isTailCall())
9688       cast<CallInst>(NC)->setTailCall();
9689     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9690     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9691   }
9692
9693   // Insert a cast of the return type as necessary.
9694   Value *NV = NC;
9695   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9696     if (NV->getType() != Type::VoidTy) {
9697       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9698                                                             OldRetTy, false);
9699       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9700
9701       // If this is an invoke instruction, we should insert it after the first
9702       // non-phi, instruction in the normal successor block.
9703       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9704         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9705         InsertNewInstBefore(NC, *I);
9706       } else {
9707         // Otherwise, it's a call, just insert cast right after the call instr
9708         InsertNewInstBefore(NC, *Caller);
9709       }
9710       AddUsersToWorkList(*Caller);
9711     } else {
9712       NV = UndefValue::get(Caller->getType());
9713     }
9714   }
9715
9716   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9717     Caller->replaceAllUsesWith(NV);
9718   Caller->eraseFromParent();
9719   RemoveFromWorkList(Caller);
9720   return true;
9721 }
9722
9723 // transformCallThroughTrampoline - Turn a call to a function created by the
9724 // init_trampoline intrinsic into a direct call to the underlying function.
9725 //
9726 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9727   Value *Callee = CS.getCalledValue();
9728   const PointerType *PTy = cast<PointerType>(Callee->getType());
9729   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9730   const AttrListPtr &Attrs = CS.getAttributes();
9731
9732   // If the call already has the 'nest' attribute somewhere then give up -
9733   // otherwise 'nest' would occur twice after splicing in the chain.
9734   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9735     return 0;
9736
9737   IntrinsicInst *Tramp =
9738     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9739
9740   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9741   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9742   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9743
9744   const AttrListPtr &NestAttrs = NestF->getAttributes();
9745   if (!NestAttrs.isEmpty()) {
9746     unsigned NestIdx = 1;
9747     const Type *NestTy = 0;
9748     Attributes NestAttr = Attribute::None;
9749
9750     // Look for a parameter marked with the 'nest' attribute.
9751     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9752          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9753       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9754         // Record the parameter type and any other attributes.
9755         NestTy = *I;
9756         NestAttr = NestAttrs.getParamAttributes(NestIdx);
9757         break;
9758       }
9759
9760     if (NestTy) {
9761       Instruction *Caller = CS.getInstruction();
9762       std::vector<Value*> NewArgs;
9763       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9764
9765       SmallVector<AttributeWithIndex, 8> NewAttrs;
9766       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9767
9768       // Insert the nest argument into the call argument list, which may
9769       // mean appending it.  Likewise for attributes.
9770
9771       // Add any result attributes.
9772       if (Attributes Attr = Attrs.getRetAttributes())
9773         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9774
9775       {
9776         unsigned Idx = 1;
9777         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9778         do {
9779           if (Idx == NestIdx) {
9780             // Add the chain argument and attributes.
9781             Value *NestVal = Tramp->getOperand(3);
9782             if (NestVal->getType() != NestTy)
9783               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9784             NewArgs.push_back(NestVal);
9785             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9786           }
9787
9788           if (I == E)
9789             break;
9790
9791           // Add the original argument and attributes.
9792           NewArgs.push_back(*I);
9793           if (Attributes Attr = Attrs.getParamAttributes(Idx))
9794             NewAttrs.push_back
9795               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9796
9797           ++Idx, ++I;
9798         } while (1);
9799       }
9800
9801       // Add any function attributes.
9802       if (Attributes Attr = Attrs.getFnAttributes())
9803         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9804
9805       // The trampoline may have been bitcast to a bogus type (FTy).
9806       // Handle this by synthesizing a new function type, equal to FTy
9807       // with the chain parameter inserted.
9808
9809       std::vector<const Type*> NewTypes;
9810       NewTypes.reserve(FTy->getNumParams()+1);
9811
9812       // Insert the chain's type into the list of parameter types, which may
9813       // mean appending it.
9814       {
9815         unsigned Idx = 1;
9816         FunctionType::param_iterator I = FTy->param_begin(),
9817           E = FTy->param_end();
9818
9819         do {
9820           if (Idx == NestIdx)
9821             // Add the chain's type.
9822             NewTypes.push_back(NestTy);
9823
9824           if (I == E)
9825             break;
9826
9827           // Add the original type.
9828           NewTypes.push_back(*I);
9829
9830           ++Idx, ++I;
9831         } while (1);
9832       }
9833
9834       // Replace the trampoline call with a direct call.  Let the generic
9835       // code sort out any function type mismatches.
9836       FunctionType *NewFTy =
9837         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9838       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9839         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9840       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
9841
9842       Instruction *NewCaller;
9843       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9844         NewCaller = InvokeInst::Create(NewCallee,
9845                                        II->getNormalDest(), II->getUnwindDest(),
9846                                        NewArgs.begin(), NewArgs.end(),
9847                                        Caller->getName(), Caller);
9848         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9849         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
9850       } else {
9851         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9852                                      Caller->getName(), Caller);
9853         if (cast<CallInst>(Caller)->isTailCall())
9854           cast<CallInst>(NewCaller)->setTailCall();
9855         cast<CallInst>(NewCaller)->
9856           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9857         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
9858       }
9859       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9860         Caller->replaceAllUsesWith(NewCaller);
9861       Caller->eraseFromParent();
9862       RemoveFromWorkList(Caller);
9863       return 0;
9864     }
9865   }
9866
9867   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9868   // parameter, there is no need to adjust the argument list.  Let the generic
9869   // code sort out any function type mismatches.
9870   Constant *NewCallee =
9871     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9872   CS.setCalledFunction(NewCallee);
9873   return CS.getInstruction();
9874 }
9875
9876 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9877 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9878 /// and a single binop.
9879 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9880   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9881   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9882          isa<CmpInst>(FirstInst));
9883   unsigned Opc = FirstInst->getOpcode();
9884   Value *LHSVal = FirstInst->getOperand(0);
9885   Value *RHSVal = FirstInst->getOperand(1);
9886     
9887   const Type *LHSType = LHSVal->getType();
9888   const Type *RHSType = RHSVal->getType();
9889   
9890   // Scan to see if all operands are the same opcode, all have one use, and all
9891   // kill their operands (i.e. the operands have one use).
9892   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9893     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9894     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9895         // Verify type of the LHS matches so we don't fold cmp's of different
9896         // types or GEP's with different index types.
9897         I->getOperand(0)->getType() != LHSType ||
9898         I->getOperand(1)->getType() != RHSType)
9899       return 0;
9900
9901     // If they are CmpInst instructions, check their predicates
9902     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9903       if (cast<CmpInst>(I)->getPredicate() !=
9904           cast<CmpInst>(FirstInst)->getPredicate())
9905         return 0;
9906     
9907     // Keep track of which operand needs a phi node.
9908     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9909     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9910   }
9911   
9912   // Otherwise, this is safe to transform, determine if it is profitable.
9913
9914   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9915   // Indexes are often folded into load/store instructions, so we don't want to
9916   // hide them behind a phi.
9917   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9918     return 0;
9919   
9920   Value *InLHS = FirstInst->getOperand(0);
9921   Value *InRHS = FirstInst->getOperand(1);
9922   PHINode *NewLHS = 0, *NewRHS = 0;
9923   if (LHSVal == 0) {
9924     NewLHS = PHINode::Create(LHSType,
9925                              FirstInst->getOperand(0)->getName() + ".pn");
9926     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9927     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9928     InsertNewInstBefore(NewLHS, PN);
9929     LHSVal = NewLHS;
9930   }
9931   
9932   if (RHSVal == 0) {
9933     NewRHS = PHINode::Create(RHSType,
9934                              FirstInst->getOperand(1)->getName() + ".pn");
9935     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9936     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9937     InsertNewInstBefore(NewRHS, PN);
9938     RHSVal = NewRHS;
9939   }
9940   
9941   // Add all operands to the new PHIs.
9942   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9943     if (NewLHS) {
9944       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9945       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9946     }
9947     if (NewRHS) {
9948       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9949       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9950     }
9951   }
9952     
9953   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9954     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9955   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9956     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9957                            RHSVal);
9958   else {
9959     assert(isa<GetElementPtrInst>(FirstInst));
9960     return GetElementPtrInst::Create(LHSVal, RHSVal);
9961   }
9962 }
9963
9964 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9965 /// of the block that defines it.  This means that it must be obvious the value
9966 /// of the load is not changed from the point of the load to the end of the
9967 /// block it is in.
9968 ///
9969 /// Finally, it is safe, but not profitable, to sink a load targetting a
9970 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9971 /// to a register.
9972 static bool isSafeToSinkLoad(LoadInst *L) {
9973   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9974   
9975   for (++BBI; BBI != E; ++BBI)
9976     if (BBI->mayWriteToMemory())
9977       return false;
9978   
9979   // Check for non-address taken alloca.  If not address-taken already, it isn't
9980   // profitable to do this xform.
9981   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9982     bool isAddressTaken = false;
9983     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9984          UI != E; ++UI) {
9985       if (isa<LoadInst>(UI)) continue;
9986       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9987         // If storing TO the alloca, then the address isn't taken.
9988         if (SI->getOperand(1) == AI) continue;
9989       }
9990       isAddressTaken = true;
9991       break;
9992     }
9993     
9994     if (!isAddressTaken)
9995       return false;
9996   }
9997   
9998   return true;
9999 }
10000
10001
10002 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10003 // operator and they all are only used by the PHI, PHI together their
10004 // inputs, and do the operation once, to the result of the PHI.
10005 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10006   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10007
10008   // Scan the instruction, looking for input operations that can be folded away.
10009   // If all input operands to the phi are the same instruction (e.g. a cast from
10010   // the same type or "+42") we can pull the operation through the PHI, reducing
10011   // code size and simplifying code.
10012   Constant *ConstantOp = 0;
10013   const Type *CastSrcTy = 0;
10014   bool isVolatile = false;
10015   if (isa<CastInst>(FirstInst)) {
10016     CastSrcTy = FirstInst->getOperand(0)->getType();
10017   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10018     // Can fold binop, compare or shift here if the RHS is a constant, 
10019     // otherwise call FoldPHIArgBinOpIntoPHI.
10020     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10021     if (ConstantOp == 0)
10022       return FoldPHIArgBinOpIntoPHI(PN);
10023   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10024     isVolatile = LI->isVolatile();
10025     // We can't sink the load if the loaded value could be modified between the
10026     // load and the PHI.
10027     if (LI->getParent() != PN.getIncomingBlock(0) ||
10028         !isSafeToSinkLoad(LI))
10029       return 0;
10030     
10031     // If the PHI is of volatile loads and the load block has multiple
10032     // successors, sinking it would remove a load of the volatile value from
10033     // the path through the other successor.
10034     if (isVolatile &&
10035         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10036       return 0;
10037     
10038   } else if (isa<GetElementPtrInst>(FirstInst)) {
10039     if (FirstInst->getNumOperands() == 2)
10040       return FoldPHIArgBinOpIntoPHI(PN);
10041     // Can't handle general GEPs yet.
10042     return 0;
10043   } else {
10044     return 0;  // Cannot fold this operation.
10045   }
10046
10047   // Check to see if all arguments are the same operation.
10048   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10049     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10050     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10051     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10052       return 0;
10053     if (CastSrcTy) {
10054       if (I->getOperand(0)->getType() != CastSrcTy)
10055         return 0;  // Cast operation must match.
10056     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10057       // We can't sink the load if the loaded value could be modified between 
10058       // the load and the PHI.
10059       if (LI->isVolatile() != isVolatile ||
10060           LI->getParent() != PN.getIncomingBlock(i) ||
10061           !isSafeToSinkLoad(LI))
10062         return 0;
10063       
10064       // If the PHI is of volatile loads and the load block has multiple
10065       // successors, sinking it would remove a load of the volatile value from
10066       // the path through the other successor.
10067       if (isVolatile &&
10068           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10069         return 0;
10070
10071       
10072     } else if (I->getOperand(1) != ConstantOp) {
10073       return 0;
10074     }
10075   }
10076
10077   // Okay, they are all the same operation.  Create a new PHI node of the
10078   // correct type, and PHI together all of the LHS's of the instructions.
10079   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10080                                    PN.getName()+".in");
10081   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10082
10083   Value *InVal = FirstInst->getOperand(0);
10084   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10085
10086   // Add all operands to the new PHI.
10087   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10088     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10089     if (NewInVal != InVal)
10090       InVal = 0;
10091     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10092   }
10093
10094   Value *PhiVal;
10095   if (InVal) {
10096     // The new PHI unions all of the same values together.  This is really
10097     // common, so we handle it intelligently here for compile-time speed.
10098     PhiVal = InVal;
10099     delete NewPN;
10100   } else {
10101     InsertNewInstBefore(NewPN, PN);
10102     PhiVal = NewPN;
10103   }
10104
10105   // Insert and return the new operation.
10106   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10107     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10108   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10109     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10110   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10111     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10112                            PhiVal, ConstantOp);
10113   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10114   
10115   // If this was a volatile load that we are merging, make sure to loop through
10116   // and mark all the input loads as non-volatile.  If we don't do this, we will
10117   // insert a new volatile load and the old ones will not be deletable.
10118   if (isVolatile)
10119     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10120       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10121   
10122   return new LoadInst(PhiVal, "", isVolatile);
10123 }
10124
10125 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10126 /// that is dead.
10127 static bool DeadPHICycle(PHINode *PN,
10128                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10129   if (PN->use_empty()) return true;
10130   if (!PN->hasOneUse()) return false;
10131
10132   // Remember this node, and if we find the cycle, return.
10133   if (!PotentiallyDeadPHIs.insert(PN))
10134     return true;
10135   
10136   // Don't scan crazily complex things.
10137   if (PotentiallyDeadPHIs.size() == 16)
10138     return false;
10139
10140   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10141     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10142
10143   return false;
10144 }
10145
10146 /// PHIsEqualValue - Return true if this phi node is always equal to
10147 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10148 ///   z = some value; x = phi (y, z); y = phi (x, z)
10149 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10150                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10151   // See if we already saw this PHI node.
10152   if (!ValueEqualPHIs.insert(PN))
10153     return true;
10154   
10155   // Don't scan crazily complex things.
10156   if (ValueEqualPHIs.size() == 16)
10157     return false;
10158  
10159   // Scan the operands to see if they are either phi nodes or are equal to
10160   // the value.
10161   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10162     Value *Op = PN->getIncomingValue(i);
10163     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10164       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10165         return false;
10166     } else if (Op != NonPhiInVal)
10167       return false;
10168   }
10169   
10170   return true;
10171 }
10172
10173
10174 // PHINode simplification
10175 //
10176 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10177   // If LCSSA is around, don't mess with Phi nodes
10178   if (MustPreserveLCSSA) return 0;
10179   
10180   if (Value *V = PN.hasConstantValue())
10181     return ReplaceInstUsesWith(PN, V);
10182
10183   // If all PHI operands are the same operation, pull them through the PHI,
10184   // reducing code size.
10185   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10186       PN.getIncomingValue(0)->hasOneUse())
10187     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10188       return Result;
10189
10190   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10191   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10192   // PHI)... break the cycle.
10193   if (PN.hasOneUse()) {
10194     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10195     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10196       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10197       PotentiallyDeadPHIs.insert(&PN);
10198       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10199         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10200     }
10201    
10202     // If this phi has a single use, and if that use just computes a value for
10203     // the next iteration of a loop, delete the phi.  This occurs with unused
10204     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10205     // common case here is good because the only other things that catch this
10206     // are induction variable analysis (sometimes) and ADCE, which is only run
10207     // late.
10208     if (PHIUser->hasOneUse() &&
10209         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10210         PHIUser->use_back() == &PN) {
10211       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10212     }
10213   }
10214
10215   // We sometimes end up with phi cycles that non-obviously end up being the
10216   // same value, for example:
10217   //   z = some value; x = phi (y, z); y = phi (x, z)
10218   // where the phi nodes don't necessarily need to be in the same block.  Do a
10219   // quick check to see if the PHI node only contains a single non-phi value, if
10220   // so, scan to see if the phi cycle is actually equal to that value.
10221   {
10222     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10223     // Scan for the first non-phi operand.
10224     while (InValNo != NumOperandVals && 
10225            isa<PHINode>(PN.getIncomingValue(InValNo)))
10226       ++InValNo;
10227
10228     if (InValNo != NumOperandVals) {
10229       Value *NonPhiInVal = PN.getOperand(InValNo);
10230       
10231       // Scan the rest of the operands to see if there are any conflicts, if so
10232       // there is no need to recursively scan other phis.
10233       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10234         Value *OpVal = PN.getIncomingValue(InValNo);
10235         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10236           break;
10237       }
10238       
10239       // If we scanned over all operands, then we have one unique value plus
10240       // phi values.  Scan PHI nodes to see if they all merge in each other or
10241       // the value.
10242       if (InValNo == NumOperandVals) {
10243         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10244         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10245           return ReplaceInstUsesWith(PN, NonPhiInVal);
10246       }
10247     }
10248   }
10249   return 0;
10250 }
10251
10252 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10253                                    Instruction *InsertPoint,
10254                                    InstCombiner *IC) {
10255   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10256   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10257   // We must cast correctly to the pointer type. Ensure that we
10258   // sign extend the integer value if it is smaller as this is
10259   // used for address computation.
10260   Instruction::CastOps opcode = 
10261      (VTySize < PtrSize ? Instruction::SExt :
10262       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10263   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10264 }
10265
10266
10267 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10268   Value *PtrOp = GEP.getOperand(0);
10269   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10270   // If so, eliminate the noop.
10271   if (GEP.getNumOperands() == 1)
10272     return ReplaceInstUsesWith(GEP, PtrOp);
10273
10274   if (isa<UndefValue>(GEP.getOperand(0)))
10275     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10276
10277   bool HasZeroPointerIndex = false;
10278   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10279     HasZeroPointerIndex = C->isNullValue();
10280
10281   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10282     return ReplaceInstUsesWith(GEP, PtrOp);
10283
10284   // Eliminate unneeded casts for indices.
10285   bool MadeChange = false;
10286   
10287   gep_type_iterator GTI = gep_type_begin(GEP);
10288   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10289        i != e; ++i, ++GTI) {
10290     if (isa<SequentialType>(*GTI)) {
10291       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10292         if (CI->getOpcode() == Instruction::ZExt ||
10293             CI->getOpcode() == Instruction::SExt) {
10294           const Type *SrcTy = CI->getOperand(0)->getType();
10295           // We can eliminate a cast from i32 to i64 iff the target 
10296           // is a 32-bit pointer target.
10297           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10298             MadeChange = true;
10299             *i = CI->getOperand(0);
10300           }
10301         }
10302       }
10303       // If we are using a wider index than needed for this platform, shrink it
10304       // to what we need.  If narrower, sign-extend it to what we need.
10305       // If the incoming value needs a cast instruction,
10306       // insert it.  This explicit cast can make subsequent optimizations more
10307       // obvious.
10308       Value *Op = *i;
10309       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10310         if (Constant *C = dyn_cast<Constant>(Op)) {
10311           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10312           MadeChange = true;
10313         } else {
10314           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10315                                 GEP);
10316           *i = Op;
10317           MadeChange = true;
10318         }
10319       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10320         if (Constant *C = dyn_cast<Constant>(Op)) {
10321           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10322           MadeChange = true;
10323         } else {
10324           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10325                                 GEP);
10326           *i = Op;
10327           MadeChange = true;
10328         }
10329       }
10330     }
10331   }
10332   if (MadeChange) return &GEP;
10333
10334   // If this GEP instruction doesn't move the pointer, and if the input operand
10335   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10336   // real input to the dest type.
10337   if (GEP.hasAllZeroIndices()) {
10338     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10339       // If the bitcast is of an allocation, and the allocation will be
10340       // converted to match the type of the cast, don't touch this.
10341       if (isa<AllocationInst>(BCI->getOperand(0))) {
10342         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10343         if (Instruction *I = visitBitCast(*BCI)) {
10344           if (I != BCI) {
10345             I->takeName(BCI);
10346             BCI->getParent()->getInstList().insert(BCI, I);
10347             ReplaceInstUsesWith(*BCI, I);
10348           }
10349           return &GEP;
10350         }
10351       }
10352       return new BitCastInst(BCI->getOperand(0), GEP.getType());
10353     }
10354   }
10355   
10356   // Combine Indices - If the source pointer to this getelementptr instruction
10357   // is a getelementptr instruction, combine the indices of the two
10358   // getelementptr instructions into a single instruction.
10359   //
10360   SmallVector<Value*, 8> SrcGEPOperands;
10361   if (User *Src = dyn_castGetElementPtr(PtrOp))
10362     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10363
10364   if (!SrcGEPOperands.empty()) {
10365     // Note that if our source is a gep chain itself that we wait for that
10366     // chain to be resolved before we perform this transformation.  This
10367     // avoids us creating a TON of code in some cases.
10368     //
10369     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10370         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10371       return 0;   // Wait until our source is folded to completion.
10372
10373     SmallVector<Value*, 8> Indices;
10374
10375     // Find out whether the last index in the source GEP is a sequential idx.
10376     bool EndsWithSequential = false;
10377     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10378            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10379       EndsWithSequential = !isa<StructType>(*I);
10380
10381     // Can we combine the two pointer arithmetics offsets?
10382     if (EndsWithSequential) {
10383       // Replace: gep (gep %P, long B), long A, ...
10384       // With:    T = long A+B; gep %P, T, ...
10385       //
10386       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10387       if (SO1 == Constant::getNullValue(SO1->getType())) {
10388         Sum = GO1;
10389       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10390         Sum = SO1;
10391       } else {
10392         // If they aren't the same type, convert both to an integer of the
10393         // target's pointer size.
10394         if (SO1->getType() != GO1->getType()) {
10395           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10396             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10397           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10398             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10399           } else {
10400             unsigned PS = TD->getPointerSizeInBits();
10401             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10402               // Convert GO1 to SO1's type.
10403               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10404
10405             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10406               // Convert SO1 to GO1's type.
10407               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10408             } else {
10409               const Type *PT = TD->getIntPtrType();
10410               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10411               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10412             }
10413           }
10414         }
10415         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10416           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10417         else {
10418           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10419           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10420         }
10421       }
10422
10423       // Recycle the GEP we already have if possible.
10424       if (SrcGEPOperands.size() == 2) {
10425         GEP.setOperand(0, SrcGEPOperands[0]);
10426         GEP.setOperand(1, Sum);
10427         return &GEP;
10428       } else {
10429         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10430                        SrcGEPOperands.end()-1);
10431         Indices.push_back(Sum);
10432         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10433       }
10434     } else if (isa<Constant>(*GEP.idx_begin()) &&
10435                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10436                SrcGEPOperands.size() != 1) {
10437       // Otherwise we can do the fold if the first index of the GEP is a zero
10438       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10439                      SrcGEPOperands.end());
10440       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10441     }
10442
10443     if (!Indices.empty())
10444       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10445                                        Indices.end(), GEP.getName());
10446
10447   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10448     // GEP of global variable.  If all of the indices for this GEP are
10449     // constants, we can promote this to a constexpr instead of an instruction.
10450
10451     // Scan for nonconstants...
10452     SmallVector<Constant*, 8> Indices;
10453     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10454     for (; I != E && isa<Constant>(*I); ++I)
10455       Indices.push_back(cast<Constant>(*I));
10456
10457     if (I == E) {  // If they are all constants...
10458       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10459                                                     &Indices[0],Indices.size());
10460
10461       // Replace all uses of the GEP with the new constexpr...
10462       return ReplaceInstUsesWith(GEP, CE);
10463     }
10464   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10465     if (!isa<PointerType>(X->getType())) {
10466       // Not interesting.  Source pointer must be a cast from pointer.
10467     } else if (HasZeroPointerIndex) {
10468       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10469       // into     : GEP [10 x i8]* X, i32 0, ...
10470       //
10471       // This occurs when the program declares an array extern like "int X[];"
10472       //
10473       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10474       const PointerType *XTy = cast<PointerType>(X->getType());
10475       if (const ArrayType *XATy =
10476           dyn_cast<ArrayType>(XTy->getElementType()))
10477         if (const ArrayType *CATy =
10478             dyn_cast<ArrayType>(CPTy->getElementType()))
10479           if (CATy->getElementType() == XATy->getElementType()) {
10480             // At this point, we know that the cast source type is a pointer
10481             // to an array of the same type as the destination pointer
10482             // array.  Because the array type is never stepped over (there
10483             // is a leading zero) we can fold the cast into this GEP.
10484             GEP.setOperand(0, X);
10485             return &GEP;
10486           }
10487     } else if (GEP.getNumOperands() == 2) {
10488       // Transform things like:
10489       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10490       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10491       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10492       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10493       if (isa<ArrayType>(SrcElTy) &&
10494           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10495           TD->getABITypeSize(ResElTy)) {
10496         Value *Idx[2];
10497         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10498         Idx[1] = GEP.getOperand(1);
10499         Value *V = InsertNewInstBefore(
10500                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10501         // V and GEP are both pointer types --> BitCast
10502         return new BitCastInst(V, GEP.getType());
10503       }
10504       
10505       // Transform things like:
10506       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10507       //   (where tmp = 8*tmp2) into:
10508       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10509       
10510       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10511         uint64_t ArrayEltSize =
10512             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10513         
10514         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10515         // allow either a mul, shift, or constant here.
10516         Value *NewIdx = 0;
10517         ConstantInt *Scale = 0;
10518         if (ArrayEltSize == 1) {
10519           NewIdx = GEP.getOperand(1);
10520           Scale = ConstantInt::get(NewIdx->getType(), 1);
10521         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10522           NewIdx = ConstantInt::get(CI->getType(), 1);
10523           Scale = CI;
10524         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10525           if (Inst->getOpcode() == Instruction::Shl &&
10526               isa<ConstantInt>(Inst->getOperand(1))) {
10527             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10528             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10529             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10530             NewIdx = Inst->getOperand(0);
10531           } else if (Inst->getOpcode() == Instruction::Mul &&
10532                      isa<ConstantInt>(Inst->getOperand(1))) {
10533             Scale = cast<ConstantInt>(Inst->getOperand(1));
10534             NewIdx = Inst->getOperand(0);
10535           }
10536         }
10537         
10538         // If the index will be to exactly the right offset with the scale taken
10539         // out, perform the transformation. Note, we don't know whether Scale is
10540         // signed or not. We'll use unsigned version of division/modulo
10541         // operation after making sure Scale doesn't have the sign bit set.
10542         if (Scale && Scale->getSExtValue() >= 0LL &&
10543             Scale->getZExtValue() % ArrayEltSize == 0) {
10544           Scale = ConstantInt::get(Scale->getType(),
10545                                    Scale->getZExtValue() / ArrayEltSize);
10546           if (Scale->getZExtValue() != 1) {
10547             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10548                                                        false /*ZExt*/);
10549             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10550             NewIdx = InsertNewInstBefore(Sc, GEP);
10551           }
10552
10553           // Insert the new GEP instruction.
10554           Value *Idx[2];
10555           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10556           Idx[1] = NewIdx;
10557           Instruction *NewGEP =
10558             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10559           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10560           // The NewGEP must be pointer typed, so must the old one -> BitCast
10561           return new BitCastInst(NewGEP, GEP.getType());
10562         }
10563       }
10564     }
10565   }
10566
10567   return 0;
10568 }
10569
10570 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10571   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10572   if (AI.isArrayAllocation()) {  // Check C != 1
10573     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10574       const Type *NewTy = 
10575         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10576       AllocationInst *New = 0;
10577
10578       // Create and insert the replacement instruction...
10579       if (isa<MallocInst>(AI))
10580         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10581       else {
10582         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10583         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10584       }
10585
10586       InsertNewInstBefore(New, AI);
10587
10588       // Scan to the end of the allocation instructions, to skip over a block of
10589       // allocas if possible...
10590       //
10591       BasicBlock::iterator It = New;
10592       while (isa<AllocationInst>(*It)) ++It;
10593
10594       // Now that I is pointing to the first non-allocation-inst in the block,
10595       // insert our getelementptr instruction...
10596       //
10597       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10598       Value *Idx[2];
10599       Idx[0] = NullIdx;
10600       Idx[1] = NullIdx;
10601       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10602                                            New->getName()+".sub", It);
10603
10604       // Now make everything use the getelementptr instead of the original
10605       // allocation.
10606       return ReplaceInstUsesWith(AI, V);
10607     } else if (isa<UndefValue>(AI.getArraySize())) {
10608       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10609     }
10610   }
10611
10612   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10613   // Note that we only do this for alloca's, because malloc should allocate and
10614   // return a unique pointer, even for a zero byte allocation.
10615   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10616       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10617     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10618
10619   return 0;
10620 }
10621
10622 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10623   Value *Op = FI.getOperand(0);
10624
10625   // free undef -> unreachable.
10626   if (isa<UndefValue>(Op)) {
10627     // Insert a new store to null because we cannot modify the CFG here.
10628     new StoreInst(ConstantInt::getTrue(),
10629                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10630     return EraseInstFromFunction(FI);
10631   }
10632   
10633   // If we have 'free null' delete the instruction.  This can happen in stl code
10634   // when lots of inlining happens.
10635   if (isa<ConstantPointerNull>(Op))
10636     return EraseInstFromFunction(FI);
10637   
10638   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10639   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10640     FI.setOperand(0, CI->getOperand(0));
10641     return &FI;
10642   }
10643   
10644   // Change free (gep X, 0,0,0,0) into free(X)
10645   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10646     if (GEPI->hasAllZeroIndices()) {
10647       AddToWorkList(GEPI);
10648       FI.setOperand(0, GEPI->getOperand(0));
10649       return &FI;
10650     }
10651   }
10652   
10653   // Change free(malloc) into nothing, if the malloc has a single use.
10654   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10655     if (MI->hasOneUse()) {
10656       EraseInstFromFunction(FI);
10657       return EraseInstFromFunction(*MI);
10658     }
10659
10660   return 0;
10661 }
10662
10663
10664 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10665 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10666                                         const TargetData *TD) {
10667   User *CI = cast<User>(LI.getOperand(0));
10668   Value *CastOp = CI->getOperand(0);
10669
10670   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10671     // Instead of loading constant c string, use corresponding integer value
10672     // directly if string length is small enough.
10673     std::string Str;
10674     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10675       unsigned len = Str.length();
10676       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10677       unsigned numBits = Ty->getPrimitiveSizeInBits();
10678       // Replace LI with immediate integer store.
10679       if ((numBits >> 3) == len + 1) {
10680         APInt StrVal(numBits, 0);
10681         APInt SingleChar(numBits, 0);
10682         if (TD->isLittleEndian()) {
10683           for (signed i = len-1; i >= 0; i--) {
10684             SingleChar = (uint64_t) Str[i];
10685             StrVal = (StrVal << 8) | SingleChar;
10686           }
10687         } else {
10688           for (unsigned i = 0; i < len; i++) {
10689             SingleChar = (uint64_t) Str[i];
10690             StrVal = (StrVal << 8) | SingleChar;
10691           }
10692           // Append NULL at the end.
10693           SingleChar = 0;
10694           StrVal = (StrVal << 8) | SingleChar;
10695         }
10696         Value *NL = ConstantInt::get(StrVal);
10697         return IC.ReplaceInstUsesWith(LI, NL);
10698       }
10699     }
10700   }
10701
10702   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10703   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10704     const Type *SrcPTy = SrcTy->getElementType();
10705
10706     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10707          isa<VectorType>(DestPTy)) {
10708       // If the source is an array, the code below will not succeed.  Check to
10709       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10710       // constants.
10711       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10712         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10713           if (ASrcTy->getNumElements() != 0) {
10714             Value *Idxs[2];
10715             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10716             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10717             SrcTy = cast<PointerType>(CastOp->getType());
10718             SrcPTy = SrcTy->getElementType();
10719           }
10720
10721       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10722             isa<VectorType>(SrcPTy)) &&
10723           // Do not allow turning this into a load of an integer, which is then
10724           // casted to a pointer, this pessimizes pointer analysis a lot.
10725           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10726           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10727                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10728
10729         // Okay, we are casting from one integer or pointer type to another of
10730         // the same size.  Instead of casting the pointer before the load, cast
10731         // the result of the loaded value.
10732         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10733                                                              CI->getName(),
10734                                                          LI.isVolatile()),LI);
10735         // Now cast the result of the load.
10736         return new BitCastInst(NewLoad, LI.getType());
10737       }
10738     }
10739   }
10740   return 0;
10741 }
10742
10743 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10744 /// from this value cannot trap.  If it is not obviously safe to load from the
10745 /// specified pointer, we do a quick local scan of the basic block containing
10746 /// ScanFrom, to determine if the address is already accessed.
10747 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10748   // If it is an alloca it is always safe to load from.
10749   if (isa<AllocaInst>(V)) return true;
10750
10751   // If it is a global variable it is mostly safe to load from.
10752   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10753     // Don't try to evaluate aliases.  External weak GV can be null.
10754     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10755
10756   // Otherwise, be a little bit agressive by scanning the local block where we
10757   // want to check to see if the pointer is already being loaded or stored
10758   // from/to.  If so, the previous load or store would have already trapped,
10759   // so there is no harm doing an extra load (also, CSE will later eliminate
10760   // the load entirely).
10761   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10762
10763   while (BBI != E) {
10764     --BBI;
10765
10766     // If we see a free or a call (which might do a free) the pointer could be
10767     // marked invalid.
10768     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10769       return false;
10770     
10771     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10772       if (LI->getOperand(0) == V) return true;
10773     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10774       if (SI->getOperand(1) == V) return true;
10775     }
10776
10777   }
10778   return false;
10779 }
10780
10781 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10782   Value *Op = LI.getOperand(0);
10783
10784   // Attempt to improve the alignment.
10785   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10786   if (KnownAlign >
10787       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10788                                 LI.getAlignment()))
10789     LI.setAlignment(KnownAlign);
10790
10791   // load (cast X) --> cast (load X) iff safe
10792   if (isa<CastInst>(Op))
10793     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10794       return Res;
10795
10796   // None of the following transforms are legal for volatile loads.
10797   if (LI.isVolatile()) return 0;
10798   
10799   // Do really simple store-to-load forwarding and load CSE, to catch cases
10800   // where there are several consequtive memory accesses to the same location,
10801   // separated by a few arithmetic operations.
10802   BasicBlock::iterator BBI = &LI;
10803   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
10804     return ReplaceInstUsesWith(LI, AvailableVal);
10805
10806   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10807     const Value *GEPI0 = GEPI->getOperand(0);
10808     // TODO: Consider a target hook for valid address spaces for this xform.
10809     if (isa<ConstantPointerNull>(GEPI0) &&
10810         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10811       // Insert a new store to null instruction before the load to indicate
10812       // that this code is not reachable.  We do this instead of inserting
10813       // an unreachable instruction directly because we cannot modify the
10814       // CFG.
10815       new StoreInst(UndefValue::get(LI.getType()),
10816                     Constant::getNullValue(Op->getType()), &LI);
10817       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10818     }
10819   } 
10820
10821   if (Constant *C = dyn_cast<Constant>(Op)) {
10822     // load null/undef -> undef
10823     // TODO: Consider a target hook for valid address spaces for this xform.
10824     if (isa<UndefValue>(C) || (C->isNullValue() && 
10825         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10826       // Insert a new store to null instruction before the load to indicate that
10827       // this code is not reachable.  We do this instead of inserting an
10828       // unreachable instruction directly because we cannot modify the CFG.
10829       new StoreInst(UndefValue::get(LI.getType()),
10830                     Constant::getNullValue(Op->getType()), &LI);
10831       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10832     }
10833
10834     // Instcombine load (constant global) into the value loaded.
10835     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10836       if (GV->isConstant() && !GV->isDeclaration())
10837         return ReplaceInstUsesWith(LI, GV->getInitializer());
10838
10839     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10840     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10841       if (CE->getOpcode() == Instruction::GetElementPtr) {
10842         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10843           if (GV->isConstant() && !GV->isDeclaration())
10844             if (Constant *V = 
10845                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10846               return ReplaceInstUsesWith(LI, V);
10847         if (CE->getOperand(0)->isNullValue()) {
10848           // Insert a new store to null instruction before the load to indicate
10849           // that this code is not reachable.  We do this instead of inserting
10850           // an unreachable instruction directly because we cannot modify the
10851           // CFG.
10852           new StoreInst(UndefValue::get(LI.getType()),
10853                         Constant::getNullValue(Op->getType()), &LI);
10854           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10855         }
10856
10857       } else if (CE->isCast()) {
10858         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10859           return Res;
10860       }
10861     }
10862   }
10863     
10864   // If this load comes from anywhere in a constant global, and if the global
10865   // is all undef or zero, we know what it loads.
10866   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
10867     if (GV->isConstant() && GV->hasInitializer()) {
10868       if (GV->getInitializer()->isNullValue())
10869         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10870       else if (isa<UndefValue>(GV->getInitializer()))
10871         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10872     }
10873   }
10874
10875   if (Op->hasOneUse()) {
10876     // Change select and PHI nodes to select values instead of addresses: this
10877     // helps alias analysis out a lot, allows many others simplifications, and
10878     // exposes redundancy in the code.
10879     //
10880     // Note that we cannot do the transformation unless we know that the
10881     // introduced loads cannot trap!  Something like this is valid as long as
10882     // the condition is always false: load (select bool %C, int* null, int* %G),
10883     // but it would not be valid if we transformed it to load from null
10884     // unconditionally.
10885     //
10886     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10887       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10888       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10889           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10890         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10891                                      SI->getOperand(1)->getName()+".val"), LI);
10892         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10893                                      SI->getOperand(2)->getName()+".val"), LI);
10894         return SelectInst::Create(SI->getCondition(), V1, V2);
10895       }
10896
10897       // load (select (cond, null, P)) -> load P
10898       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10899         if (C->isNullValue()) {
10900           LI.setOperand(0, SI->getOperand(2));
10901           return &LI;
10902         }
10903
10904       // load (select (cond, P, null)) -> load P
10905       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10906         if (C->isNullValue()) {
10907           LI.setOperand(0, SI->getOperand(1));
10908           return &LI;
10909         }
10910     }
10911   }
10912   return 0;
10913 }
10914
10915 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10916 /// when possible.
10917 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10918   User *CI = cast<User>(SI.getOperand(1));
10919   Value *CastOp = CI->getOperand(0);
10920
10921   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10922   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10923     const Type *SrcPTy = SrcTy->getElementType();
10924
10925     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10926       // If the source is an array, the code below will not succeed.  Check to
10927       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10928       // constants.
10929       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10930         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10931           if (ASrcTy->getNumElements() != 0) {
10932             Value* Idxs[2];
10933             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10934             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10935             SrcTy = cast<PointerType>(CastOp->getType());
10936             SrcPTy = SrcTy->getElementType();
10937           }
10938
10939       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10940           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10941                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10942
10943         // Okay, we are casting from one integer or pointer type to another of
10944         // the same size.  Instead of casting the pointer before 
10945         // the store, cast the value to be stored.
10946         Value *NewCast;
10947         Value *SIOp0 = SI.getOperand(0);
10948         Instruction::CastOps opcode = Instruction::BitCast;
10949         const Type* CastSrcTy = SIOp0->getType();
10950         const Type* CastDstTy = SrcPTy;
10951         if (isa<PointerType>(CastDstTy)) {
10952           if (CastSrcTy->isInteger())
10953             opcode = Instruction::IntToPtr;
10954         } else if (isa<IntegerType>(CastDstTy)) {
10955           if (isa<PointerType>(SIOp0->getType()))
10956             opcode = Instruction::PtrToInt;
10957         }
10958         if (Constant *C = dyn_cast<Constant>(SIOp0))
10959           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10960         else
10961           NewCast = IC.InsertNewInstBefore(
10962             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10963             SI);
10964         return new StoreInst(NewCast, CastOp);
10965       }
10966     }
10967   }
10968   return 0;
10969 }
10970
10971 /// equivalentAddressValues - Test if A and B will obviously have the same
10972 /// value. This includes recognizing that %t0 and %t1 will have the same
10973 /// value in code like this:
10974 ///   %t0 = getelementptr @a, 0, 3
10975 ///   store i32 0, i32* %t0
10976 ///   %t1 = getelementptr @a, 0, 3
10977 ///   %t2 = load i32* %t1
10978 ///
10979 static bool equivalentAddressValues(Value *A, Value *B) {
10980   // Test if the values are trivially equivalent.
10981   if (A == B) return true;
10982   
10983   // Test if the values come form identical arithmetic instructions.
10984   if (isa<BinaryOperator>(A) ||
10985       isa<CastInst>(A) ||
10986       isa<PHINode>(A) ||
10987       isa<GetElementPtrInst>(A))
10988     if (Instruction *BI = dyn_cast<Instruction>(B))
10989       if (cast<Instruction>(A)->isIdenticalTo(BI))
10990         return true;
10991   
10992   // Otherwise they may not be equivalent.
10993   return false;
10994 }
10995
10996 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10997   Value *Val = SI.getOperand(0);
10998   Value *Ptr = SI.getOperand(1);
10999
11000   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11001     EraseInstFromFunction(SI);
11002     ++NumCombined;
11003     return 0;
11004   }
11005   
11006   // If the RHS is an alloca with a single use, zapify the store, making the
11007   // alloca dead.
11008   if (Ptr->hasOneUse() && !SI.isVolatile()) {
11009     if (isa<AllocaInst>(Ptr)) {
11010       EraseInstFromFunction(SI);
11011       ++NumCombined;
11012       return 0;
11013     }
11014     
11015     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11016       if (isa<AllocaInst>(GEP->getOperand(0)) &&
11017           GEP->getOperand(0)->hasOneUse()) {
11018         EraseInstFromFunction(SI);
11019         ++NumCombined;
11020         return 0;
11021       }
11022   }
11023
11024   // Attempt to improve the alignment.
11025   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11026   if (KnownAlign >
11027       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11028                                 SI.getAlignment()))
11029     SI.setAlignment(KnownAlign);
11030
11031   // Do really simple DSE, to catch cases where there are several consequtive
11032   // stores to the same location, separated by a few arithmetic operations. This
11033   // situation often occurs with bitfield accesses.
11034   BasicBlock::iterator BBI = &SI;
11035   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11036        --ScanInsts) {
11037     --BBI;
11038     
11039     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11040       // Prev store isn't volatile, and stores to the same location?
11041       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11042                                                           SI.getOperand(1))) {
11043         ++NumDeadStore;
11044         ++BBI;
11045         EraseInstFromFunction(*PrevSI);
11046         continue;
11047       }
11048       break;
11049     }
11050     
11051     // If this is a load, we have to stop.  However, if the loaded value is from
11052     // the pointer we're loading and is producing the pointer we're storing,
11053     // then *this* store is dead (X = load P; store X -> P).
11054     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11055       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11056           !SI.isVolatile()) {
11057         EraseInstFromFunction(SI);
11058         ++NumCombined;
11059         return 0;
11060       }
11061       // Otherwise, this is a load from some other location.  Stores before it
11062       // may not be dead.
11063       break;
11064     }
11065     
11066     // Don't skip over loads or things that can modify memory.
11067     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11068       break;
11069   }
11070   
11071   
11072   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11073
11074   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11075   if (isa<ConstantPointerNull>(Ptr)) {
11076     if (!isa<UndefValue>(Val)) {
11077       SI.setOperand(0, UndefValue::get(Val->getType()));
11078       if (Instruction *U = dyn_cast<Instruction>(Val))
11079         AddToWorkList(U);  // Dropped a use.
11080       ++NumCombined;
11081     }
11082     return 0;  // Do not modify these!
11083   }
11084
11085   // store undef, Ptr -> noop
11086   if (isa<UndefValue>(Val)) {
11087     EraseInstFromFunction(SI);
11088     ++NumCombined;
11089     return 0;
11090   }
11091
11092   // If the pointer destination is a cast, see if we can fold the cast into the
11093   // source instead.
11094   if (isa<CastInst>(Ptr))
11095     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11096       return Res;
11097   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11098     if (CE->isCast())
11099       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11100         return Res;
11101
11102   
11103   // If this store is the last instruction in the basic block, and if the block
11104   // ends with an unconditional branch, try to move it to the successor block.
11105   BBI = &SI; ++BBI;
11106   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11107     if (BI->isUnconditional())
11108       if (SimplifyStoreAtEndOfBlock(SI))
11109         return 0;  // xform done!
11110   
11111   return 0;
11112 }
11113
11114 /// SimplifyStoreAtEndOfBlock - Turn things like:
11115 ///   if () { *P = v1; } else { *P = v2 }
11116 /// into a phi node with a store in the successor.
11117 ///
11118 /// Simplify things like:
11119 ///   *P = v1; if () { *P = v2; }
11120 /// into a phi node with a store in the successor.
11121 ///
11122 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11123   BasicBlock *StoreBB = SI.getParent();
11124   
11125   // Check to see if the successor block has exactly two incoming edges.  If
11126   // so, see if the other predecessor contains a store to the same location.
11127   // if so, insert a PHI node (if needed) and move the stores down.
11128   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11129   
11130   // Determine whether Dest has exactly two predecessors and, if so, compute
11131   // the other predecessor.
11132   pred_iterator PI = pred_begin(DestBB);
11133   BasicBlock *OtherBB = 0;
11134   if (*PI != StoreBB)
11135     OtherBB = *PI;
11136   ++PI;
11137   if (PI == pred_end(DestBB))
11138     return false;
11139   
11140   if (*PI != StoreBB) {
11141     if (OtherBB)
11142       return false;
11143     OtherBB = *PI;
11144   }
11145   if (++PI != pred_end(DestBB))
11146     return false;
11147
11148   // Bail out if all the relevant blocks aren't distinct (this can happen,
11149   // for example, if SI is in an infinite loop)
11150   if (StoreBB == DestBB || OtherBB == DestBB)
11151     return false;
11152
11153   // Verify that the other block ends in a branch and is not otherwise empty.
11154   BasicBlock::iterator BBI = OtherBB->getTerminator();
11155   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11156   if (!OtherBr || BBI == OtherBB->begin())
11157     return false;
11158   
11159   // If the other block ends in an unconditional branch, check for the 'if then
11160   // else' case.  there is an instruction before the branch.
11161   StoreInst *OtherStore = 0;
11162   if (OtherBr->isUnconditional()) {
11163     // If this isn't a store, or isn't a store to the same location, bail out.
11164     --BBI;
11165     OtherStore = dyn_cast<StoreInst>(BBI);
11166     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11167       return false;
11168   } else {
11169     // Otherwise, the other block ended with a conditional branch. If one of the
11170     // destinations is StoreBB, then we have the if/then case.
11171     if (OtherBr->getSuccessor(0) != StoreBB && 
11172         OtherBr->getSuccessor(1) != StoreBB)
11173       return false;
11174     
11175     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11176     // if/then triangle.  See if there is a store to the same ptr as SI that
11177     // lives in OtherBB.
11178     for (;; --BBI) {
11179       // Check to see if we find the matching store.
11180       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11181         if (OtherStore->getOperand(1) != SI.getOperand(1))
11182           return false;
11183         break;
11184       }
11185       // If we find something that may be using or overwriting the stored
11186       // value, or if we run out of instructions, we can't do the xform.
11187       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11188           BBI == OtherBB->begin())
11189         return false;
11190     }
11191     
11192     // In order to eliminate the store in OtherBr, we have to
11193     // make sure nothing reads or overwrites the stored value in
11194     // StoreBB.
11195     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11196       // FIXME: This should really be AA driven.
11197       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11198         return false;
11199     }
11200   }
11201   
11202   // Insert a PHI node now if we need it.
11203   Value *MergedVal = OtherStore->getOperand(0);
11204   if (MergedVal != SI.getOperand(0)) {
11205     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11206     PN->reserveOperandSpace(2);
11207     PN->addIncoming(SI.getOperand(0), SI.getParent());
11208     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11209     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11210   }
11211   
11212   // Advance to a place where it is safe to insert the new store and
11213   // insert it.
11214   BBI = DestBB->getFirstNonPHI();
11215   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11216                                     OtherStore->isVolatile()), *BBI);
11217   
11218   // Nuke the old stores.
11219   EraseInstFromFunction(SI);
11220   EraseInstFromFunction(*OtherStore);
11221   ++NumCombined;
11222   return true;
11223 }
11224
11225
11226 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11227   // Change br (not X), label True, label False to: br X, label False, True
11228   Value *X = 0;
11229   BasicBlock *TrueDest;
11230   BasicBlock *FalseDest;
11231   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11232       !isa<Constant>(X)) {
11233     // Swap Destinations and condition...
11234     BI.setCondition(X);
11235     BI.setSuccessor(0, FalseDest);
11236     BI.setSuccessor(1, TrueDest);
11237     return &BI;
11238   }
11239
11240   // Cannonicalize fcmp_one -> fcmp_oeq
11241   FCmpInst::Predicate FPred; Value *Y;
11242   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11243                              TrueDest, FalseDest)))
11244     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11245          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11246       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11247       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11248       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11249       NewSCC->takeName(I);
11250       // Swap Destinations and condition...
11251       BI.setCondition(NewSCC);
11252       BI.setSuccessor(0, FalseDest);
11253       BI.setSuccessor(1, TrueDest);
11254       RemoveFromWorkList(I);
11255       I->eraseFromParent();
11256       AddToWorkList(NewSCC);
11257       return &BI;
11258     }
11259
11260   // Cannonicalize icmp_ne -> icmp_eq
11261   ICmpInst::Predicate IPred;
11262   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11263                       TrueDest, FalseDest)))
11264     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11265          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11266          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11267       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11268       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11269       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11270       NewSCC->takeName(I);
11271       // Swap Destinations and condition...
11272       BI.setCondition(NewSCC);
11273       BI.setSuccessor(0, FalseDest);
11274       BI.setSuccessor(1, TrueDest);
11275       RemoveFromWorkList(I);
11276       I->eraseFromParent();;
11277       AddToWorkList(NewSCC);
11278       return &BI;
11279     }
11280
11281   return 0;
11282 }
11283
11284 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11285   Value *Cond = SI.getCondition();
11286   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11287     if (I->getOpcode() == Instruction::Add)
11288       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11289         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11290         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11291           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11292                                                 AddRHS));
11293         SI.setOperand(0, I->getOperand(0));
11294         AddToWorkList(I);
11295         return &SI;
11296       }
11297   }
11298   return 0;
11299 }
11300
11301 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11302   Value *Agg = EV.getAggregateOperand();
11303
11304   if (!EV.hasIndices())
11305     return ReplaceInstUsesWith(EV, Agg);
11306
11307   if (Constant *C = dyn_cast<Constant>(Agg)) {
11308     if (isa<UndefValue>(C))
11309       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11310       
11311     if (isa<ConstantAggregateZero>(C))
11312       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11313
11314     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11315       // Extract the element indexed by the first index out of the constant
11316       Value *V = C->getOperand(*EV.idx_begin());
11317       if (EV.getNumIndices() > 1)
11318         // Extract the remaining indices out of the constant indexed by the
11319         // first index
11320         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11321       else
11322         return ReplaceInstUsesWith(EV, V);
11323     }
11324     return 0; // Can't handle other constants
11325   } 
11326   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11327     // We're extracting from an insertvalue instruction, compare the indices
11328     const unsigned *exti, *exte, *insi, *inse;
11329     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11330          exte = EV.idx_end(), inse = IV->idx_end();
11331          exti != exte && insi != inse;
11332          ++exti, ++insi) {
11333       if (*insi != *exti)
11334         // The insert and extract both reference distinctly different elements.
11335         // This means the extract is not influenced by the insert, and we can
11336         // replace the aggregate operand of the extract with the aggregate
11337         // operand of the insert. i.e., replace
11338         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11339         // %E = extractvalue { i32, { i32 } } %I, 0
11340         // with
11341         // %E = extractvalue { i32, { i32 } } %A, 0
11342         return ExtractValueInst::Create(IV->getAggregateOperand(),
11343                                         EV.idx_begin(), EV.idx_end());
11344     }
11345     if (exti == exte && insi == inse)
11346       // Both iterators are at the end: Index lists are identical. Replace
11347       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11348       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11349       // with "i32 42"
11350       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11351     if (exti == exte) {
11352       // The extract list is a prefix of the insert list. i.e. replace
11353       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11354       // %E = extractvalue { i32, { i32 } } %I, 1
11355       // with
11356       // %X = extractvalue { i32, { i32 } } %A, 1
11357       // %E = insertvalue { i32 } %X, i32 42, 0
11358       // by switching the order of the insert and extract (though the
11359       // insertvalue should be left in, since it may have other uses).
11360       Value *NewEV = InsertNewInstBefore(
11361         ExtractValueInst::Create(IV->getAggregateOperand(),
11362                                  EV.idx_begin(), EV.idx_end()),
11363         EV);
11364       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11365                                      insi, inse);
11366     }
11367     if (insi == inse)
11368       // The insert list is a prefix of the extract list
11369       // We can simply remove the common indices from the extract and make it
11370       // operate on the inserted value instead of the insertvalue result.
11371       // i.e., replace
11372       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11373       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11374       // with
11375       // %E extractvalue { i32 } { i32 42 }, 0
11376       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11377                                       exti, exte);
11378   }
11379   // Can't simplify extracts from other values. Note that nested extracts are
11380   // already simplified implicitely by the above (extract ( extract (insert) )
11381   // will be translated into extract ( insert ( extract ) ) first and then just
11382   // the value inserted, if appropriate).
11383   return 0;
11384 }
11385
11386 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11387 /// is to leave as a vector operation.
11388 static bool CheapToScalarize(Value *V, bool isConstant) {
11389   if (isa<ConstantAggregateZero>(V)) 
11390     return true;
11391   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11392     if (isConstant) return true;
11393     // If all elts are the same, we can extract.
11394     Constant *Op0 = C->getOperand(0);
11395     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11396       if (C->getOperand(i) != Op0)
11397         return false;
11398     return true;
11399   }
11400   Instruction *I = dyn_cast<Instruction>(V);
11401   if (!I) return false;
11402   
11403   // Insert element gets simplified to the inserted element or is deleted if
11404   // this is constant idx extract element and its a constant idx insertelt.
11405   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11406       isa<ConstantInt>(I->getOperand(2)))
11407     return true;
11408   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11409     return true;
11410   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11411     if (BO->hasOneUse() &&
11412         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11413          CheapToScalarize(BO->getOperand(1), isConstant)))
11414       return true;
11415   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11416     if (CI->hasOneUse() &&
11417         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11418          CheapToScalarize(CI->getOperand(1), isConstant)))
11419       return true;
11420   
11421   return false;
11422 }
11423
11424 /// Read and decode a shufflevector mask.
11425 ///
11426 /// It turns undef elements into values that are larger than the number of
11427 /// elements in the input.
11428 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11429   unsigned NElts = SVI->getType()->getNumElements();
11430   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11431     return std::vector<unsigned>(NElts, 0);
11432   if (isa<UndefValue>(SVI->getOperand(2)))
11433     return std::vector<unsigned>(NElts, 2*NElts);
11434
11435   std::vector<unsigned> Result;
11436   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11437   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11438     if (isa<UndefValue>(*i))
11439       Result.push_back(NElts*2);  // undef -> 8
11440     else
11441       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11442   return Result;
11443 }
11444
11445 /// FindScalarElement - Given a vector and an element number, see if the scalar
11446 /// value is already around as a register, for example if it were inserted then
11447 /// extracted from the vector.
11448 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11449   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11450   const VectorType *PTy = cast<VectorType>(V->getType());
11451   unsigned Width = PTy->getNumElements();
11452   if (EltNo >= Width)  // Out of range access.
11453     return UndefValue::get(PTy->getElementType());
11454   
11455   if (isa<UndefValue>(V))
11456     return UndefValue::get(PTy->getElementType());
11457   else if (isa<ConstantAggregateZero>(V))
11458     return Constant::getNullValue(PTy->getElementType());
11459   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11460     return CP->getOperand(EltNo);
11461   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11462     // If this is an insert to a variable element, we don't know what it is.
11463     if (!isa<ConstantInt>(III->getOperand(2))) 
11464       return 0;
11465     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11466     
11467     // If this is an insert to the element we are looking for, return the
11468     // inserted value.
11469     if (EltNo == IIElt) 
11470       return III->getOperand(1);
11471     
11472     // Otherwise, the insertelement doesn't modify the value, recurse on its
11473     // vector input.
11474     return FindScalarElement(III->getOperand(0), EltNo);
11475   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11476     unsigned LHSWidth =
11477       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11478     unsigned InEl = getShuffleMask(SVI)[EltNo];
11479     if (InEl < LHSWidth)
11480       return FindScalarElement(SVI->getOperand(0), InEl);
11481     else if (InEl < LHSWidth*2)
11482       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11483     else
11484       return UndefValue::get(PTy->getElementType());
11485   }
11486   
11487   // Otherwise, we don't know.
11488   return 0;
11489 }
11490
11491 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11492   // If vector val is undef, replace extract with scalar undef.
11493   if (isa<UndefValue>(EI.getOperand(0)))
11494     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11495
11496   // If vector val is constant 0, replace extract with scalar 0.
11497   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11498     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11499   
11500   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11501     // If vector val is constant with all elements the same, replace EI with
11502     // that element. When the elements are not identical, we cannot replace yet
11503     // (we do that below, but only when the index is constant).
11504     Constant *op0 = C->getOperand(0);
11505     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11506       if (C->getOperand(i) != op0) {
11507         op0 = 0; 
11508         break;
11509       }
11510     if (op0)
11511       return ReplaceInstUsesWith(EI, op0);
11512   }
11513   
11514   // If extracting a specified index from the vector, see if we can recursively
11515   // find a previously computed scalar that was inserted into the vector.
11516   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11517     unsigned IndexVal = IdxC->getZExtValue();
11518     unsigned VectorWidth = 
11519       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11520       
11521     // If this is extracting an invalid index, turn this into undef, to avoid
11522     // crashing the code below.
11523     if (IndexVal >= VectorWidth)
11524       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11525     
11526     // This instruction only demands the single element from the input vector.
11527     // If the input vector has a single use, simplify it based on this use
11528     // property.
11529     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11530       uint64_t UndefElts;
11531       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11532                                                 1 << IndexVal,
11533                                                 UndefElts)) {
11534         EI.setOperand(0, V);
11535         return &EI;
11536       }
11537     }
11538     
11539     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11540       return ReplaceInstUsesWith(EI, Elt);
11541     
11542     // If the this extractelement is directly using a bitcast from a vector of
11543     // the same number of elements, see if we can find the source element from
11544     // it.  In this case, we will end up needing to bitcast the scalars.
11545     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11546       if (const VectorType *VT = 
11547               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11548         if (VT->getNumElements() == VectorWidth)
11549           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11550             return new BitCastInst(Elt, EI.getType());
11551     }
11552   }
11553   
11554   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11555     if (I->hasOneUse()) {
11556       // Push extractelement into predecessor operation if legal and
11557       // profitable to do so
11558       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11559         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11560         if (CheapToScalarize(BO, isConstantElt)) {
11561           ExtractElementInst *newEI0 = 
11562             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11563                                    EI.getName()+".lhs");
11564           ExtractElementInst *newEI1 =
11565             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11566                                    EI.getName()+".rhs");
11567           InsertNewInstBefore(newEI0, EI);
11568           InsertNewInstBefore(newEI1, EI);
11569           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11570         }
11571       } else if (isa<LoadInst>(I)) {
11572         unsigned AS = 
11573           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11574         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11575                                          PointerType::get(EI.getType(), AS),EI);
11576         GetElementPtrInst *GEP =
11577           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11578         InsertNewInstBefore(GEP, EI);
11579         return new LoadInst(GEP);
11580       }
11581     }
11582     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11583       // Extracting the inserted element?
11584       if (IE->getOperand(2) == EI.getOperand(1))
11585         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11586       // If the inserted and extracted elements are constants, they must not
11587       // be the same value, extract from the pre-inserted value instead.
11588       if (isa<Constant>(IE->getOperand(2)) &&
11589           isa<Constant>(EI.getOperand(1))) {
11590         AddUsesToWorkList(EI);
11591         EI.setOperand(0, IE->getOperand(0));
11592         return &EI;
11593       }
11594     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11595       // If this is extracting an element from a shufflevector, figure out where
11596       // it came from and extract from the appropriate input element instead.
11597       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11598         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11599         Value *Src;
11600         unsigned LHSWidth =
11601           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11602
11603         if (SrcIdx < LHSWidth)
11604           Src = SVI->getOperand(0);
11605         else if (SrcIdx < LHSWidth*2) {
11606           SrcIdx -= LHSWidth;
11607           Src = SVI->getOperand(1);
11608         } else {
11609           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11610         }
11611         return new ExtractElementInst(Src, SrcIdx);
11612       }
11613     }
11614   }
11615   return 0;
11616 }
11617
11618 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11619 /// elements from either LHS or RHS, return the shuffle mask and true. 
11620 /// Otherwise, return false.
11621 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11622                                          std::vector<Constant*> &Mask) {
11623   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11624          "Invalid CollectSingleShuffleElements");
11625   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11626
11627   if (isa<UndefValue>(V)) {
11628     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11629     return true;
11630   } else if (V == LHS) {
11631     for (unsigned i = 0; i != NumElts; ++i)
11632       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11633     return true;
11634   } else if (V == RHS) {
11635     for (unsigned i = 0; i != NumElts; ++i)
11636       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11637     return true;
11638   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11639     // If this is an insert of an extract from some other vector, include it.
11640     Value *VecOp    = IEI->getOperand(0);
11641     Value *ScalarOp = IEI->getOperand(1);
11642     Value *IdxOp    = IEI->getOperand(2);
11643     
11644     if (!isa<ConstantInt>(IdxOp))
11645       return false;
11646     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11647     
11648     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11649       // Okay, we can handle this if the vector we are insertinting into is
11650       // transitively ok.
11651       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11652         // If so, update the mask to reflect the inserted undef.
11653         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11654         return true;
11655       }      
11656     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11657       if (isa<ConstantInt>(EI->getOperand(1)) &&
11658           EI->getOperand(0)->getType() == V->getType()) {
11659         unsigned ExtractedIdx =
11660           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11661         
11662         // This must be extracting from either LHS or RHS.
11663         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11664           // Okay, we can handle this if the vector we are insertinting into is
11665           // transitively ok.
11666           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11667             // If so, update the mask to reflect the inserted value.
11668             if (EI->getOperand(0) == LHS) {
11669               Mask[InsertedIdx % NumElts] = 
11670                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11671             } else {
11672               assert(EI->getOperand(0) == RHS);
11673               Mask[InsertedIdx % NumElts] = 
11674                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11675               
11676             }
11677             return true;
11678           }
11679         }
11680       }
11681     }
11682   }
11683   // TODO: Handle shufflevector here!
11684   
11685   return false;
11686 }
11687
11688 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11689 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11690 /// that computes V and the LHS value of the shuffle.
11691 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11692                                      Value *&RHS) {
11693   assert(isa<VectorType>(V->getType()) && 
11694          (RHS == 0 || V->getType() == RHS->getType()) &&
11695          "Invalid shuffle!");
11696   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11697
11698   if (isa<UndefValue>(V)) {
11699     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11700     return V;
11701   } else if (isa<ConstantAggregateZero>(V)) {
11702     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11703     return V;
11704   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11705     // If this is an insert of an extract from some other vector, include it.
11706     Value *VecOp    = IEI->getOperand(0);
11707     Value *ScalarOp = IEI->getOperand(1);
11708     Value *IdxOp    = IEI->getOperand(2);
11709     
11710     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11711       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11712           EI->getOperand(0)->getType() == V->getType()) {
11713         unsigned ExtractedIdx =
11714           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11715         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11716         
11717         // Either the extracted from or inserted into vector must be RHSVec,
11718         // otherwise we'd end up with a shuffle of three inputs.
11719         if (EI->getOperand(0) == RHS || RHS == 0) {
11720           RHS = EI->getOperand(0);
11721           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11722           Mask[InsertedIdx % NumElts] = 
11723             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11724           return V;
11725         }
11726         
11727         if (VecOp == RHS) {
11728           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11729           // Everything but the extracted element is replaced with the RHS.
11730           for (unsigned i = 0; i != NumElts; ++i) {
11731             if (i != InsertedIdx)
11732               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11733           }
11734           return V;
11735         }
11736         
11737         // If this insertelement is a chain that comes from exactly these two
11738         // vectors, return the vector and the effective shuffle.
11739         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11740           return EI->getOperand(0);
11741         
11742       }
11743     }
11744   }
11745   // TODO: Handle shufflevector here!
11746   
11747   // Otherwise, can't do anything fancy.  Return an identity vector.
11748   for (unsigned i = 0; i != NumElts; ++i)
11749     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11750   return V;
11751 }
11752
11753 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11754   Value *VecOp    = IE.getOperand(0);
11755   Value *ScalarOp = IE.getOperand(1);
11756   Value *IdxOp    = IE.getOperand(2);
11757   
11758   // Inserting an undef or into an undefined place, remove this.
11759   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11760     ReplaceInstUsesWith(IE, VecOp);
11761   
11762   // If the inserted element was extracted from some other vector, and if the 
11763   // indexes are constant, try to turn this into a shufflevector operation.
11764   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11765     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11766         EI->getOperand(0)->getType() == IE.getType()) {
11767       unsigned NumVectorElts = IE.getType()->getNumElements();
11768       unsigned ExtractedIdx =
11769         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11770       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11771       
11772       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11773         return ReplaceInstUsesWith(IE, VecOp);
11774       
11775       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11776         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11777       
11778       // If we are extracting a value from a vector, then inserting it right
11779       // back into the same place, just use the input vector.
11780       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11781         return ReplaceInstUsesWith(IE, VecOp);      
11782       
11783       // We could theoretically do this for ANY input.  However, doing so could
11784       // turn chains of insertelement instructions into a chain of shufflevector
11785       // instructions, and right now we do not merge shufflevectors.  As such,
11786       // only do this in a situation where it is clear that there is benefit.
11787       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11788         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11789         // the values of VecOp, except then one read from EIOp0.
11790         // Build a new shuffle mask.
11791         std::vector<Constant*> Mask;
11792         if (isa<UndefValue>(VecOp))
11793           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11794         else {
11795           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11796           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11797                                                        NumVectorElts));
11798         } 
11799         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11800         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11801                                      ConstantVector::get(Mask));
11802       }
11803       
11804       // If this insertelement isn't used by some other insertelement, turn it
11805       // (and any insertelements it points to), into one big shuffle.
11806       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11807         std::vector<Constant*> Mask;
11808         Value *RHS = 0;
11809         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11810         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11811         // We now have a shuffle of LHS, RHS, Mask.
11812         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11813       }
11814     }
11815   }
11816
11817   return 0;
11818 }
11819
11820
11821 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11822   Value *LHS = SVI.getOperand(0);
11823   Value *RHS = SVI.getOperand(1);
11824   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11825
11826   bool MadeChange = false;
11827
11828   // Undefined shuffle mask -> undefined value.
11829   if (isa<UndefValue>(SVI.getOperand(2)))
11830     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11831
11832   uint64_t UndefElts;
11833   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
11834
11835   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
11836     return 0;
11837
11838   uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
11839   if (VWidth <= 64 &&
11840       SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11841     LHS = SVI.getOperand(0);
11842     RHS = SVI.getOperand(1);
11843     MadeChange = true;
11844   }
11845   
11846   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11847   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11848   if (LHS == RHS || isa<UndefValue>(LHS)) {
11849     if (isa<UndefValue>(LHS) && LHS == RHS) {
11850       // shuffle(undef,undef,mask) -> undef.
11851       return ReplaceInstUsesWith(SVI, LHS);
11852     }
11853     
11854     // Remap any references to RHS to use LHS.
11855     std::vector<Constant*> Elts;
11856     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11857       if (Mask[i] >= 2*e)
11858         Elts.push_back(UndefValue::get(Type::Int32Ty));
11859       else {
11860         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11861             (Mask[i] <  e && isa<UndefValue>(LHS))) {
11862           Mask[i] = 2*e;     // Turn into undef.
11863           Elts.push_back(UndefValue::get(Type::Int32Ty));
11864         } else {
11865           Mask[i] = Mask[i] % e;  // Force to LHS.
11866           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11867         }
11868       }
11869     }
11870     SVI.setOperand(0, SVI.getOperand(1));
11871     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11872     SVI.setOperand(2, ConstantVector::get(Elts));
11873     LHS = SVI.getOperand(0);
11874     RHS = SVI.getOperand(1);
11875     MadeChange = true;
11876   }
11877   
11878   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11879   bool isLHSID = true, isRHSID = true;
11880     
11881   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11882     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11883     // Is this an identity shuffle of the LHS value?
11884     isLHSID &= (Mask[i] == i);
11885       
11886     // Is this an identity shuffle of the RHS value?
11887     isRHSID &= (Mask[i]-e == i);
11888   }
11889
11890   // Eliminate identity shuffles.
11891   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11892   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11893   
11894   // If the LHS is a shufflevector itself, see if we can combine it with this
11895   // one without producing an unusual shuffle.  Here we are really conservative:
11896   // we are absolutely afraid of producing a shuffle mask not in the input
11897   // program, because the code gen may not be smart enough to turn a merged
11898   // shuffle into two specific shuffles: it may produce worse code.  As such,
11899   // we only merge two shuffles if the result is one of the two input shuffle
11900   // masks.  In this case, merging the shuffles just removes one instruction,
11901   // which we know is safe.  This is good for things like turning:
11902   // (splat(splat)) -> splat.
11903   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11904     if (isa<UndefValue>(RHS)) {
11905       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11906
11907       std::vector<unsigned> NewMask;
11908       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11909         if (Mask[i] >= 2*e)
11910           NewMask.push_back(2*e);
11911         else
11912           NewMask.push_back(LHSMask[Mask[i]]);
11913       
11914       // If the result mask is equal to the src shuffle or this shuffle mask, do
11915       // the replacement.
11916       if (NewMask == LHSMask || NewMask == Mask) {
11917         std::vector<Constant*> Elts;
11918         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11919           if (NewMask[i] >= e*2) {
11920             Elts.push_back(UndefValue::get(Type::Int32Ty));
11921           } else {
11922             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11923           }
11924         }
11925         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11926                                      LHSSVI->getOperand(1),
11927                                      ConstantVector::get(Elts));
11928       }
11929     }
11930   }
11931
11932   return MadeChange ? &SVI : 0;
11933 }
11934
11935
11936
11937
11938 /// TryToSinkInstruction - Try to move the specified instruction from its
11939 /// current block into the beginning of DestBlock, which can only happen if it's
11940 /// safe to move the instruction past all of the instructions between it and the
11941 /// end of its block.
11942 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11943   assert(I->hasOneUse() && "Invariants didn't hold!");
11944
11945   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11946   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11947     return false;
11948
11949   // Do not sink alloca instructions out of the entry block.
11950   if (isa<AllocaInst>(I) && I->getParent() ==
11951         &DestBlock->getParent()->getEntryBlock())
11952     return false;
11953
11954   // We can only sink load instructions if there is nothing between the load and
11955   // the end of block that could change the value.
11956   if (I->mayReadFromMemory()) {
11957     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11958          Scan != E; ++Scan)
11959       if (Scan->mayWriteToMemory())
11960         return false;
11961   }
11962
11963   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11964
11965   I->moveBefore(InsertPos);
11966   ++NumSunkInst;
11967   return true;
11968 }
11969
11970
11971 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11972 /// all reachable code to the worklist.
11973 ///
11974 /// This has a couple of tricks to make the code faster and more powerful.  In
11975 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11976 /// them to the worklist (this significantly speeds up instcombine on code where
11977 /// many instructions are dead or constant).  Additionally, if we find a branch
11978 /// whose condition is a known constant, we only visit the reachable successors.
11979 ///
11980 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11981                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11982                                        InstCombiner &IC,
11983                                        const TargetData *TD) {
11984   SmallVector<BasicBlock*, 256> Worklist;
11985   Worklist.push_back(BB);
11986
11987   while (!Worklist.empty()) {
11988     BB = Worklist.back();
11989     Worklist.pop_back();
11990     
11991     // We have now visited this block!  If we've already been here, ignore it.
11992     if (!Visited.insert(BB)) continue;
11993
11994     DbgInfoIntrinsic *DBI_Prev = NULL;
11995     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11996       Instruction *Inst = BBI++;
11997       
11998       // DCE instruction if trivially dead.
11999       if (isInstructionTriviallyDead(Inst)) {
12000         ++NumDeadInst;
12001         DOUT << "IC: DCE: " << *Inst;
12002         Inst->eraseFromParent();
12003         continue;
12004       }
12005       
12006       // ConstantProp instruction if trivially constant.
12007       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12008         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12009         Inst->replaceAllUsesWith(C);
12010         ++NumConstProp;
12011         Inst->eraseFromParent();
12012         continue;
12013       }
12014      
12015       // If there are two consecutive llvm.dbg.stoppoint calls then
12016       // it is likely that the optimizer deleted code in between these
12017       // two intrinsics. 
12018       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12019       if (DBI_Next) {
12020         if (DBI_Prev
12021             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12022             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12023           IC.RemoveFromWorkList(DBI_Prev);
12024           DBI_Prev->eraseFromParent();
12025         }
12026         DBI_Prev = DBI_Next;
12027       }
12028
12029       IC.AddToWorkList(Inst);
12030     }
12031
12032     // Recursively visit successors.  If this is a branch or switch on a
12033     // constant, only visit the reachable successor.
12034     TerminatorInst *TI = BB->getTerminator();
12035     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12036       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12037         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12038         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12039         Worklist.push_back(ReachableBB);
12040         continue;
12041       }
12042     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12043       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12044         // See if this is an explicit destination.
12045         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12046           if (SI->getCaseValue(i) == Cond) {
12047             BasicBlock *ReachableBB = SI->getSuccessor(i);
12048             Worklist.push_back(ReachableBB);
12049             continue;
12050           }
12051         
12052         // Otherwise it is the default destination.
12053         Worklist.push_back(SI->getSuccessor(0));
12054         continue;
12055       }
12056     }
12057     
12058     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12059       Worklist.push_back(TI->getSuccessor(i));
12060   }
12061 }
12062
12063 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12064   bool Changed = false;
12065   TD = &getAnalysis<TargetData>();
12066   
12067   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12068              << F.getNameStr() << "\n");
12069
12070   {
12071     // Do a depth-first traversal of the function, populate the worklist with
12072     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12073     // track of which blocks we visit.
12074     SmallPtrSet<BasicBlock*, 64> Visited;
12075     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12076
12077     // Do a quick scan over the function.  If we find any blocks that are
12078     // unreachable, remove any instructions inside of them.  This prevents
12079     // the instcombine code from having to deal with some bad special cases.
12080     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12081       if (!Visited.count(BB)) {
12082         Instruction *Term = BB->getTerminator();
12083         while (Term != BB->begin()) {   // Remove instrs bottom-up
12084           BasicBlock::iterator I = Term; --I;
12085
12086           DOUT << "IC: DCE: " << *I;
12087           ++NumDeadInst;
12088
12089           if (!I->use_empty())
12090             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12091           I->eraseFromParent();
12092         }
12093       }
12094   }
12095
12096   while (!Worklist.empty()) {
12097     Instruction *I = RemoveOneFromWorkList();
12098     if (I == 0) continue;  // skip null values.
12099
12100     // Check to see if we can DCE the instruction.
12101     if (isInstructionTriviallyDead(I)) {
12102       // Add operands to the worklist.
12103       if (I->getNumOperands() < 4)
12104         AddUsesToWorkList(*I);
12105       ++NumDeadInst;
12106
12107       DOUT << "IC: DCE: " << *I;
12108
12109       I->eraseFromParent();
12110       RemoveFromWorkList(I);
12111       continue;
12112     }
12113
12114     // Instruction isn't dead, see if we can constant propagate it.
12115     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12116       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12117
12118       // Add operands to the worklist.
12119       AddUsesToWorkList(*I);
12120       ReplaceInstUsesWith(*I, C);
12121
12122       ++NumConstProp;
12123       I->eraseFromParent();
12124       RemoveFromWorkList(I);
12125       continue;
12126     }
12127
12128     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12129       // See if we can constant fold its operands.
12130       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12131         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12132           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12133             i->set(NewC);
12134         }
12135       }
12136     }
12137
12138     // See if we can trivially sink this instruction to a successor basic block.
12139     if (I->hasOneUse()) {
12140       BasicBlock *BB = I->getParent();
12141       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12142       if (UserParent != BB) {
12143         bool UserIsSuccessor = false;
12144         // See if the user is one of our successors.
12145         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12146           if (*SI == UserParent) {
12147             UserIsSuccessor = true;
12148             break;
12149           }
12150
12151         // If the user is one of our immediate successors, and if that successor
12152         // only has us as a predecessors (we'd have to split the critical edge
12153         // otherwise), we can keep going.
12154         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12155             next(pred_begin(UserParent)) == pred_end(UserParent))
12156           // Okay, the CFG is simple enough, try to sink this instruction.
12157           Changed |= TryToSinkInstruction(I, UserParent);
12158       }
12159     }
12160
12161     // Now that we have an instruction, try combining it to simplify it...
12162 #ifndef NDEBUG
12163     std::string OrigI;
12164 #endif
12165     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12166     if (Instruction *Result = visit(*I)) {
12167       ++NumCombined;
12168       // Should we replace the old instruction with a new one?
12169       if (Result != I) {
12170         DOUT << "IC: Old = " << *I
12171              << "    New = " << *Result;
12172
12173         // Everything uses the new instruction now.
12174         I->replaceAllUsesWith(Result);
12175
12176         // Push the new instruction and any users onto the worklist.
12177         AddToWorkList(Result);
12178         AddUsersToWorkList(*Result);
12179
12180         // Move the name to the new instruction first.
12181         Result->takeName(I);
12182
12183         // Insert the new instruction into the basic block...
12184         BasicBlock *InstParent = I->getParent();
12185         BasicBlock::iterator InsertPos = I;
12186
12187         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12188           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12189             ++InsertPos;
12190
12191         InstParent->getInstList().insert(InsertPos, Result);
12192
12193         // Make sure that we reprocess all operands now that we reduced their
12194         // use counts.
12195         AddUsesToWorkList(*I);
12196
12197         // Instructions can end up on the worklist more than once.  Make sure
12198         // we do not process an instruction that has been deleted.
12199         RemoveFromWorkList(I);
12200
12201         // Erase the old instruction.
12202         InstParent->getInstList().erase(I);
12203       } else {
12204 #ifndef NDEBUG
12205         DOUT << "IC: Mod = " << OrigI
12206              << "    New = " << *I;
12207 #endif
12208
12209         // If the instruction was modified, it's possible that it is now dead.
12210         // if so, remove it.
12211         if (isInstructionTriviallyDead(I)) {
12212           // Make sure we process all operands now that we are reducing their
12213           // use counts.
12214           AddUsesToWorkList(*I);
12215
12216           // Instructions may end up in the worklist more than once.  Erase all
12217           // occurrences of this instruction.
12218           RemoveFromWorkList(I);
12219           I->eraseFromParent();
12220         } else {
12221           AddToWorkList(I);
12222           AddUsersToWorkList(*I);
12223         }
12224       }
12225       Changed = true;
12226     }
12227   }
12228
12229   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12230     
12231   // Do an explicit clear, this shrinks the map if needed.
12232   WorklistMap.clear();
12233   return Changed;
12234 }
12235
12236
12237 bool InstCombiner::runOnFunction(Function &F) {
12238   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12239   
12240   bool EverMadeChange = false;
12241
12242   // Iterate while there is work to do.
12243   unsigned Iteration = 0;
12244   while (DoOneIteration(F, Iteration++))
12245     EverMadeChange = true;
12246   return EverMadeChange;
12247 }
12248
12249 FunctionPass *llvm::createInstructionCombiningPass() {
12250   return new InstCombiner();
12251 }
12252
12253