I found a better place for this optz'n.
[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((intptr_t)&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).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 *visitAnd(BinaryOperator &I);
184     Instruction *visitOr (BinaryOperator &I);
185     Instruction *visitXor(BinaryOperator &I);
186     Instruction *visitShl(BinaryOperator &I);
187     Instruction *visitAShr(BinaryOperator &I);
188     Instruction *visitLShr(BinaryOperator &I);
189     Instruction *commonShiftTransforms(BinaryOperator &I);
190     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
191                                       Constant *RHSC);
192     Instruction *visitFCmpInst(FCmpInst &I);
193     Instruction *visitICmpInst(ICmpInst &I);
194     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
195     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
196                                                 Instruction *LHS,
197                                                 ConstantInt *RHS);
198     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
199                                 ConstantInt *DivRHS);
200
201     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
202                              ICmpInst::Predicate Cond, Instruction &I);
203     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
204                                      BinaryOperator &I);
205     Instruction *commonCastTransforms(CastInst &CI);
206     Instruction *commonIntCastTransforms(CastInst &CI);
207     Instruction *commonPointerCastTransforms(CastInst &CI);
208     Instruction *visitTrunc(TruncInst &CI);
209     Instruction *visitZExt(ZExtInst &CI);
210     Instruction *visitSExt(SExtInst &CI);
211     Instruction *visitFPTrunc(FPTruncInst &CI);
212     Instruction *visitFPExt(CastInst &CI);
213     Instruction *visitFPToUI(FPToUIInst &FI);
214     Instruction *visitFPToSI(FPToSIInst &FI);
215     Instruction *visitUIToFP(CastInst &CI);
216     Instruction *visitSIToFP(CastInst &CI);
217     Instruction *visitPtrToInt(CastInst &CI);
218     Instruction *visitIntToPtr(IntToPtrInst &CI);
219     Instruction *visitBitCast(BitCastInst &CI);
220     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
221                                 Instruction *FI);
222     Instruction *visitSelectInst(SelectInst &CI);
223     Instruction *visitCallInst(CallInst &CI);
224     Instruction *visitInvokeInst(InvokeInst &II);
225     Instruction *visitPHINode(PHINode &PN);
226     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
227     Instruction *visitAllocationInst(AllocationInst &AI);
228     Instruction *visitFreeInst(FreeInst &FI);
229     Instruction *visitLoadInst(LoadInst &LI);
230     Instruction *visitStoreInst(StoreInst &SI);
231     Instruction *visitBranchInst(BranchInst &BI);
232     Instruction *visitSwitchInst(SwitchInst &SI);
233     Instruction *visitInsertElementInst(InsertElementInst &IE);
234     Instruction *visitExtractElementInst(ExtractElementInst &EI);
235     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
236     Instruction *visitExtractValueInst(ExtractValueInst &EV);
237
238     // visitInstruction - Specify what to return for unhandled instructions...
239     Instruction *visitInstruction(Instruction &I) { return 0; }
240
241   private:
242     Instruction *visitCallSite(CallSite CS);
243     bool transformConstExprCastCall(CallSite CS);
244     Instruction *transformCallThroughTrampoline(CallSite CS);
245     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
246                                    bool DoXform = true);
247     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
248
249   public:
250     // InsertNewInstBefore - insert an instruction New before instruction Old
251     // in the program.  Add the new instruction to the worklist.
252     //
253     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
254       assert(New && New->getParent() == 0 &&
255              "New instruction already inserted into a basic block!");
256       BasicBlock *BB = Old.getParent();
257       BB->getInstList().insert(&Old, New);  // Insert inst
258       AddToWorkList(New);
259       return New;
260     }
261
262     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
263     /// This also adds the cast to the worklist.  Finally, this returns the
264     /// cast.
265     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
266                             Instruction &Pos) {
267       if (V->getType() == Ty) return V;
268
269       if (Constant *CV = dyn_cast<Constant>(V))
270         return ConstantExpr::getCast(opc, CV, Ty);
271       
272       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
273       AddToWorkList(C);
274       return C;
275     }
276         
277     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
278       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
279     }
280
281
282     // ReplaceInstUsesWith - This method is to be used when an instruction is
283     // found to be dead, replacable with another preexisting expression.  Here
284     // we add all uses of I to the worklist, replace all uses of I with the new
285     // value, then return I, so that the inst combiner will know that I was
286     // modified.
287     //
288     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
289       AddUsersToWorkList(I);         // Add all modified instrs to worklist
290       if (&I != V) {
291         I.replaceAllUsesWith(V);
292         return &I;
293       } else {
294         // If we are replacing the instruction with itself, this must be in a
295         // segment of unreachable code, so just clobber the instruction.
296         I.replaceAllUsesWith(UndefValue::get(I.getType()));
297         return &I;
298       }
299     }
300
301     // UpdateValueUsesWith - This method is to be used when an value is
302     // found to be replacable with another preexisting expression or was
303     // updated.  Here we add all uses of I to the worklist, replace all uses of
304     // I with the new value (unless the instruction was just updated), then
305     // return true, so that the inst combiner will know that I was modified.
306     //
307     bool UpdateValueUsesWith(Value *Old, Value *New) {
308       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
309       if (Old != New)
310         Old->replaceAllUsesWith(New);
311       if (Instruction *I = dyn_cast<Instruction>(Old))
312         AddToWorkList(I);
313       if (Instruction *I = dyn_cast<Instruction>(New))
314         AddToWorkList(I);
315       return true;
316     }
317     
318     // EraseInstFromFunction - When dealing with an instruction that has side
319     // effects or produces a void value, we can't rely on DCE to delete the
320     // instruction.  Instead, visit methods should return the value returned by
321     // this function.
322     Instruction *EraseInstFromFunction(Instruction &I) {
323       assert(I.use_empty() && "Cannot erase instruction that is used!");
324       AddUsesToWorkList(I);
325       RemoveFromWorkList(&I);
326       I.eraseFromParent();
327       return 0;  // Don't do anything with FI
328     }
329         
330     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
331                            APInt &KnownOne, unsigned Depth = 0) const {
332       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
333     }
334     
335     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
336                            unsigned Depth = 0) const {
337       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
338     }
339     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
340       return llvm::ComputeNumSignBits(Op, TD, Depth);
341     }
342
343   private:
344     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
345     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
346     /// casts that are known to not do anything...
347     ///
348     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
349                                    Value *V, const Type *DestTy,
350                                    Instruction *InsertBefore);
351
352     /// SimplifyCommutative - This performs a few simplifications for 
353     /// commutative operators.
354     bool SimplifyCommutative(BinaryOperator &I);
355
356     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
357     /// most-complex to least-complex order.
358     bool SimplifyCompare(CmpInst &I);
359
360     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
361     /// on the demanded bits.
362     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
363                               APInt& KnownZero, APInt& KnownOne,
364                               unsigned Depth = 0);
365
366     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
367                                       uint64_t &UndefElts, unsigned Depth = 0);
368       
369     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370     // PHI node as operand #0, see if we can fold the instruction into the PHI
371     // (which is only possible if all operands to the PHI are constants).
372     Instruction *FoldOpIntoPhi(Instruction &I);
373
374     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375     // operator and they all are only used by the PHI, PHI together their
376     // inputs, and do the operation once, to the result of the PHI.
377     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
378     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
379     
380     
381     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
383     
384     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
385                               bool isSub, Instruction &I);
386     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
387                                  bool isSigned, bool Inside, Instruction &IB);
388     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
389     Instruction *MatchBSwap(BinaryOperator &I);
390     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
391     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
392     Instruction *SimplifyMemSet(MemSetInst *MI);
393
394
395     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
396
397     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
398                                     unsigned CastOpc,
399                                     int &NumCastsRemoved);
400     unsigned GetOrEnforceKnownAlignment(Value *V,
401                                         unsigned PrefAlign = 0);
402
403   };
404 }
405
406 char InstCombiner::ID = 0;
407 static RegisterPass<InstCombiner>
408 X("instcombine", "Combine redundant instructions");
409
410 // getComplexity:  Assign a complexity or rank value to LLVM Values...
411 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
412 static unsigned getComplexity(Value *V) {
413   if (isa<Instruction>(V)) {
414     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
415       return 3;
416     return 4;
417   }
418   if (isa<Argument>(V)) return 3;
419   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
420 }
421
422 // isOnlyUse - Return true if this instruction will be deleted if we stop using
423 // it.
424 static bool isOnlyUse(Value *V) {
425   return V->hasOneUse() || isa<Constant>(V);
426 }
427
428 // getPromotedType - Return the specified type promoted as it would be to pass
429 // though a va_arg area...
430 static const Type *getPromotedType(const Type *Ty) {
431   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
432     if (ITy->getBitWidth() < 32)
433       return Type::Int32Ty;
434   }
435   return Ty;
436 }
437
438 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
439 /// expression bitcast,  return the operand value, otherwise return null.
440 static Value *getBitCastOperand(Value *V) {
441   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
442     return I->getOperand(0);
443   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
444     if (CE->getOpcode() == Instruction::BitCast)
445       return CE->getOperand(0);
446   return 0;
447 }
448
449 /// This function is a wrapper around CastInst::isEliminableCastPair. It
450 /// simply extracts arguments and returns what that function returns.
451 static Instruction::CastOps 
452 isEliminableCastPair(
453   const CastInst *CI, ///< The first cast instruction
454   unsigned opcode,       ///< The opcode of the second cast instruction
455   const Type *DstTy,     ///< The target type for the second cast instruction
456   TargetData *TD         ///< The target data for pointer size
457 ) {
458   
459   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
460   const Type *MidTy = CI->getType();                  // B from above
461
462   // Get the opcodes of the two Cast instructions
463   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
464   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
465
466   return Instruction::CastOps(
467       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
468                                      DstTy, TD->getIntPtrType()));
469 }
470
471 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
472 /// in any code being generated.  It does not require codegen if V is simple
473 /// enough or if the cast can be folded into other casts.
474 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
475                               const Type *Ty, TargetData *TD) {
476   if (V->getType() == Ty || isa<Constant>(V)) return false;
477   
478   // If this is another cast that can be eliminated, it isn't codegen either.
479   if (const CastInst *CI = dyn_cast<CastInst>(V))
480     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
481       return false;
482   return true;
483 }
484
485 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
486 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
487 /// casts that are known to not do anything...
488 ///
489 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
490                                              Value *V, const Type *DestTy,
491                                              Instruction *InsertBefore) {
492   if (V->getType() == DestTy) return V;
493   if (Constant *C = dyn_cast<Constant>(V))
494     return ConstantExpr::getCast(opcode, C, DestTy);
495   
496   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
497 }
498
499 // SimplifyCommutative - This performs a few simplifications for commutative
500 // operators:
501 //
502 //  1. Order operands such that they are listed from right (least complex) to
503 //     left (most complex).  This puts constants before unary operators before
504 //     binary operators.
505 //
506 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
507 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
508 //
509 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
510   bool Changed = false;
511   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
512     Changed = !I.swapOperands();
513
514   if (!I.isAssociative()) return Changed;
515   Instruction::BinaryOps Opcode = I.getOpcode();
516   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
517     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
518       if (isa<Constant>(I.getOperand(1))) {
519         Constant *Folded = ConstantExpr::get(I.getOpcode(),
520                                              cast<Constant>(I.getOperand(1)),
521                                              cast<Constant>(Op->getOperand(1)));
522         I.setOperand(0, Op->getOperand(0));
523         I.setOperand(1, Folded);
524         return true;
525       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
526         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
527             isOnlyUse(Op) && isOnlyUse(Op1)) {
528           Constant *C1 = cast<Constant>(Op->getOperand(1));
529           Constant *C2 = cast<Constant>(Op1->getOperand(1));
530
531           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
532           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
533           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
534                                                     Op1->getOperand(0),
535                                                     Op1->getName(), &I);
536           AddToWorkList(New);
537           I.setOperand(0, New);
538           I.setOperand(1, Folded);
539           return true;
540         }
541     }
542   return Changed;
543 }
544
545 /// SimplifyCompare - For a CmpInst this function just orders the operands
546 /// so that theyare listed from right (least complex) to left (most complex).
547 /// This puts constants before unary operators before binary operators.
548 bool InstCombiner::SimplifyCompare(CmpInst &I) {
549   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
550     return false;
551   I.swapOperands();
552   // Compare instructions are not associative so there's nothing else we can do.
553   return true;
554 }
555
556 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
557 // if the LHS is a constant zero (which is the 'negate' form).
558 //
559 static inline Value *dyn_castNegVal(Value *V) {
560   if (BinaryOperator::isNeg(V))
561     return BinaryOperator::getNegArgument(V);
562
563   // Constants can be considered to be negated values if they can be folded.
564   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
565     return ConstantExpr::getNeg(C);
566
567   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
568     if (C->getType()->getElementType()->isInteger())
569       return ConstantExpr::getNeg(C);
570
571   return 0;
572 }
573
574 static inline Value *dyn_castNotVal(Value *V) {
575   if (BinaryOperator::isNot(V))
576     return BinaryOperator::getNotArgument(V);
577
578   // Constants can be considered to be not'ed values...
579   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
580     return ConstantInt::get(~C->getValue());
581   return 0;
582 }
583
584 // dyn_castFoldableMul - If this value is a multiply that can be folded into
585 // other computations (because it has a constant operand), return the
586 // non-constant operand of the multiply, and set CST to point to the multiplier.
587 // Otherwise, return null.
588 //
589 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
590   if (V->hasOneUse() && V->getType()->isInteger())
591     if (Instruction *I = dyn_cast<Instruction>(V)) {
592       if (I->getOpcode() == Instruction::Mul)
593         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
594           return I->getOperand(0);
595       if (I->getOpcode() == Instruction::Shl)
596         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
597           // The multiplier is really 1 << CST.
598           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
599           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
600           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
601           return I->getOperand(0);
602         }
603     }
604   return 0;
605 }
606
607 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
608 /// expression, return it.
609 static User *dyn_castGetElementPtr(Value *V) {
610   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
611   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
612     if (CE->getOpcode() == Instruction::GetElementPtr)
613       return cast<User>(V);
614   return false;
615 }
616
617 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
618 /// opcode value. Otherwise return UserOp1.
619 static unsigned getOpcode(const Value *V) {
620   if (const Instruction *I = dyn_cast<Instruction>(V))
621     return I->getOpcode();
622   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
623     return CE->getOpcode();
624   // Use UserOp1 to mean there's no opcode.
625   return Instruction::UserOp1;
626 }
627
628 /// AddOne - Add one to a ConstantInt
629 static ConstantInt *AddOne(ConstantInt *C) {
630   APInt Val(C->getValue());
631   return ConstantInt::get(++Val);
632 }
633 /// SubOne - Subtract one from a ConstantInt
634 static ConstantInt *SubOne(ConstantInt *C) {
635   APInt Val(C->getValue());
636   return ConstantInt::get(--Val);
637 }
638 /// Add - Add two ConstantInts together
639 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
640   return ConstantInt::get(C1->getValue() + C2->getValue());
641 }
642 /// And - Bitwise AND two ConstantInts together
643 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
644   return ConstantInt::get(C1->getValue() & C2->getValue());
645 }
646 /// Subtract - Subtract one ConstantInt from another
647 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
648   return ConstantInt::get(C1->getValue() - C2->getValue());
649 }
650 /// Multiply - Multiply two ConstantInts together
651 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
652   return ConstantInt::get(C1->getValue() * C2->getValue());
653 }
654 /// MultiplyOverflows - True if the multiply can not be expressed in an int
655 /// this size.
656 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
657   uint32_t W = C1->getBitWidth();
658   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
659   if (sign) {
660     LHSExt.sext(W * 2);
661     RHSExt.sext(W * 2);
662   } else {
663     LHSExt.zext(W * 2);
664     RHSExt.zext(W * 2);
665   }
666
667   APInt MulExt = LHSExt * RHSExt;
668
669   if (sign) {
670     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
671     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
672     return MulExt.slt(Min) || MulExt.sgt(Max);
673   } else 
674     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
675 }
676
677
678 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
679 /// specified instruction is a constant integer.  If so, check to see if there
680 /// are any bits set in the constant that are not demanded.  If so, shrink the
681 /// constant and return true.
682 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
683                                    APInt Demanded) {
684   assert(I && "No instruction?");
685   assert(OpNo < I->getNumOperands() && "Operand index too large");
686
687   // If the operand is not a constant integer, nothing to do.
688   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
689   if (!OpC) return false;
690
691   // If there are no bits set that aren't demanded, nothing to do.
692   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
693   if ((~Demanded & OpC->getValue()) == 0)
694     return false;
695
696   // This instruction is producing bits that are not demanded. Shrink the RHS.
697   Demanded &= OpC->getValue();
698   I->setOperand(OpNo, ConstantInt::get(Demanded));
699   return true;
700 }
701
702 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
703 // set of known zero and one bits, compute the maximum and minimum values that
704 // could have the specified known zero and known one bits, returning them in
705 // min/max.
706 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
707                                                    const APInt& KnownZero,
708                                                    const APInt& KnownOne,
709                                                    APInt& Min, APInt& Max) {
710   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
711   assert(KnownZero.getBitWidth() == BitWidth && 
712          KnownOne.getBitWidth() == BitWidth &&
713          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
714          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
715   APInt UnknownBits = ~(KnownZero|KnownOne);
716
717   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
718   // bit if it is unknown.
719   Min = KnownOne;
720   Max = KnownOne|UnknownBits;
721   
722   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
723     Min.set(BitWidth-1);
724     Max.clear(BitWidth-1);
725   }
726 }
727
728 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
729 // a set of known zero and one bits, compute the maximum and minimum values that
730 // could have the specified known zero and known one bits, returning them in
731 // min/max.
732 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
733                                                      const APInt &KnownZero,
734                                                      const APInt &KnownOne,
735                                                      APInt &Min, APInt &Max) {
736   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
737   assert(KnownZero.getBitWidth() == BitWidth && 
738          KnownOne.getBitWidth() == BitWidth &&
739          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
740          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
741   APInt UnknownBits = ~(KnownZero|KnownOne);
742   
743   // The minimum value is when the unknown bits are all zeros.
744   Min = KnownOne;
745   // The maximum value is when the unknown bits are all ones.
746   Max = KnownOne|UnknownBits;
747 }
748
749 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
750 /// value based on the demanded bits. When this function is called, it is known
751 /// that only the bits set in DemandedMask of the result of V are ever used
752 /// downstream. Consequently, depending on the mask and V, it may be possible
753 /// to replace V with a constant or one of its operands. In such cases, this
754 /// function does the replacement and returns true. In all other cases, it
755 /// returns false after analyzing the expression and setting KnownOne and known
756 /// to be one in the expression. KnownZero contains all the bits that are known
757 /// to be zero in the expression. These are provided to potentially allow the
758 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
759 /// the expression. KnownOne and KnownZero always follow the invariant that 
760 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
761 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
762 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
763 /// and KnownOne must all be the same.
764 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
765                                         APInt& KnownZero, APInt& KnownOne,
766                                         unsigned Depth) {
767   assert(V != 0 && "Null pointer of Value???");
768   assert(Depth <= 6 && "Limit Search Depth");
769   uint32_t BitWidth = DemandedMask.getBitWidth();
770   const IntegerType *VTy = cast<IntegerType>(V->getType());
771   assert(VTy->getBitWidth() == BitWidth && 
772          KnownZero.getBitWidth() == BitWidth && 
773          KnownOne.getBitWidth() == BitWidth &&
774          "Value *V, DemandedMask, KnownZero and KnownOne \
775           must have same BitWidth");
776   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
777     // We know all of the bits for a constant!
778     KnownOne = CI->getValue() & DemandedMask;
779     KnownZero = ~KnownOne & DemandedMask;
780     return false;
781   }
782   
783   KnownZero.clear(); 
784   KnownOne.clear();
785   if (!V->hasOneUse()) {    // Other users may use these bits.
786     if (Depth != 0) {       // Not at the root.
787       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
788       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
789       return false;
790     }
791     // If this is the root being simplified, allow it to have multiple uses,
792     // just set the DemandedMask to all bits.
793     DemandedMask = APInt::getAllOnesValue(BitWidth);
794   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
795     if (V != UndefValue::get(VTy))
796       return UpdateValueUsesWith(V, UndefValue::get(VTy));
797     return false;
798   } else if (Depth == 6) {        // Limit search depth.
799     return false;
800   }
801   
802   Instruction *I = dyn_cast<Instruction>(V);
803   if (!I) return false;        // Only analyze instructions.
804
805   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
806   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
807   switch (I->getOpcode()) {
808   default:
809     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
810     break;
811   case Instruction::And:
812     // If either the LHS or the RHS are Zero, the result is zero.
813     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
814                              RHSKnownZero, RHSKnownOne, Depth+1))
815       return true;
816     assert((RHSKnownZero & RHSKnownOne) == 0 && 
817            "Bits known to be one AND zero?"); 
818
819     // If something is known zero on the RHS, the bits aren't demanded on the
820     // LHS.
821     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
822                              LHSKnownZero, LHSKnownOne, Depth+1))
823       return true;
824     assert((LHSKnownZero & LHSKnownOne) == 0 && 
825            "Bits known to be one AND zero?"); 
826
827     // If all of the demanded bits are known 1 on one side, return the other.
828     // These bits cannot contribute to the result of the 'and'.
829     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
830         (DemandedMask & ~LHSKnownZero))
831       return UpdateValueUsesWith(I, I->getOperand(0));
832     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
833         (DemandedMask & ~RHSKnownZero))
834       return UpdateValueUsesWith(I, I->getOperand(1));
835     
836     // If all of the demanded bits in the inputs are known zeros, return zero.
837     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
838       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
839       
840     // If the RHS is a constant, see if we can simplify it.
841     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
842       return UpdateValueUsesWith(I, I);
843       
844     // Output known-1 bits are only known if set in both the LHS & RHS.
845     RHSKnownOne &= LHSKnownOne;
846     // Output known-0 are known to be clear if zero in either the LHS | RHS.
847     RHSKnownZero |= LHSKnownZero;
848     break;
849   case Instruction::Or:
850     // If either the LHS or the RHS are One, the result is One.
851     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
852                              RHSKnownZero, RHSKnownOne, Depth+1))
853       return true;
854     assert((RHSKnownZero & RHSKnownOne) == 0 && 
855            "Bits known to be one AND zero?"); 
856     // If something is known one on the RHS, the bits aren't demanded on the
857     // LHS.
858     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
859                              LHSKnownZero, LHSKnownOne, Depth+1))
860       return true;
861     assert((LHSKnownZero & LHSKnownOne) == 0 && 
862            "Bits known to be one AND zero?"); 
863     
864     // If all of the demanded bits are known zero on one side, return the other.
865     // These bits cannot contribute to the result of the 'or'.
866     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
867         (DemandedMask & ~LHSKnownOne))
868       return UpdateValueUsesWith(I, I->getOperand(0));
869     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
870         (DemandedMask & ~RHSKnownOne))
871       return UpdateValueUsesWith(I, I->getOperand(1));
872
873     // If all of the potentially set bits on one side are known to be set on
874     // the other side, just use the 'other' side.
875     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
876         (DemandedMask & (~RHSKnownZero)))
877       return UpdateValueUsesWith(I, I->getOperand(0));
878     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
879         (DemandedMask & (~LHSKnownZero)))
880       return UpdateValueUsesWith(I, I->getOperand(1));
881         
882     // If the RHS is a constant, see if we can simplify it.
883     if (ShrinkDemandedConstant(I, 1, DemandedMask))
884       return UpdateValueUsesWith(I, I);
885           
886     // Output known-0 bits are only known if clear in both the LHS & RHS.
887     RHSKnownZero &= LHSKnownZero;
888     // Output known-1 are known to be set if set in either the LHS | RHS.
889     RHSKnownOne |= LHSKnownOne;
890     break;
891   case Instruction::Xor: {
892     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
893                              RHSKnownZero, RHSKnownOne, Depth+1))
894       return true;
895     assert((RHSKnownZero & RHSKnownOne) == 0 && 
896            "Bits known to be one AND zero?"); 
897     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
898                              LHSKnownZero, LHSKnownOne, Depth+1))
899       return true;
900     assert((LHSKnownZero & LHSKnownOne) == 0 && 
901            "Bits known to be one AND zero?"); 
902     
903     // If all of the demanded bits are known zero on one side, return the other.
904     // These bits cannot contribute to the result of the 'xor'.
905     if ((DemandedMask & RHSKnownZero) == DemandedMask)
906       return UpdateValueUsesWith(I, I->getOperand(0));
907     if ((DemandedMask & LHSKnownZero) == DemandedMask)
908       return UpdateValueUsesWith(I, I->getOperand(1));
909     
910     // Output known-0 bits are known if clear or set in both the LHS & RHS.
911     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
912                          (RHSKnownOne & LHSKnownOne);
913     // Output known-1 are known to be set if set in only one of the LHS, RHS.
914     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
915                         (RHSKnownOne & LHSKnownZero);
916     
917     // If all of the demanded bits are known to be zero on one side or the
918     // other, turn this into an *inclusive* or.
919     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
920     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
921       Instruction *Or =
922         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
923                                  I->getName());
924       InsertNewInstBefore(Or, *I);
925       return UpdateValueUsesWith(I, Or);
926     }
927     
928     // If all of the demanded bits on one side are known, and all of the set
929     // bits on that side are also known to be set on the other side, turn this
930     // into an AND, as we know the bits will be cleared.
931     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
932     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
933       // all known
934       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
935         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
936         Instruction *And = 
937           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
938         InsertNewInstBefore(And, *I);
939         return UpdateValueUsesWith(I, And);
940       }
941     }
942     
943     // If the RHS is a constant, see if we can simplify it.
944     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
945     if (ShrinkDemandedConstant(I, 1, DemandedMask))
946       return UpdateValueUsesWith(I, I);
947     
948     RHSKnownZero = KnownZeroOut;
949     RHSKnownOne  = KnownOneOut;
950     break;
951   }
952   case Instruction::Select:
953     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
954                              RHSKnownZero, RHSKnownOne, Depth+1))
955       return true;
956     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
957                              LHSKnownZero, LHSKnownOne, Depth+1))
958       return true;
959     assert((RHSKnownZero & RHSKnownOne) == 0 && 
960            "Bits known to be one AND zero?"); 
961     assert((LHSKnownZero & LHSKnownOne) == 0 && 
962            "Bits known to be one AND zero?"); 
963     
964     // If the operands are constants, see if we can simplify them.
965     if (ShrinkDemandedConstant(I, 1, DemandedMask))
966       return UpdateValueUsesWith(I, I);
967     if (ShrinkDemandedConstant(I, 2, DemandedMask))
968       return UpdateValueUsesWith(I, I);
969     
970     // Only known if known in both the LHS and RHS.
971     RHSKnownOne &= LHSKnownOne;
972     RHSKnownZero &= LHSKnownZero;
973     break;
974   case Instruction::Trunc: {
975     uint32_t truncBf = 
976       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
977     DemandedMask.zext(truncBf);
978     RHSKnownZero.zext(truncBf);
979     RHSKnownOne.zext(truncBf);
980     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
981                              RHSKnownZero, RHSKnownOne, Depth+1))
982       return true;
983     DemandedMask.trunc(BitWidth);
984     RHSKnownZero.trunc(BitWidth);
985     RHSKnownOne.trunc(BitWidth);
986     assert((RHSKnownZero & RHSKnownOne) == 0 && 
987            "Bits known to be one AND zero?"); 
988     break;
989   }
990   case Instruction::BitCast:
991     if (!I->getOperand(0)->getType()->isInteger())
992       return false;
993       
994     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
995                              RHSKnownZero, RHSKnownOne, Depth+1))
996       return true;
997     assert((RHSKnownZero & RHSKnownOne) == 0 && 
998            "Bits known to be one AND zero?"); 
999     break;
1000   case Instruction::ZExt: {
1001     // Compute the bits in the result that are not present in the input.
1002     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1003     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1004     
1005     DemandedMask.trunc(SrcBitWidth);
1006     RHSKnownZero.trunc(SrcBitWidth);
1007     RHSKnownOne.trunc(SrcBitWidth);
1008     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1009                              RHSKnownZero, RHSKnownOne, Depth+1))
1010       return true;
1011     DemandedMask.zext(BitWidth);
1012     RHSKnownZero.zext(BitWidth);
1013     RHSKnownOne.zext(BitWidth);
1014     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1015            "Bits known to be one AND zero?"); 
1016     // The top bits are known to be zero.
1017     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1018     break;
1019   }
1020   case Instruction::SExt: {
1021     // Compute the bits in the result that are not present in the input.
1022     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1023     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1024     
1025     APInt InputDemandedBits = DemandedMask & 
1026                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1027
1028     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1029     // If any of the sign extended bits are demanded, we know that the sign
1030     // bit is demanded.
1031     if ((NewBits & DemandedMask) != 0)
1032       InputDemandedBits.set(SrcBitWidth-1);
1033       
1034     InputDemandedBits.trunc(SrcBitWidth);
1035     RHSKnownZero.trunc(SrcBitWidth);
1036     RHSKnownOne.trunc(SrcBitWidth);
1037     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1038                              RHSKnownZero, RHSKnownOne, Depth+1))
1039       return true;
1040     InputDemandedBits.zext(BitWidth);
1041     RHSKnownZero.zext(BitWidth);
1042     RHSKnownOne.zext(BitWidth);
1043     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1044            "Bits known to be one AND zero?"); 
1045       
1046     // If the sign bit of the input is known set or clear, then we know the
1047     // top bits of the result.
1048
1049     // If the input sign bit is known zero, or if the NewBits are not demanded
1050     // convert this into a zero extension.
1051     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1052     {
1053       // Convert to ZExt cast
1054       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1055       return UpdateValueUsesWith(I, NewCast);
1056     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1057       RHSKnownOne |= NewBits;
1058     }
1059     break;
1060   }
1061   case Instruction::Add: {
1062     // Figure out what the input bits are.  If the top bits of the and result
1063     // are not demanded, then the add doesn't demand them from its input
1064     // either.
1065     uint32_t NLZ = DemandedMask.countLeadingZeros();
1066       
1067     // If there is a constant on the RHS, there are a variety of xformations
1068     // we can do.
1069     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070       // If null, this should be simplified elsewhere.  Some of the xforms here
1071       // won't work if the RHS is zero.
1072       if (RHS->isZero())
1073         break;
1074       
1075       // If the top bit of the output is demanded, demand everything from the
1076       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1077       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1078
1079       // Find information about known zero/one bits in the input.
1080       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1081                                LHSKnownZero, LHSKnownOne, Depth+1))
1082         return true;
1083
1084       // If the RHS of the add has bits set that can't affect the input, reduce
1085       // the constant.
1086       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1087         return UpdateValueUsesWith(I, I);
1088       
1089       // Avoid excess work.
1090       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1091         break;
1092       
1093       // Turn it into OR if input bits are zero.
1094       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1095         Instruction *Or =
1096           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1097                                    I->getName());
1098         InsertNewInstBefore(Or, *I);
1099         return UpdateValueUsesWith(I, Or);
1100       }
1101       
1102       // We can say something about the output known-zero and known-one bits,
1103       // depending on potential carries from the input constant and the
1104       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1105       // bits set and the RHS constant is 0x01001, then we know we have a known
1106       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1107       
1108       // To compute this, we first compute the potential carry bits.  These are
1109       // the bits which may be modified.  I'm not aware of a better way to do
1110       // this scan.
1111       const APInt& RHSVal = RHS->getValue();
1112       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1113       
1114       // Now that we know which bits have carries, compute the known-1/0 sets.
1115       
1116       // Bits are known one if they are known zero in one operand and one in the
1117       // other, and there is no input carry.
1118       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1119                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1120       
1121       // Bits are known zero if they are known zero in both operands and there
1122       // is no input carry.
1123       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1124     } else {
1125       // If the high-bits of this ADD are not demanded, then it does not demand
1126       // the high bits of its LHS or RHS.
1127       if (DemandedMask[BitWidth-1] == 0) {
1128         // Right fill the mask of bits for this ADD to demand the most
1129         // significant bit and all those below it.
1130         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1131         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1132                                  LHSKnownZero, LHSKnownOne, Depth+1))
1133           return true;
1134         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1135                                  LHSKnownZero, LHSKnownOne, Depth+1))
1136           return true;
1137       }
1138     }
1139     break;
1140   }
1141   case Instruction::Sub:
1142     // If the high-bits of this SUB are not demanded, then it does not demand
1143     // the high bits of its LHS or RHS.
1144     if (DemandedMask[BitWidth-1] == 0) {
1145       // Right fill the mask of bits for this SUB to demand the most
1146       // significant bit and all those below it.
1147       uint32_t NLZ = DemandedMask.countLeadingZeros();
1148       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1149       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1150                                LHSKnownZero, LHSKnownOne, Depth+1))
1151         return true;
1152       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1153                                LHSKnownZero, LHSKnownOne, Depth+1))
1154         return true;
1155     }
1156     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1157     // the known zeros and ones.
1158     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1159     break;
1160   case Instruction::Shl:
1161     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1162       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1163       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1164       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1165                                RHSKnownZero, RHSKnownOne, Depth+1))
1166         return true;
1167       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1168              "Bits known to be one AND zero?"); 
1169       RHSKnownZero <<= ShiftAmt;
1170       RHSKnownOne  <<= ShiftAmt;
1171       // low bits known zero.
1172       if (ShiftAmt)
1173         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1174     }
1175     break;
1176   case Instruction::LShr:
1177     // For a logical shift right
1178     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1179       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1180       
1181       // Unsigned shift right.
1182       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1183       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1184                                RHSKnownZero, RHSKnownOne, Depth+1))
1185         return true;
1186       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1187              "Bits known to be one AND zero?"); 
1188       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1189       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1190       if (ShiftAmt) {
1191         // Compute the new bits that are at the top now.
1192         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1193         RHSKnownZero |= HighBits;  // high bits known zero.
1194       }
1195     }
1196     break;
1197   case Instruction::AShr:
1198     // If this is an arithmetic shift right and only the low-bit is set, we can
1199     // always convert this into a logical shr, even if the shift amount is
1200     // variable.  The low bit of the shift cannot be an input sign bit unless
1201     // the shift amount is >= the size of the datatype, which is undefined.
1202     if (DemandedMask == 1) {
1203       // Perform the logical shift right.
1204       Value *NewVal = BinaryOperator::CreateLShr(
1205                         I->getOperand(0), I->getOperand(1), I->getName());
1206       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1207       return UpdateValueUsesWith(I, NewVal);
1208     }    
1209
1210     // If the sign bit is the only bit demanded by this ashr, then there is no
1211     // need to do it, the shift doesn't change the high bit.
1212     if (DemandedMask.isSignBit())
1213       return UpdateValueUsesWith(I, I->getOperand(0));
1214     
1215     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1216       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1217       
1218       // Signed shift right.
1219       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1220       // If any of the "high bits" are demanded, we should set the sign bit as
1221       // demanded.
1222       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1223         DemandedMaskIn.set(BitWidth-1);
1224       if (SimplifyDemandedBits(I->getOperand(0),
1225                                DemandedMaskIn,
1226                                RHSKnownZero, RHSKnownOne, Depth+1))
1227         return true;
1228       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1229              "Bits known to be one AND zero?"); 
1230       // Compute the new bits that are at the top now.
1231       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1232       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1233       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1234         
1235       // Handle the sign bits.
1236       APInt SignBit(APInt::getSignBit(BitWidth));
1237       // Adjust to where it is now in the mask.
1238       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1239         
1240       // If the input sign bit is known to be zero, or if none of the top bits
1241       // are demanded, turn this into an unsigned shift right.
1242       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1243           (HighBits & ~DemandedMask) == HighBits) {
1244         // Perform the logical shift right.
1245         Value *NewVal = BinaryOperator::CreateLShr(
1246                           I->getOperand(0), SA, I->getName());
1247         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1248         return UpdateValueUsesWith(I, NewVal);
1249       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1250         RHSKnownOne |= HighBits;
1251       }
1252     }
1253     break;
1254   case Instruction::SRem:
1255     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1256       APInt RA = Rem->getValue();
1257       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1258         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1259           return UpdateValueUsesWith(I, I->getOperand(0));
1260
1261         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1262         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1263         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1264                                  LHSKnownZero, LHSKnownOne, Depth+1))
1265           return true;
1266
1267         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1268           LHSKnownZero |= ~LowBits;
1269
1270         KnownZero |= LHSKnownZero & DemandedMask;
1271
1272         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1273       }
1274     }
1275     break;
1276   case Instruction::URem: {
1277     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1278     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1279     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1280                              KnownZero2, KnownOne2, Depth+1))
1281       return true;
1282
1283     uint32_t Leaders = KnownZero2.countLeadingOnes();
1284     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1285                              KnownZero2, KnownOne2, Depth+1))
1286       return true;
1287
1288     Leaders = std::max(Leaders,
1289                        KnownZero2.countLeadingOnes());
1290     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1291     break;
1292   }
1293   case Instruction::Call:
1294     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1295       switch (II->getIntrinsicID()) {
1296       default: break;
1297       case Intrinsic::bswap: {
1298         // If the only bits demanded come from one byte of the bswap result,
1299         // just shift the input byte into position to eliminate the bswap.
1300         unsigned NLZ = DemandedMask.countLeadingZeros();
1301         unsigned NTZ = DemandedMask.countTrailingZeros();
1302           
1303         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1304         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1305         // have 14 leading zeros, round to 8.
1306         NLZ &= ~7;
1307         NTZ &= ~7;
1308         // If we need exactly one byte, we can do this transformation.
1309         if (BitWidth-NLZ-NTZ == 8) {
1310           unsigned ResultBit = NTZ;
1311           unsigned InputBit = BitWidth-NTZ-8;
1312           
1313           // Replace this with either a left or right shift to get the byte into
1314           // the right place.
1315           Instruction *NewVal;
1316           if (InputBit > ResultBit)
1317             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1318                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1319           else
1320             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1321                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1322           NewVal->takeName(I);
1323           InsertNewInstBefore(NewVal, *I);
1324           return UpdateValueUsesWith(I, NewVal);
1325         }
1326           
1327         // TODO: Could compute known zero/one bits based on the input.
1328         break;
1329       }
1330       }
1331     }
1332     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1333     break;
1334   }
1335   
1336   // If the client is only demanding bits that we know, return the known
1337   // constant.
1338   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1339     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1340   return false;
1341 }
1342
1343
1344 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1345 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1346 /// actually used by the caller.  This method analyzes which elements of the
1347 /// operand are undef and returns that information in UndefElts.
1348 ///
1349 /// If the information about demanded elements can be used to simplify the
1350 /// operation, the operation is simplified, then the resultant value is
1351 /// returned.  This returns null if no change was made.
1352 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1353                                                 uint64_t &UndefElts,
1354                                                 unsigned Depth) {
1355   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1356   assert(VWidth <= 64 && "Vector too wide to analyze!");
1357   uint64_t EltMask = ~0ULL >> (64-VWidth);
1358   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1359          "Invalid DemandedElts!");
1360
1361   if (isa<UndefValue>(V)) {
1362     // If the entire vector is undefined, just return this info.
1363     UndefElts = EltMask;
1364     return 0;
1365   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1366     UndefElts = EltMask;
1367     return UndefValue::get(V->getType());
1368   }
1369   
1370   UndefElts = 0;
1371   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1372     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1373     Constant *Undef = UndefValue::get(EltTy);
1374
1375     std::vector<Constant*> Elts;
1376     for (unsigned i = 0; i != VWidth; ++i)
1377       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1378         Elts.push_back(Undef);
1379         UndefElts |= (1ULL << i);
1380       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1381         Elts.push_back(Undef);
1382         UndefElts |= (1ULL << i);
1383       } else {                               // Otherwise, defined.
1384         Elts.push_back(CP->getOperand(i));
1385       }
1386         
1387     // If we changed the constant, return it.
1388     Constant *NewCP = ConstantVector::get(Elts);
1389     return NewCP != CP ? NewCP : 0;
1390   } else if (isa<ConstantAggregateZero>(V)) {
1391     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1392     // set to undef.
1393     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1394     Constant *Zero = Constant::getNullValue(EltTy);
1395     Constant *Undef = UndefValue::get(EltTy);
1396     std::vector<Constant*> Elts;
1397     for (unsigned i = 0; i != VWidth; ++i)
1398       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1399     UndefElts = DemandedElts ^ EltMask;
1400     return ConstantVector::get(Elts);
1401   }
1402   
1403   if (!V->hasOneUse()) {    // Other users may use these bits.
1404     if (Depth != 0) {       // Not at the root.
1405       // TODO: Just compute the UndefElts information recursively.
1406       return false;
1407     }
1408     return false;
1409   } else if (Depth == 10) {        // Limit search depth.
1410     return false;
1411   }
1412   
1413   Instruction *I = dyn_cast<Instruction>(V);
1414   if (!I) return false;        // Only analyze instructions.
1415   
1416   bool MadeChange = false;
1417   uint64_t UndefElts2;
1418   Value *TmpV;
1419   switch (I->getOpcode()) {
1420   default: break;
1421     
1422   case Instruction::InsertElement: {
1423     // If this is a variable index, we don't know which element it overwrites.
1424     // demand exactly the same input as we produce.
1425     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1426     if (Idx == 0) {
1427       // Note that we can't propagate undef elt info, because we don't know
1428       // which elt is getting updated.
1429       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1430                                         UndefElts2, Depth+1);
1431       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1432       break;
1433     }
1434     
1435     // If this is inserting an element that isn't demanded, remove this
1436     // insertelement.
1437     unsigned IdxNo = Idx->getZExtValue();
1438     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1439       return AddSoonDeadInstToWorklist(*I, 0);
1440     
1441     // Otherwise, the element inserted overwrites whatever was there, so the
1442     // input demanded set is simpler than the output set.
1443     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1444                                       DemandedElts & ~(1ULL << IdxNo),
1445                                       UndefElts, Depth+1);
1446     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1447
1448     // The inserted element is defined.
1449     UndefElts |= 1ULL << IdxNo;
1450     break;
1451   }
1452   case Instruction::BitCast: {
1453     // Vector->vector casts only.
1454     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1455     if (!VTy) break;
1456     unsigned InVWidth = VTy->getNumElements();
1457     uint64_t InputDemandedElts = 0;
1458     unsigned Ratio;
1459
1460     if (VWidth == InVWidth) {
1461       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1462       // elements as are demanded of us.
1463       Ratio = 1;
1464       InputDemandedElts = DemandedElts;
1465     } else if (VWidth > InVWidth) {
1466       // Untested so far.
1467       break;
1468       
1469       // If there are more elements in the result than there are in the source,
1470       // then an input element is live if any of the corresponding output
1471       // elements are live.
1472       Ratio = VWidth/InVWidth;
1473       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1474         if (DemandedElts & (1ULL << OutIdx))
1475           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1476       }
1477     } else {
1478       // Untested so far.
1479       break;
1480       
1481       // If there are more elements in the source than there are in the result,
1482       // then an input element is live if the corresponding output element is
1483       // live.
1484       Ratio = InVWidth/VWidth;
1485       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1486         if (DemandedElts & (1ULL << InIdx/Ratio))
1487           InputDemandedElts |= 1ULL << InIdx;
1488     }
1489     
1490     // div/rem demand all inputs, because they don't want divide by zero.
1491     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1492                                       UndefElts2, Depth+1);
1493     if (TmpV) {
1494       I->setOperand(0, TmpV);
1495       MadeChange = true;
1496     }
1497     
1498     UndefElts = UndefElts2;
1499     if (VWidth > InVWidth) {
1500       assert(0 && "Unimp");
1501       // If there are more elements in the result than there are in the source,
1502       // then an output element is undef if the corresponding input element is
1503       // undef.
1504       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1505         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1506           UndefElts |= 1ULL << OutIdx;
1507     } else if (VWidth < InVWidth) {
1508       assert(0 && "Unimp");
1509       // If there are more elements in the source than there are in the result,
1510       // then a result element is undef if all of the corresponding input
1511       // elements are undef.
1512       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1513       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1514         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1515           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1516     }
1517     break;
1518   }
1519   case Instruction::And:
1520   case Instruction::Or:
1521   case Instruction::Xor:
1522   case Instruction::Add:
1523   case Instruction::Sub:
1524   case Instruction::Mul:
1525     // div/rem demand all inputs, because they don't want divide by zero.
1526     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1527                                       UndefElts, Depth+1);
1528     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1529     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1530                                       UndefElts2, Depth+1);
1531     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1532       
1533     // Output elements are undefined if both are undefined.  Consider things
1534     // like undef&0.  The result is known zero, not undef.
1535     UndefElts &= UndefElts2;
1536     break;
1537     
1538   case Instruction::Call: {
1539     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1540     if (!II) break;
1541     switch (II->getIntrinsicID()) {
1542     default: break;
1543       
1544     // Binary vector operations that work column-wise.  A dest element is a
1545     // function of the corresponding input elements from the two inputs.
1546     case Intrinsic::x86_sse_sub_ss:
1547     case Intrinsic::x86_sse_mul_ss:
1548     case Intrinsic::x86_sse_min_ss:
1549     case Intrinsic::x86_sse_max_ss:
1550     case Intrinsic::x86_sse2_sub_sd:
1551     case Intrinsic::x86_sse2_mul_sd:
1552     case Intrinsic::x86_sse2_min_sd:
1553     case Intrinsic::x86_sse2_max_sd:
1554       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1555                                         UndefElts, Depth+1);
1556       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1557       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1558                                         UndefElts2, Depth+1);
1559       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1560
1561       // If only the low elt is demanded and this is a scalarizable intrinsic,
1562       // scalarize it now.
1563       if (DemandedElts == 1) {
1564         switch (II->getIntrinsicID()) {
1565         default: break;
1566         case Intrinsic::x86_sse_sub_ss:
1567         case Intrinsic::x86_sse_mul_ss:
1568         case Intrinsic::x86_sse2_sub_sd:
1569         case Intrinsic::x86_sse2_mul_sd:
1570           // TODO: Lower MIN/MAX/ABS/etc
1571           Value *LHS = II->getOperand(1);
1572           Value *RHS = II->getOperand(2);
1573           // Extract the element as scalars.
1574           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1575           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1576           
1577           switch (II->getIntrinsicID()) {
1578           default: assert(0 && "Case stmts out of sync!");
1579           case Intrinsic::x86_sse_sub_ss:
1580           case Intrinsic::x86_sse2_sub_sd:
1581             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1582                                                         II->getName()), *II);
1583             break;
1584           case Intrinsic::x86_sse_mul_ss:
1585           case Intrinsic::x86_sse2_mul_sd:
1586             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1587                                                          II->getName()), *II);
1588             break;
1589           }
1590           
1591           Instruction *New =
1592             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1593                                       II->getName());
1594           InsertNewInstBefore(New, *II);
1595           AddSoonDeadInstToWorklist(*II, 0);
1596           return New;
1597         }            
1598       }
1599         
1600       // Output elements are undefined if both are undefined.  Consider things
1601       // like undef&0.  The result is known zero, not undef.
1602       UndefElts &= UndefElts2;
1603       break;
1604     }
1605     break;
1606   }
1607   }
1608   return MadeChange ? I : 0;
1609 }
1610
1611
1612 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1613 /// function is designed to check a chain of associative operators for a
1614 /// potential to apply a certain optimization.  Since the optimization may be
1615 /// applicable if the expression was reassociated, this checks the chain, then
1616 /// reassociates the expression as necessary to expose the optimization
1617 /// opportunity.  This makes use of a special Functor, which must define
1618 /// 'shouldApply' and 'apply' methods.
1619 ///
1620 template<typename Functor>
1621 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1622   unsigned Opcode = Root.getOpcode();
1623   Value *LHS = Root.getOperand(0);
1624
1625   // Quick check, see if the immediate LHS matches...
1626   if (F.shouldApply(LHS))
1627     return F.apply(Root);
1628
1629   // Otherwise, if the LHS is not of the same opcode as the root, return.
1630   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1631   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1632     // Should we apply this transform to the RHS?
1633     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1634
1635     // If not to the RHS, check to see if we should apply to the LHS...
1636     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1637       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1638       ShouldApply = true;
1639     }
1640
1641     // If the functor wants to apply the optimization to the RHS of LHSI,
1642     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1643     if (ShouldApply) {
1644       // Now all of the instructions are in the current basic block, go ahead
1645       // and perform the reassociation.
1646       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1647
1648       // First move the selected RHS to the LHS of the root...
1649       Root.setOperand(0, LHSI->getOperand(1));
1650
1651       // Make what used to be the LHS of the root be the user of the root...
1652       Value *ExtraOperand = TmpLHSI->getOperand(1);
1653       if (&Root == TmpLHSI) {
1654         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1655         return 0;
1656       }
1657       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1658       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1659       BasicBlock::iterator ARI = &Root; ++ARI;
1660       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1661       ARI = Root;
1662
1663       // Now propagate the ExtraOperand down the chain of instructions until we
1664       // get to LHSI.
1665       while (TmpLHSI != LHSI) {
1666         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1667         // Move the instruction to immediately before the chain we are
1668         // constructing to avoid breaking dominance properties.
1669         NextLHSI->moveBefore(ARI);
1670         ARI = NextLHSI;
1671
1672         Value *NextOp = NextLHSI->getOperand(1);
1673         NextLHSI->setOperand(1, ExtraOperand);
1674         TmpLHSI = NextLHSI;
1675         ExtraOperand = NextOp;
1676       }
1677
1678       // Now that the instructions are reassociated, have the functor perform
1679       // the transformation...
1680       return F.apply(Root);
1681     }
1682
1683     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1684   }
1685   return 0;
1686 }
1687
1688 namespace {
1689
1690 // AddRHS - Implements: X + X --> X << 1
1691 struct AddRHS {
1692   Value *RHS;
1693   AddRHS(Value *rhs) : RHS(rhs) {}
1694   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1695   Instruction *apply(BinaryOperator &Add) const {
1696     return BinaryOperator::CreateShl(Add.getOperand(0),
1697                                      ConstantInt::get(Add.getType(), 1));
1698   }
1699 };
1700
1701 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1702 //                 iff C1&C2 == 0
1703 struct AddMaskingAnd {
1704   Constant *C2;
1705   AddMaskingAnd(Constant *c) : C2(c) {}
1706   bool shouldApply(Value *LHS) const {
1707     ConstantInt *C1;
1708     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1709            ConstantExpr::getAnd(C1, C2)->isNullValue();
1710   }
1711   Instruction *apply(BinaryOperator &Add) const {
1712     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1713   }
1714 };
1715
1716 }
1717
1718 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1719                                              InstCombiner *IC) {
1720   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1721     if (Constant *SOC = dyn_cast<Constant>(SO))
1722       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1723
1724     return IC->InsertNewInstBefore(CastInst::Create(
1725           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1726   }
1727
1728   // Figure out if the constant is the left or the right argument.
1729   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1730   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1731
1732   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1733     if (ConstIsRHS)
1734       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1735     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1736   }
1737
1738   Value *Op0 = SO, *Op1 = ConstOperand;
1739   if (!ConstIsRHS)
1740     std::swap(Op0, Op1);
1741   Instruction *New;
1742   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1743     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1744   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1745     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1746                           SO->getName()+".cmp");
1747   else {
1748     assert(0 && "Unknown binary instruction type!");
1749     abort();
1750   }
1751   return IC->InsertNewInstBefore(New, I);
1752 }
1753
1754 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1755 // constant as the other operand, try to fold the binary operator into the
1756 // select arguments.  This also works for Cast instructions, which obviously do
1757 // not have a second operand.
1758 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1759                                      InstCombiner *IC) {
1760   // Don't modify shared select instructions
1761   if (!SI->hasOneUse()) return 0;
1762   Value *TV = SI->getOperand(1);
1763   Value *FV = SI->getOperand(2);
1764
1765   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1766     // Bool selects with constant operands can be folded to logical ops.
1767     if (SI->getType() == Type::Int1Ty) return 0;
1768
1769     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1770     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1771
1772     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1773                               SelectFalseVal);
1774   }
1775   return 0;
1776 }
1777
1778
1779 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1780 /// node as operand #0, see if we can fold the instruction into the PHI (which
1781 /// is only possible if all operands to the PHI are constants).
1782 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1783   PHINode *PN = cast<PHINode>(I.getOperand(0));
1784   unsigned NumPHIValues = PN->getNumIncomingValues();
1785   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1786
1787   // Check to see if all of the operands of the PHI are constants.  If there is
1788   // one non-constant value, remember the BB it is.  If there is more than one
1789   // or if *it* is a PHI, bail out.
1790   BasicBlock *NonConstBB = 0;
1791   for (unsigned i = 0; i != NumPHIValues; ++i)
1792     if (!isa<Constant>(PN->getIncomingValue(i))) {
1793       if (NonConstBB) return 0;  // More than one non-const value.
1794       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1795       NonConstBB = PN->getIncomingBlock(i);
1796       
1797       // If the incoming non-constant value is in I's block, we have an infinite
1798       // loop.
1799       if (NonConstBB == I.getParent())
1800         return 0;
1801     }
1802   
1803   // If there is exactly one non-constant value, we can insert a copy of the
1804   // operation in that block.  However, if this is a critical edge, we would be
1805   // inserting the computation one some other paths (e.g. inside a loop).  Only
1806   // do this if the pred block is unconditionally branching into the phi block.
1807   if (NonConstBB) {
1808     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1809     if (!BI || !BI->isUnconditional()) return 0;
1810   }
1811
1812   // Okay, we can do the transformation: create the new PHI node.
1813   PHINode *NewPN = PHINode::Create(I.getType(), "");
1814   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1815   InsertNewInstBefore(NewPN, *PN);
1816   NewPN->takeName(PN);
1817
1818   // Next, add all of the operands to the PHI.
1819   if (I.getNumOperands() == 2) {
1820     Constant *C = cast<Constant>(I.getOperand(1));
1821     for (unsigned i = 0; i != NumPHIValues; ++i) {
1822       Value *InV = 0;
1823       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1824         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1825           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1826         else
1827           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1828       } else {
1829         assert(PN->getIncomingBlock(i) == NonConstBB);
1830         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1831           InV = BinaryOperator::Create(BO->getOpcode(),
1832                                        PN->getIncomingValue(i), C, "phitmp",
1833                                        NonConstBB->getTerminator());
1834         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1835           InV = CmpInst::Create(CI->getOpcode(), 
1836                                 CI->getPredicate(),
1837                                 PN->getIncomingValue(i), C, "phitmp",
1838                                 NonConstBB->getTerminator());
1839         else
1840           assert(0 && "Unknown binop!");
1841         
1842         AddToWorkList(cast<Instruction>(InV));
1843       }
1844       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1845     }
1846   } else { 
1847     CastInst *CI = cast<CastInst>(&I);
1848     const Type *RetTy = CI->getType();
1849     for (unsigned i = 0; i != NumPHIValues; ++i) {
1850       Value *InV;
1851       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1852         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1853       } else {
1854         assert(PN->getIncomingBlock(i) == NonConstBB);
1855         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1856                                I.getType(), "phitmp", 
1857                                NonConstBB->getTerminator());
1858         AddToWorkList(cast<Instruction>(InV));
1859       }
1860       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1861     }
1862   }
1863   return ReplaceInstUsesWith(I, NewPN);
1864 }
1865
1866
1867 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1868 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1869 /// This basically requires proving that the add in the original type would not
1870 /// overflow to change the sign bit or have a carry out.
1871 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1872   // There are different heuristics we can use for this.  Here are some simple
1873   // ones.
1874   
1875   // Add has the property that adding any two 2's complement numbers can only 
1876   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1877   // have at least two sign bits, we know that the addition of the two values will
1878   // sign extend fine.
1879   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1880     return true;
1881   
1882   
1883   // If one of the operands only has one non-zero bit, and if the other operand
1884   // has a known-zero bit in a more significant place than it (not including the
1885   // sign bit) the ripple may go up to and fill the zero, but won't change the
1886   // sign.  For example, (X & ~4) + 1.
1887   
1888   // TODO: Implement.
1889   
1890   return false;
1891 }
1892
1893
1894 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1895   bool Changed = SimplifyCommutative(I);
1896   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1897
1898   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1899     // X + undef -> undef
1900     if (isa<UndefValue>(RHS))
1901       return ReplaceInstUsesWith(I, RHS);
1902
1903     // X + 0 --> X
1904     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1905       if (RHSC->isNullValue())
1906         return ReplaceInstUsesWith(I, LHS);
1907     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1908       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1909                               (I.getType())->getValueAPF()))
1910         return ReplaceInstUsesWith(I, LHS);
1911     }
1912
1913     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1914       // X + (signbit) --> X ^ signbit
1915       const APInt& Val = CI->getValue();
1916       uint32_t BitWidth = Val.getBitWidth();
1917       if (Val == APInt::getSignBit(BitWidth))
1918         return BinaryOperator::CreateXor(LHS, RHS);
1919       
1920       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1921       // (X & 254)+1 -> (X&254)|1
1922       if (!isa<VectorType>(I.getType())) {
1923         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1924         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1925                                  KnownZero, KnownOne))
1926           return &I;
1927       }
1928     }
1929
1930     if (isa<PHINode>(LHS))
1931       if (Instruction *NV = FoldOpIntoPhi(I))
1932         return NV;
1933     
1934     ConstantInt *XorRHS = 0;
1935     Value *XorLHS = 0;
1936     if (isa<ConstantInt>(RHSC) &&
1937         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1938       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1939       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1940       
1941       uint32_t Size = TySizeBits / 2;
1942       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1943       APInt CFF80Val(-C0080Val);
1944       do {
1945         if (TySizeBits > Size) {
1946           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1947           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1948           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1949               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1950             // This is a sign extend if the top bits are known zero.
1951             if (!MaskedValueIsZero(XorLHS, 
1952                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1953               Size = 0;  // Not a sign ext, but can't be any others either.
1954             break;
1955           }
1956         }
1957         Size >>= 1;
1958         C0080Val = APIntOps::lshr(C0080Val, Size);
1959         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1960       } while (Size >= 1);
1961       
1962       // FIXME: This shouldn't be necessary. When the backends can handle types
1963       // with funny bit widths then this switch statement should be removed. It
1964       // is just here to get the size of the "middle" type back up to something
1965       // that the back ends can handle.
1966       const Type *MiddleType = 0;
1967       switch (Size) {
1968         default: break;
1969         case 32: MiddleType = Type::Int32Ty; break;
1970         case 16: MiddleType = Type::Int16Ty; break;
1971         case  8: MiddleType = Type::Int8Ty; break;
1972       }
1973       if (MiddleType) {
1974         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1975         InsertNewInstBefore(NewTrunc, I);
1976         return new SExtInst(NewTrunc, I.getType(), I.getName());
1977       }
1978     }
1979   }
1980
1981   if (I.getType() == Type::Int1Ty)
1982     return BinaryOperator::CreateXor(LHS, RHS);
1983
1984   // X + X --> X << 1
1985   if (I.getType()->isInteger()) {
1986     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1987
1988     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1989       if (RHSI->getOpcode() == Instruction::Sub)
1990         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1991           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1992     }
1993     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1994       if (LHSI->getOpcode() == Instruction::Sub)
1995         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1996           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1997     }
1998   }
1999
2000   // -A + B  -->  B - A
2001   // -A + -B  -->  -(A + B)
2002   if (Value *LHSV = dyn_castNegVal(LHS)) {
2003     if (LHS->getType()->isIntOrIntVector()) {
2004       if (Value *RHSV = dyn_castNegVal(RHS)) {
2005         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2006         InsertNewInstBefore(NewAdd, I);
2007         return BinaryOperator::CreateNeg(NewAdd);
2008       }
2009     }
2010     
2011     return BinaryOperator::CreateSub(RHS, LHSV);
2012   }
2013
2014   // A + -B  -->  A - B
2015   if (!isa<Constant>(RHS))
2016     if (Value *V = dyn_castNegVal(RHS))
2017       return BinaryOperator::CreateSub(LHS, V);
2018
2019
2020   ConstantInt *C2;
2021   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2022     if (X == RHS)   // X*C + X --> X * (C+1)
2023       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2024
2025     // X*C1 + X*C2 --> X * (C1+C2)
2026     ConstantInt *C1;
2027     if (X == dyn_castFoldableMul(RHS, C1))
2028       return BinaryOperator::CreateMul(X, Add(C1, C2));
2029   }
2030
2031   // X + X*C --> X * (C+1)
2032   if (dyn_castFoldableMul(RHS, C2) == LHS)
2033     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2034
2035   // X + ~X --> -1   since   ~X = -X-1
2036   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2037     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2038   
2039
2040   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2041   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2042     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2043       return R;
2044   
2045   // A+B --> A|B iff A and B have no bits set in common.
2046   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2047     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2048     APInt LHSKnownOne(IT->getBitWidth(), 0);
2049     APInt LHSKnownZero(IT->getBitWidth(), 0);
2050     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2051     if (LHSKnownZero != 0) {
2052       APInt RHSKnownOne(IT->getBitWidth(), 0);
2053       APInt RHSKnownZero(IT->getBitWidth(), 0);
2054       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2055       
2056       // No bits in common -> bitwise or.
2057       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2058         return BinaryOperator::CreateOr(LHS, RHS);
2059     }
2060   }
2061
2062   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2063   if (I.getType()->isIntOrIntVector()) {
2064     Value *W, *X, *Y, *Z;
2065     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2066         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2067       if (W != Y) {
2068         if (W == Z) {
2069           std::swap(Y, Z);
2070         } else if (Y == X) {
2071           std::swap(W, X);
2072         } else if (X == Z) {
2073           std::swap(Y, Z);
2074           std::swap(W, X);
2075         }
2076       }
2077
2078       if (W == Y) {
2079         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2080                                                             LHS->getName()), I);
2081         return BinaryOperator::CreateMul(W, NewAdd);
2082       }
2083     }
2084   }
2085
2086   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2087     Value *X = 0;
2088     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2089       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2090
2091     // (X & FF00) + xx00  -> (X+xx00) & FF00
2092     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2093       Constant *Anded = And(CRHS, C2);
2094       if (Anded == CRHS) {
2095         // See if all bits from the first bit set in the Add RHS up are included
2096         // in the mask.  First, get the rightmost bit.
2097         const APInt& AddRHSV = CRHS->getValue();
2098
2099         // Form a mask of all bits from the lowest bit added through the top.
2100         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2101
2102         // See if the and mask includes all of these bits.
2103         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2104
2105         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2106           // Okay, the xform is safe.  Insert the new add pronto.
2107           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2108                                                             LHS->getName()), I);
2109           return BinaryOperator::CreateAnd(NewAdd, C2);
2110         }
2111       }
2112     }
2113
2114     // Try to fold constant add into select arguments.
2115     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2116       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2117         return R;
2118   }
2119
2120   // add (cast *A to intptrtype) B -> 
2121   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2122   {
2123     CastInst *CI = dyn_cast<CastInst>(LHS);
2124     Value *Other = RHS;
2125     if (!CI) {
2126       CI = dyn_cast<CastInst>(RHS);
2127       Other = LHS;
2128     }
2129     if (CI && CI->getType()->isSized() && 
2130         (CI->getType()->getPrimitiveSizeInBits() == 
2131          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2132         && isa<PointerType>(CI->getOperand(0)->getType())) {
2133       unsigned AS =
2134         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2135       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2136                                       PointerType::get(Type::Int8Ty, AS), I);
2137       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2138       return new PtrToIntInst(I2, CI->getType());
2139     }
2140   }
2141   
2142   // add (select X 0 (sub n A)) A  -->  select X A n
2143   {
2144     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2145     Value *Other = RHS;
2146     if (!SI) {
2147       SI = dyn_cast<SelectInst>(RHS);
2148       Other = LHS;
2149     }
2150     if (SI && SI->hasOneUse()) {
2151       Value *TV = SI->getTrueValue();
2152       Value *FV = SI->getFalseValue();
2153       Value *A, *N;
2154
2155       // Can we fold the add into the argument of the select?
2156       // We check both true and false select arguments for a matching subtract.
2157       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2158           A == Other)  // Fold the add into the true select value.
2159         return SelectInst::Create(SI->getCondition(), N, A);
2160       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2161           A == Other)  // Fold the add into the false select value.
2162         return SelectInst::Create(SI->getCondition(), A, N);
2163     }
2164   }
2165   
2166   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2167   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2168     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2169       return ReplaceInstUsesWith(I, LHS);
2170
2171   // Check for (add (sext x), y), see if we can merge this into an
2172   // integer add followed by a sext.
2173   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2174     // (add (sext x), cst) --> (sext (add x, cst'))
2175     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2176       Constant *CI = 
2177         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2178       if (LHSConv->hasOneUse() &&
2179           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2180           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2181         // Insert the new, smaller add.
2182         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2183                                                         CI, "addconv");
2184         InsertNewInstBefore(NewAdd, I);
2185         return new SExtInst(NewAdd, I.getType());
2186       }
2187     }
2188     
2189     // (add (sext x), (sext y)) --> (sext (add int x, y))
2190     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2191       // Only do this if x/y have the same type, if at last one of them has a
2192       // single use (so we don't increase the number of sexts), and if the
2193       // integer add will not overflow.
2194       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2195           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2196           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2197                                    RHSConv->getOperand(0))) {
2198         // Insert the new integer add.
2199         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2200                                                         RHSConv->getOperand(0),
2201                                                         "addconv");
2202         InsertNewInstBefore(NewAdd, I);
2203         return new SExtInst(NewAdd, I.getType());
2204       }
2205     }
2206   }
2207   
2208   // Check for (add double (sitofp x), y), see if we can merge this into an
2209   // integer add followed by a promotion.
2210   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2211     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2212     // ... if the constant fits in the integer value.  This is useful for things
2213     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2214     // requires a constant pool load, and generally allows the add to be better
2215     // instcombined.
2216     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2217       Constant *CI = 
2218       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2219       if (LHSConv->hasOneUse() &&
2220           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2221           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2222         // Insert the new integer add.
2223         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2224                                                         CI, "addconv");
2225         InsertNewInstBefore(NewAdd, I);
2226         return new SIToFPInst(NewAdd, I.getType());
2227       }
2228     }
2229     
2230     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2231     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2232       // Only do this if x/y have the same type, if at last one of them has a
2233       // single use (so we don't increase the number of int->fp conversions),
2234       // and if the integer add will not overflow.
2235       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2236           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2237           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2238                                    RHSConv->getOperand(0))) {
2239         // Insert the new integer add.
2240         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2241                                                         RHSConv->getOperand(0),
2242                                                         "addconv");
2243         InsertNewInstBefore(NewAdd, I);
2244         return new SIToFPInst(NewAdd, I.getType());
2245       }
2246     }
2247   }
2248   
2249   return Changed ? &I : 0;
2250 }
2251
2252 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2253   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2254
2255   if (Op0 == Op1 &&                        // sub X, X  -> 0
2256       !I.getType()->isFPOrFPVector())
2257     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2258
2259   // If this is a 'B = x-(-A)', change to B = x+A...
2260   if (Value *V = dyn_castNegVal(Op1))
2261     return BinaryOperator::CreateAdd(Op0, V);
2262
2263   if (isa<UndefValue>(Op0))
2264     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2265   if (isa<UndefValue>(Op1))
2266     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2267
2268   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2269     // Replace (-1 - A) with (~A)...
2270     if (C->isAllOnesValue())
2271       return BinaryOperator::CreateNot(Op1);
2272
2273     // C - ~X == X + (1+C)
2274     Value *X = 0;
2275     if (match(Op1, m_Not(m_Value(X))))
2276       return BinaryOperator::CreateAdd(X, AddOne(C));
2277
2278     // -(X >>u 31) -> (X >>s 31)
2279     // -(X >>s 31) -> (X >>u 31)
2280     if (C->isZero()) {
2281       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2282         if (SI->getOpcode() == Instruction::LShr) {
2283           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2284             // Check to see if we are shifting out everything but the sign bit.
2285             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2286                 SI->getType()->getPrimitiveSizeInBits()-1) {
2287               // Ok, the transformation is safe.  Insert AShr.
2288               return BinaryOperator::Create(Instruction::AShr, 
2289                                           SI->getOperand(0), CU, SI->getName());
2290             }
2291           }
2292         }
2293         else if (SI->getOpcode() == Instruction::AShr) {
2294           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2295             // Check to see if we are shifting out everything but the sign bit.
2296             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2297                 SI->getType()->getPrimitiveSizeInBits()-1) {
2298               // Ok, the transformation is safe.  Insert LShr. 
2299               return BinaryOperator::CreateLShr(
2300                                           SI->getOperand(0), CU, SI->getName());
2301             }
2302           }
2303         }
2304       }
2305     }
2306
2307     // Try to fold constant sub into select arguments.
2308     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2309       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2310         return R;
2311
2312     if (isa<PHINode>(Op0))
2313       if (Instruction *NV = FoldOpIntoPhi(I))
2314         return NV;
2315   }
2316
2317   if (I.getType() == Type::Int1Ty)
2318     return BinaryOperator::CreateXor(Op0, Op1);
2319
2320   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2321     if (Op1I->getOpcode() == Instruction::Add &&
2322         !Op0->getType()->isFPOrFPVector()) {
2323       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2324         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2325       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2326         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2327       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2328         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2329           // C1-(X+C2) --> (C1-C2)-X
2330           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2331                                            Op1I->getOperand(0));
2332       }
2333     }
2334
2335     if (Op1I->hasOneUse()) {
2336       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2337       // is not used by anyone else...
2338       //
2339       if (Op1I->getOpcode() == Instruction::Sub &&
2340           !Op1I->getType()->isFPOrFPVector()) {
2341         // Swap the two operands of the subexpr...
2342         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2343         Op1I->setOperand(0, IIOp1);
2344         Op1I->setOperand(1, IIOp0);
2345
2346         // Create the new top level add instruction...
2347         return BinaryOperator::CreateAdd(Op0, Op1);
2348       }
2349
2350       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2351       //
2352       if (Op1I->getOpcode() == Instruction::And &&
2353           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2354         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2355
2356         Value *NewNot =
2357           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2358         return BinaryOperator::CreateAnd(Op0, NewNot);
2359       }
2360
2361       // 0 - (X sdiv C)  -> (X sdiv -C)
2362       if (Op1I->getOpcode() == Instruction::SDiv)
2363         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2364           if (CSI->isZero())
2365             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2366               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2367                                                ConstantExpr::getNeg(DivRHS));
2368
2369       // X - X*C --> X * (1-C)
2370       ConstantInt *C2 = 0;
2371       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2372         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2373         return BinaryOperator::CreateMul(Op0, CP1);
2374       }
2375
2376       // X - ((X / Y) * Y) --> X % Y
2377       if (Op1I->getOpcode() == Instruction::Mul)
2378         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2379           if (Op0 == I->getOperand(0) &&
2380               Op1I->getOperand(1) == I->getOperand(1)) {
2381             if (I->getOpcode() == Instruction::SDiv)
2382               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2383             if (I->getOpcode() == Instruction::UDiv)
2384               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2385           }
2386     }
2387   }
2388
2389   if (!Op0->getType()->isFPOrFPVector())
2390     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2391       if (Op0I->getOpcode() == Instruction::Add) {
2392         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2393           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2394         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2395           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2396       } else if (Op0I->getOpcode() == Instruction::Sub) {
2397         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2398           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2399       }
2400     }
2401
2402   ConstantInt *C1;
2403   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2404     if (X == Op1)  // X*C - X --> X * (C-1)
2405       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2406
2407     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2408     if (X == dyn_castFoldableMul(Op1, C2))
2409       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2410   }
2411   return 0;
2412 }
2413
2414 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2415 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2416 /// TrueIfSigned if the result of the comparison is true when the input value is
2417 /// signed.
2418 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2419                            bool &TrueIfSigned) {
2420   switch (pred) {
2421   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2422     TrueIfSigned = true;
2423     return RHS->isZero();
2424   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2425     TrueIfSigned = true;
2426     return RHS->isAllOnesValue();
2427   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2428     TrueIfSigned = false;
2429     return RHS->isAllOnesValue();
2430   case ICmpInst::ICMP_UGT:
2431     // True if LHS u> RHS and RHS == high-bit-mask - 1
2432     TrueIfSigned = true;
2433     return RHS->getValue() ==
2434       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2435   case ICmpInst::ICMP_UGE: 
2436     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2437     TrueIfSigned = true;
2438     return RHS->getValue().isSignBit();
2439   default:
2440     return false;
2441   }
2442 }
2443
2444 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2445   bool Changed = SimplifyCommutative(I);
2446   Value *Op0 = I.getOperand(0);
2447
2448   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2449     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2450
2451   // Simplify mul instructions with a constant RHS...
2452   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2453     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2454
2455       // ((X << C1)*C2) == (X * (C2 << C1))
2456       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2457         if (SI->getOpcode() == Instruction::Shl)
2458           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2459             return BinaryOperator::CreateMul(SI->getOperand(0),
2460                                              ConstantExpr::getShl(CI, ShOp));
2461
2462       if (CI->isZero())
2463         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2464       if (CI->equalsInt(1))                  // X * 1  == X
2465         return ReplaceInstUsesWith(I, Op0);
2466       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2467         return BinaryOperator::CreateNeg(Op0, I.getName());
2468
2469       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2470       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2471         return BinaryOperator::CreateShl(Op0,
2472                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2473       }
2474     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2475       if (Op1F->isNullValue())
2476         return ReplaceInstUsesWith(I, Op1);
2477
2478       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2479       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2480       if (Op1F->isExactlyValue(1.0))
2481         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2482     } else if (isa<VectorType>(Op1->getType())) {
2483       if (isa<ConstantAggregateZero>(Op1))
2484         return ReplaceInstUsesWith(I, Op1);
2485       
2486       // As above, vector X*splat(1.0) -> X in all defined cases.
2487       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1))
2488         if (ConstantFP *F = dyn_cast_or_null<ConstantFP>(Op1V->getSplatValue()))
2489           if (F->isExactlyValue(1.0))
2490             return ReplaceInstUsesWith(I, Op0);
2491     }
2492     
2493     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2494       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2495           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2496         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2497         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2498                                                      Op1, "tmp");
2499         InsertNewInstBefore(Add, I);
2500         Value *C1C2 = ConstantExpr::getMul(Op1, 
2501                                            cast<Constant>(Op0I->getOperand(1)));
2502         return BinaryOperator::CreateAdd(Add, C1C2);
2503         
2504       }
2505
2506     // Try to fold constant mul into select arguments.
2507     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2508       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2509         return R;
2510
2511     if (isa<PHINode>(Op0))
2512       if (Instruction *NV = FoldOpIntoPhi(I))
2513         return NV;
2514   }
2515
2516   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2517     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2518       return BinaryOperator::CreateMul(Op0v, Op1v);
2519
2520   if (I.getType() == Type::Int1Ty)
2521     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2522
2523   // If one of the operands of the multiply is a cast from a boolean value, then
2524   // we know the bool is either zero or one, so this is a 'masking' multiply.
2525   // See if we can simplify things based on how the boolean was originally
2526   // formed.
2527   CastInst *BoolCast = 0;
2528   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2529     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2530       BoolCast = CI;
2531   if (!BoolCast)
2532     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2533       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2534         BoolCast = CI;
2535   if (BoolCast) {
2536     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2537       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2538       const Type *SCOpTy = SCIOp0->getType();
2539       bool TIS = false;
2540       
2541       // If the icmp is true iff the sign bit of X is set, then convert this
2542       // multiply into a shift/and combination.
2543       if (isa<ConstantInt>(SCIOp1) &&
2544           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2545           TIS) {
2546         // Shift the X value right to turn it into "all signbits".
2547         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2548                                           SCOpTy->getPrimitiveSizeInBits()-1);
2549         Value *V =
2550           InsertNewInstBefore(
2551             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2552                                             BoolCast->getOperand(0)->getName()+
2553                                             ".mask"), I);
2554
2555         // If the multiply type is not the same as the source type, sign extend
2556         // or truncate to the multiply type.
2557         if (I.getType() != V->getType()) {
2558           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2559           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2560           Instruction::CastOps opcode = 
2561             (SrcBits == DstBits ? Instruction::BitCast : 
2562              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2563           V = InsertCastBefore(opcode, V, I.getType(), I);
2564         }
2565
2566         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2567         return BinaryOperator::CreateAnd(V, OtherOp);
2568       }
2569     }
2570   }
2571
2572   return Changed ? &I : 0;
2573 }
2574
2575 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2576 /// instruction.
2577 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2578   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2579   
2580   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2581   int NonNullOperand = -1;
2582   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2583     if (ST->isNullValue())
2584       NonNullOperand = 2;
2585   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2586   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2587     if (ST->isNullValue())
2588       NonNullOperand = 1;
2589   
2590   if (NonNullOperand == -1)
2591     return false;
2592   
2593   Value *SelectCond = SI->getOperand(0);
2594   
2595   // Change the div/rem to use 'Y' instead of the select.
2596   I.setOperand(1, SI->getOperand(NonNullOperand));
2597   
2598   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2599   // problem.  However, the select, or the condition of the select may have
2600   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2601   // propagate the known value for the select into other uses of it, and
2602   // propagate a known value of the condition into its other users.
2603   
2604   // If the select and condition only have a single use, don't bother with this,
2605   // early exit.
2606   if (SI->use_empty() && SelectCond->hasOneUse())
2607     return true;
2608   
2609   // Scan the current block backward, looking for other uses of SI.
2610   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2611   
2612   while (BBI != BBFront) {
2613     --BBI;
2614     // If we found a call to a function, we can't assume it will return, so
2615     // information from below it cannot be propagated above it.
2616     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2617       break;
2618     
2619     // Replace uses of the select or its condition with the known values.
2620     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2621          I != E; ++I) {
2622       if (*I == SI) {
2623         *I = SI->getOperand(NonNullOperand);
2624         AddToWorkList(BBI);
2625       } else if (*I == SelectCond) {
2626         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2627                                    ConstantInt::getFalse();
2628         AddToWorkList(BBI);
2629       }
2630     }
2631     
2632     // If we past the instruction, quit looking for it.
2633     if (&*BBI == SI)
2634       SI = 0;
2635     if (&*BBI == SelectCond)
2636       SelectCond = 0;
2637     
2638     // If we ran out of things to eliminate, break out of the loop.
2639     if (SelectCond == 0 && SI == 0)
2640       break;
2641     
2642   }
2643   return true;
2644 }
2645
2646
2647 /// This function implements the transforms on div instructions that work
2648 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2649 /// used by the visitors to those instructions.
2650 /// @brief Transforms common to all three div instructions
2651 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2652   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2653
2654   // undef / X -> 0        for integer.
2655   // undef / X -> undef    for FP (the undef could be a snan).
2656   if (isa<UndefValue>(Op0)) {
2657     if (Op0->getType()->isFPOrFPVector())
2658       return ReplaceInstUsesWith(I, Op0);
2659     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2660   }
2661
2662   // X / undef -> undef
2663   if (isa<UndefValue>(Op1))
2664     return ReplaceInstUsesWith(I, Op1);
2665
2666   return 0;
2667 }
2668
2669 /// This function implements the transforms common to both integer division
2670 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2671 /// division instructions.
2672 /// @brief Common integer divide transforms
2673 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2674   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2675
2676   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2677   if (Op0 == Op1) {
2678     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2679       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2680       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2681       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2682     }
2683
2684     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2685     return ReplaceInstUsesWith(I, CI);
2686   }
2687   
2688   if (Instruction *Common = commonDivTransforms(I))
2689     return Common;
2690   
2691   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2692   // This does not apply for fdiv.
2693   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2694     return &I;
2695
2696   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2697     // div X, 1 == X
2698     if (RHS->equalsInt(1))
2699       return ReplaceInstUsesWith(I, Op0);
2700
2701     // (X / C1) / C2  -> X / (C1*C2)
2702     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2703       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2704         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2705           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2706             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2707           else 
2708             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2709                                           Multiply(RHS, LHSRHS));
2710         }
2711
2712     if (!RHS->isZero()) { // avoid X udiv 0
2713       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2714         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2715           return R;
2716       if (isa<PHINode>(Op0))
2717         if (Instruction *NV = FoldOpIntoPhi(I))
2718           return NV;
2719     }
2720   }
2721
2722   // 0 / X == 0, we don't need to preserve faults!
2723   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2724     if (LHS->equalsInt(0))
2725       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2726
2727   // It can't be division by zero, hence it must be division by one.
2728   if (I.getType() == Type::Int1Ty)
2729     return ReplaceInstUsesWith(I, Op0);
2730
2731   return 0;
2732 }
2733
2734 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2735   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2736
2737   // Handle the integer div common cases
2738   if (Instruction *Common = commonIDivTransforms(I))
2739     return Common;
2740
2741   // X udiv C^2 -> X >> C
2742   // Check to see if this is an unsigned division with an exact power of 2,
2743   // if so, convert to a right shift.
2744   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2745     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2746       return BinaryOperator::CreateLShr(Op0, 
2747                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2748   }
2749
2750   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2751   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2752     if (RHSI->getOpcode() == Instruction::Shl &&
2753         isa<ConstantInt>(RHSI->getOperand(0))) {
2754       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2755       if (C1.isPowerOf2()) {
2756         Value *N = RHSI->getOperand(1);
2757         const Type *NTy = N->getType();
2758         if (uint32_t C2 = C1.logBase2()) {
2759           Constant *C2V = ConstantInt::get(NTy, C2);
2760           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2761         }
2762         return BinaryOperator::CreateLShr(Op0, N);
2763       }
2764     }
2765   }
2766   
2767   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2768   // where C1&C2 are powers of two.
2769   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2770     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2771       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2772         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2773         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2774           // Compute the shift amounts
2775           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2776           // Construct the "on true" case of the select
2777           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2778           Instruction *TSI = BinaryOperator::CreateLShr(
2779                                                  Op0, TC, SI->getName()+".t");
2780           TSI = InsertNewInstBefore(TSI, I);
2781   
2782           // Construct the "on false" case of the select
2783           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2784           Instruction *FSI = BinaryOperator::CreateLShr(
2785                                                  Op0, FC, SI->getName()+".f");
2786           FSI = InsertNewInstBefore(FSI, I);
2787
2788           // construct the select instruction and return it.
2789           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2790         }
2791       }
2792   return 0;
2793 }
2794
2795 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2796   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2797
2798   // Handle the integer div common cases
2799   if (Instruction *Common = commonIDivTransforms(I))
2800     return Common;
2801
2802   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2803     // sdiv X, -1 == -X
2804     if (RHS->isAllOnesValue())
2805       return BinaryOperator::CreateNeg(Op0);
2806
2807     // -X/C -> X/-C
2808     if (Value *LHSNeg = dyn_castNegVal(Op0))
2809       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2810   }
2811
2812   // If the sign bits of both operands are zero (i.e. we can prove they are
2813   // unsigned inputs), turn this into a udiv.
2814   if (I.getType()->isInteger()) {
2815     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2816     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2817       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2818       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2819     }
2820   }      
2821   
2822   return 0;
2823 }
2824
2825 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2826   return commonDivTransforms(I);
2827 }
2828
2829 /// This function implements the transforms on rem instructions that work
2830 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2831 /// is used by the visitors to those instructions.
2832 /// @brief Transforms common to all three rem instructions
2833 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2834   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2835
2836   // 0 % X == 0 for integer, we don't need to preserve faults!
2837   if (Constant *LHS = dyn_cast<Constant>(Op0))
2838     if (LHS->isNullValue())
2839       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2840
2841   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2842     if (I.getType()->isFPOrFPVector())
2843       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2844     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2845   }
2846   if (isa<UndefValue>(Op1))
2847     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2848
2849   // Handle cases involving: rem X, (select Cond, Y, Z)
2850   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2851     return &I;
2852
2853   return 0;
2854 }
2855
2856 /// This function implements the transforms common to both integer remainder
2857 /// instructions (urem and srem). It is called by the visitors to those integer
2858 /// remainder instructions.
2859 /// @brief Common integer remainder transforms
2860 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2861   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2862
2863   if (Instruction *common = commonRemTransforms(I))
2864     return common;
2865
2866   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2867     // X % 0 == undef, we don't need to preserve faults!
2868     if (RHS->equalsInt(0))
2869       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2870     
2871     if (RHS->equalsInt(1))  // X % 1 == 0
2872       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2873
2874     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2875       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2876         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2877           return R;
2878       } else if (isa<PHINode>(Op0I)) {
2879         if (Instruction *NV = FoldOpIntoPhi(I))
2880           return NV;
2881       }
2882
2883       // See if we can fold away this rem instruction.
2884       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2885       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2886       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2887                                KnownZero, KnownOne))
2888         return &I;
2889     }
2890   }
2891
2892   return 0;
2893 }
2894
2895 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2896   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2897
2898   if (Instruction *common = commonIRemTransforms(I))
2899     return common;
2900   
2901   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2902     // X urem C^2 -> X and C
2903     // Check to see if this is an unsigned remainder with an exact power of 2,
2904     // if so, convert to a bitwise and.
2905     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2906       if (C->getValue().isPowerOf2())
2907         return BinaryOperator::CreateAnd(Op0, SubOne(C));
2908   }
2909
2910   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2911     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2912     if (RHSI->getOpcode() == Instruction::Shl &&
2913         isa<ConstantInt>(RHSI->getOperand(0))) {
2914       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2915         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2916         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2917                                                                    "tmp"), I);
2918         return BinaryOperator::CreateAnd(Op0, Add);
2919       }
2920     }
2921   }
2922
2923   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2924   // where C1&C2 are powers of two.
2925   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2926     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2927       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2928         // STO == 0 and SFO == 0 handled above.
2929         if ((STO->getValue().isPowerOf2()) && 
2930             (SFO->getValue().isPowerOf2())) {
2931           Value *TrueAnd = InsertNewInstBefore(
2932             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2933           Value *FalseAnd = InsertNewInstBefore(
2934             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2935           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2936         }
2937       }
2938   }
2939   
2940   return 0;
2941 }
2942
2943 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2944   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2945
2946   // Handle the integer rem common cases
2947   if (Instruction *common = commonIRemTransforms(I))
2948     return common;
2949   
2950   if (Value *RHSNeg = dyn_castNegVal(Op1))
2951     if (!isa<ConstantInt>(RHSNeg) || 
2952         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2953       // X % -Y -> X % Y
2954       AddUsesToWorkList(I);
2955       I.setOperand(1, RHSNeg);
2956       return &I;
2957     }
2958  
2959   // If the sign bits of both operands are zero (i.e. we can prove they are
2960   // unsigned inputs), turn this into a urem.
2961   if (I.getType()->isInteger()) {
2962     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2963     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2964       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2965       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2966     }
2967   }
2968
2969   return 0;
2970 }
2971
2972 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2973   return commonRemTransforms(I);
2974 }
2975
2976 // isOneBitSet - Return true if there is exactly one bit set in the specified
2977 // constant.
2978 static bool isOneBitSet(const ConstantInt *CI) {
2979   return CI->getValue().isPowerOf2();
2980 }
2981
2982 // isHighOnes - Return true if the constant is of the form 1+0+.
2983 // This is the same as lowones(~X).
2984 static bool isHighOnes(const ConstantInt *CI) {
2985   return (~CI->getValue() + 1).isPowerOf2();
2986 }
2987
2988 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2989 /// are carefully arranged to allow folding of expressions such as:
2990 ///
2991 ///      (A < B) | (A > B) --> (A != B)
2992 ///
2993 /// Note that this is only valid if the first and second predicates have the
2994 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2995 ///
2996 /// Three bits are used to represent the condition, as follows:
2997 ///   0  A > B
2998 ///   1  A == B
2999 ///   2  A < B
3000 ///
3001 /// <=>  Value  Definition
3002 /// 000     0   Always false
3003 /// 001     1   A >  B
3004 /// 010     2   A == B
3005 /// 011     3   A >= B
3006 /// 100     4   A <  B
3007 /// 101     5   A != B
3008 /// 110     6   A <= B
3009 /// 111     7   Always true
3010 ///  
3011 static unsigned getICmpCode(const ICmpInst *ICI) {
3012   switch (ICI->getPredicate()) {
3013     // False -> 0
3014   case ICmpInst::ICMP_UGT: return 1;  // 001
3015   case ICmpInst::ICMP_SGT: return 1;  // 001
3016   case ICmpInst::ICMP_EQ:  return 2;  // 010
3017   case ICmpInst::ICMP_UGE: return 3;  // 011
3018   case ICmpInst::ICMP_SGE: return 3;  // 011
3019   case ICmpInst::ICMP_ULT: return 4;  // 100
3020   case ICmpInst::ICMP_SLT: return 4;  // 100
3021   case ICmpInst::ICMP_NE:  return 5;  // 101
3022   case ICmpInst::ICMP_ULE: return 6;  // 110
3023   case ICmpInst::ICMP_SLE: return 6;  // 110
3024     // True -> 7
3025   default:
3026     assert(0 && "Invalid ICmp predicate!");
3027     return 0;
3028   }
3029 }
3030
3031 /// getICmpValue - This is the complement of getICmpCode, which turns an
3032 /// opcode and two operands into either a constant true or false, or a brand 
3033 /// new ICmp instruction. The sign is passed in to determine which kind
3034 /// of predicate to use in new icmp instructions.
3035 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3036   switch (code) {
3037   default: assert(0 && "Illegal ICmp code!");
3038   case  0: return ConstantInt::getFalse();
3039   case  1: 
3040     if (sign)
3041       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3042     else
3043       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3044   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3045   case  3: 
3046     if (sign)
3047       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3048     else
3049       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3050   case  4: 
3051     if (sign)
3052       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3053     else
3054       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3055   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3056   case  6: 
3057     if (sign)
3058       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3059     else
3060       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3061   case  7: return ConstantInt::getTrue();
3062   }
3063 }
3064
3065 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3066   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3067     (ICmpInst::isSignedPredicate(p1) && 
3068      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3069     (ICmpInst::isSignedPredicate(p2) && 
3070      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3071 }
3072
3073 namespace { 
3074 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3075 struct FoldICmpLogical {
3076   InstCombiner &IC;
3077   Value *LHS, *RHS;
3078   ICmpInst::Predicate pred;
3079   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3080     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3081       pred(ICI->getPredicate()) {}
3082   bool shouldApply(Value *V) const {
3083     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3084       if (PredicatesFoldable(pred, ICI->getPredicate()))
3085         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3086                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3087     return false;
3088   }
3089   Instruction *apply(Instruction &Log) const {
3090     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3091     if (ICI->getOperand(0) != LHS) {
3092       assert(ICI->getOperand(1) == LHS);
3093       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3094     }
3095
3096     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3097     unsigned LHSCode = getICmpCode(ICI);
3098     unsigned RHSCode = getICmpCode(RHSICI);
3099     unsigned Code;
3100     switch (Log.getOpcode()) {
3101     case Instruction::And: Code = LHSCode & RHSCode; break;
3102     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3103     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3104     default: assert(0 && "Illegal logical opcode!"); return 0;
3105     }
3106
3107     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3108                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3109       
3110     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3111     if (Instruction *I = dyn_cast<Instruction>(RV))
3112       return I;
3113     // Otherwise, it's a constant boolean value...
3114     return IC.ReplaceInstUsesWith(Log, RV);
3115   }
3116 };
3117 } // end anonymous namespace
3118
3119 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3120 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3121 // guaranteed to be a binary operator.
3122 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3123                                     ConstantInt *OpRHS,
3124                                     ConstantInt *AndRHS,
3125                                     BinaryOperator &TheAnd) {
3126   Value *X = Op->getOperand(0);
3127   Constant *Together = 0;
3128   if (!Op->isShift())
3129     Together = And(AndRHS, OpRHS);
3130
3131   switch (Op->getOpcode()) {
3132   case Instruction::Xor:
3133     if (Op->hasOneUse()) {
3134       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3135       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3136       InsertNewInstBefore(And, TheAnd);
3137       And->takeName(Op);
3138       return BinaryOperator::CreateXor(And, Together);
3139     }
3140     break;
3141   case Instruction::Or:
3142     if (Together == AndRHS) // (X | C) & C --> C
3143       return ReplaceInstUsesWith(TheAnd, AndRHS);
3144
3145     if (Op->hasOneUse() && Together != OpRHS) {
3146       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3147       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3148       InsertNewInstBefore(Or, TheAnd);
3149       Or->takeName(Op);
3150       return BinaryOperator::CreateAnd(Or, AndRHS);
3151     }
3152     break;
3153   case Instruction::Add:
3154     if (Op->hasOneUse()) {
3155       // Adding a one to a single bit bit-field should be turned into an XOR
3156       // of the bit.  First thing to check is to see if this AND is with a
3157       // single bit constant.
3158       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3159
3160       // If there is only one bit set...
3161       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3162         // Ok, at this point, we know that we are masking the result of the
3163         // ADD down to exactly one bit.  If the constant we are adding has
3164         // no bits set below this bit, then we can eliminate the ADD.
3165         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3166
3167         // Check to see if any bits below the one bit set in AndRHSV are set.
3168         if ((AddRHS & (AndRHSV-1)) == 0) {
3169           // If not, the only thing that can effect the output of the AND is
3170           // the bit specified by AndRHSV.  If that bit is set, the effect of
3171           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3172           // no effect.
3173           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3174             TheAnd.setOperand(0, X);
3175             return &TheAnd;
3176           } else {
3177             // Pull the XOR out of the AND.
3178             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3179             InsertNewInstBefore(NewAnd, TheAnd);
3180             NewAnd->takeName(Op);
3181             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3182           }
3183         }
3184       }
3185     }
3186     break;
3187
3188   case Instruction::Shl: {
3189     // We know that the AND will not produce any of the bits shifted in, so if
3190     // the anded constant includes them, clear them now!
3191     //
3192     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3193     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3194     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3195     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3196
3197     if (CI->getValue() == ShlMask) { 
3198     // Masking out bits that the shift already masks
3199       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3200     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3201       TheAnd.setOperand(1, CI);
3202       return &TheAnd;
3203     }
3204     break;
3205   }
3206   case Instruction::LShr:
3207   {
3208     // We know that the AND will not produce any of the bits shifted in, so if
3209     // the anded constant includes them, clear them now!  This only applies to
3210     // unsigned shifts, because a signed shr may bring in set bits!
3211     //
3212     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3213     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3214     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3215     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3216
3217     if (CI->getValue() == ShrMask) {   
3218     // Masking out bits that the shift already masks.
3219       return ReplaceInstUsesWith(TheAnd, Op);
3220     } else if (CI != AndRHS) {
3221       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3222       return &TheAnd;
3223     }
3224     break;
3225   }
3226   case Instruction::AShr:
3227     // Signed shr.
3228     // See if this is shifting in some sign extension, then masking it out
3229     // with an and.
3230     if (Op->hasOneUse()) {
3231       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3232       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3233       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3234       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3235       if (C == AndRHS) {          // Masking out bits shifted in.
3236         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3237         // Make the argument unsigned.
3238         Value *ShVal = Op->getOperand(0);
3239         ShVal = InsertNewInstBefore(
3240             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3241                                    Op->getName()), TheAnd);
3242         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3243       }
3244     }
3245     break;
3246   }
3247   return 0;
3248 }
3249
3250
3251 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3252 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3253 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3254 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3255 /// insert new instructions.
3256 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3257                                            bool isSigned, bool Inside, 
3258                                            Instruction &IB) {
3259   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3260             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3261          "Lo is not <= Hi in range emission code!");
3262     
3263   if (Inside) {
3264     if (Lo == Hi)  // Trivially false.
3265       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3266
3267     // V >= Min && V < Hi --> V < Hi
3268     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3269       ICmpInst::Predicate pred = (isSigned ? 
3270         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3271       return new ICmpInst(pred, V, Hi);
3272     }
3273
3274     // Emit V-Lo <u Hi-Lo
3275     Constant *NegLo = ConstantExpr::getNeg(Lo);
3276     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3277     InsertNewInstBefore(Add, IB);
3278     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3279     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3280   }
3281
3282   if (Lo == Hi)  // Trivially true.
3283     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3284
3285   // V < Min || V >= Hi -> V > Hi-1
3286   Hi = SubOne(cast<ConstantInt>(Hi));
3287   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3288     ICmpInst::Predicate pred = (isSigned ? 
3289         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3290     return new ICmpInst(pred, V, Hi);
3291   }
3292
3293   // Emit V-Lo >u Hi-1-Lo
3294   // Note that Hi has already had one subtracted from it, above.
3295   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3296   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3297   InsertNewInstBefore(Add, IB);
3298   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3299   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3300 }
3301
3302 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3303 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3304 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3305 // not, since all 1s are not contiguous.
3306 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3307   const APInt& V = Val->getValue();
3308   uint32_t BitWidth = Val->getType()->getBitWidth();
3309   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3310
3311   // look for the first zero bit after the run of ones
3312   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3313   // look for the first non-zero bit
3314   ME = V.getActiveBits(); 
3315   return true;
3316 }
3317
3318 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3319 /// where isSub determines whether the operator is a sub.  If we can fold one of
3320 /// the following xforms:
3321 /// 
3322 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3323 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3324 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3325 ///
3326 /// return (A +/- B).
3327 ///
3328 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3329                                         ConstantInt *Mask, bool isSub,
3330                                         Instruction &I) {
3331   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3332   if (!LHSI || LHSI->getNumOperands() != 2 ||
3333       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3334
3335   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3336
3337   switch (LHSI->getOpcode()) {
3338   default: return 0;
3339   case Instruction::And:
3340     if (And(N, Mask) == Mask) {
3341       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3342       if ((Mask->getValue().countLeadingZeros() + 
3343            Mask->getValue().countPopulation()) == 
3344           Mask->getValue().getBitWidth())
3345         break;
3346
3347       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3348       // part, we don't need any explicit masks to take them out of A.  If that
3349       // is all N is, ignore it.
3350       uint32_t MB = 0, ME = 0;
3351       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3352         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3353         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3354         if (MaskedValueIsZero(RHS, Mask))
3355           break;
3356       }
3357     }
3358     return 0;
3359   case Instruction::Or:
3360   case Instruction::Xor:
3361     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3362     if ((Mask->getValue().countLeadingZeros() + 
3363          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3364         && And(N, Mask)->isZero())
3365       break;
3366     return 0;
3367   }
3368   
3369   Instruction *New;
3370   if (isSub)
3371     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3372   else
3373     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3374   return InsertNewInstBefore(New, I);
3375 }
3376
3377 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3378   bool Changed = SimplifyCommutative(I);
3379   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3380
3381   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3382     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3383
3384   // and X, X = X
3385   if (Op0 == Op1)
3386     return ReplaceInstUsesWith(I, Op1);
3387
3388   // See if we can simplify any instructions used by the instruction whose sole 
3389   // purpose is to compute bits we don't care about.
3390   if (!isa<VectorType>(I.getType())) {
3391     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3392     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3393     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3394                              KnownZero, KnownOne))
3395       return &I;
3396   } else {
3397     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3398       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3399         return ReplaceInstUsesWith(I, I.getOperand(0));
3400     } else if (isa<ConstantAggregateZero>(Op1)) {
3401       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3402     }
3403   }
3404   
3405   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3406     const APInt& AndRHSMask = AndRHS->getValue();
3407     APInt NotAndRHS(~AndRHSMask);
3408
3409     // Optimize a variety of ((val OP C1) & C2) combinations...
3410     if (isa<BinaryOperator>(Op0)) {
3411       Instruction *Op0I = cast<Instruction>(Op0);
3412       Value *Op0LHS = Op0I->getOperand(0);
3413       Value *Op0RHS = Op0I->getOperand(1);
3414       switch (Op0I->getOpcode()) {
3415       case Instruction::Xor:
3416       case Instruction::Or:
3417         // If the mask is only needed on one incoming arm, push it up.
3418         if (Op0I->hasOneUse()) {
3419           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3420             // Not masking anything out for the LHS, move to RHS.
3421             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3422                                                    Op0RHS->getName()+".masked");
3423             InsertNewInstBefore(NewRHS, I);
3424             return BinaryOperator::Create(
3425                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3426           }
3427           if (!isa<Constant>(Op0RHS) &&
3428               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3429             // Not masking anything out for the RHS, move to LHS.
3430             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3431                                                    Op0LHS->getName()+".masked");
3432             InsertNewInstBefore(NewLHS, I);
3433             return BinaryOperator::Create(
3434                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3435           }
3436         }
3437
3438         break;
3439       case Instruction::Add:
3440         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3441         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3442         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3443         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3444           return BinaryOperator::CreateAnd(V, AndRHS);
3445         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3446           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3447         break;
3448
3449       case Instruction::Sub:
3450         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3451         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3452         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3453         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3454           return BinaryOperator::CreateAnd(V, AndRHS);
3455
3456         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3457         // has 1's for all bits that the subtraction with A might affect.
3458         if (Op0I->hasOneUse()) {
3459           uint32_t BitWidth = AndRHSMask.getBitWidth();
3460           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3461           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3462
3463           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3464           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3465               MaskedValueIsZero(Op0LHS, Mask)) {
3466             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3467             InsertNewInstBefore(NewNeg, I);
3468             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3469           }
3470         }
3471         break;
3472
3473       case Instruction::Shl:
3474       case Instruction::LShr:
3475         // (1 << x) & 1 --> zext(x == 0)
3476         // (1 >> x) & 1 --> zext(x == 0)
3477         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3478           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3479                                            Constant::getNullValue(I.getType()));
3480           InsertNewInstBefore(NewICmp, I);
3481           return new ZExtInst(NewICmp, I.getType());
3482         }
3483         break;
3484       }
3485
3486       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3487         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3488           return Res;
3489     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3490       // If this is an integer truncation or change from signed-to-unsigned, and
3491       // if the source is an and/or with immediate, transform it.  This
3492       // frequently occurs for bitfield accesses.
3493       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3494         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3495             CastOp->getNumOperands() == 2)
3496           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3497             if (CastOp->getOpcode() == Instruction::And) {
3498               // Change: and (cast (and X, C1) to T), C2
3499               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3500               // This will fold the two constants together, which may allow 
3501               // other simplifications.
3502               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3503                 CastOp->getOperand(0), I.getType(), 
3504                 CastOp->getName()+".shrunk");
3505               NewCast = InsertNewInstBefore(NewCast, I);
3506               // trunc_or_bitcast(C1)&C2
3507               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3508               C3 = ConstantExpr::getAnd(C3, AndRHS);
3509               return BinaryOperator::CreateAnd(NewCast, C3);
3510             } else if (CastOp->getOpcode() == Instruction::Or) {
3511               // Change: and (cast (or X, C1) to T), C2
3512               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3513               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3514               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3515                 return ReplaceInstUsesWith(I, AndRHS);
3516             }
3517           }
3518       }
3519     }
3520
3521     // Try to fold constant and into select arguments.
3522     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3523       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3524         return R;
3525     if (isa<PHINode>(Op0))
3526       if (Instruction *NV = FoldOpIntoPhi(I))
3527         return NV;
3528   }
3529
3530   Value *Op0NotVal = dyn_castNotVal(Op0);
3531   Value *Op1NotVal = dyn_castNotVal(Op1);
3532
3533   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3534     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3535
3536   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3537   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3538     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3539                                                I.getName()+".demorgan");
3540     InsertNewInstBefore(Or, I);
3541     return BinaryOperator::CreateNot(Or);
3542   }
3543   
3544   {
3545     Value *A = 0, *B = 0, *C = 0, *D = 0;
3546     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3547       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3548         return ReplaceInstUsesWith(I, Op1);
3549     
3550       // (A|B) & ~(A&B) -> A^B
3551       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3552         if ((A == C && B == D) || (A == D && B == C))
3553           return BinaryOperator::CreateXor(A, B);
3554       }
3555     }
3556     
3557     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3558       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3559         return ReplaceInstUsesWith(I, Op0);
3560
3561       // ~(A&B) & (A|B) -> A^B
3562       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3563         if ((A == C && B == D) || (A == D && B == C))
3564           return BinaryOperator::CreateXor(A, B);
3565       }
3566     }
3567     
3568     if (Op0->hasOneUse() &&
3569         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3570       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3571         I.swapOperands();     // Simplify below
3572         std::swap(Op0, Op1);
3573       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3574         cast<BinaryOperator>(Op0)->swapOperands();
3575         I.swapOperands();     // Simplify below
3576         std::swap(Op0, Op1);
3577       }
3578     }
3579     if (Op1->hasOneUse() &&
3580         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3581       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3582         cast<BinaryOperator>(Op1)->swapOperands();
3583         std::swap(A, B);
3584       }
3585       if (A == Op0) {                                // A&(A^B) -> A & ~B
3586         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3587         InsertNewInstBefore(NotB, I);
3588         return BinaryOperator::CreateAnd(A, NotB);
3589       }
3590     }
3591   }
3592   
3593   { // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3594     // where C is a power of 2
3595     Value *A, *B;
3596     ConstantInt *C1, *C2;
3597     ICmpInst::Predicate LHSCC, RHSCC;
3598     if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3599                         m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3600       if (C1 == C2 && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3601           C1->getValue().isPowerOf2()) {
3602         Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3603         InsertNewInstBefore(NewOr, I);
3604         return new ICmpInst(LHSCC, NewOr, C1);
3605       }
3606   }
3607   
3608   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3609     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3610     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3611       return R;
3612
3613     Value *LHSVal, *RHSVal;
3614     ConstantInt *LHSCst, *RHSCst;
3615     ICmpInst::Predicate LHSCC, RHSCC;
3616     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3617       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3618         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3619             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3620             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3621             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3622             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3623             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3624             
3625             // Don't try to fold ICMP_SLT + ICMP_ULT.
3626             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3627              ICmpInst::isSignedPredicate(LHSCC) == 
3628                  ICmpInst::isSignedPredicate(RHSCC))) {
3629           // Ensure that the larger constant is on the RHS.
3630           ICmpInst::Predicate GT;
3631           if (ICmpInst::isSignedPredicate(LHSCC) ||
3632               (ICmpInst::isEquality(LHSCC) && 
3633                ICmpInst::isSignedPredicate(RHSCC)))
3634             GT = ICmpInst::ICMP_SGT;
3635           else
3636             GT = ICmpInst::ICMP_UGT;
3637           
3638           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3639           ICmpInst *LHS = cast<ICmpInst>(Op0);
3640           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3641             std::swap(LHS, RHS);
3642             std::swap(LHSCst, RHSCst);
3643             std::swap(LHSCC, RHSCC);
3644           }
3645
3646           // At this point, we know we have have two icmp instructions
3647           // comparing a value against two constants and and'ing the result
3648           // together.  Because of the above check, we know that we only have
3649           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3650           // (from the FoldICmpLogical check above), that the two constants 
3651           // are not equal and that the larger constant is on the RHS
3652           assert(LHSCst != RHSCst && "Compares not folded above?");
3653
3654           switch (LHSCC) {
3655           default: assert(0 && "Unknown integer condition code!");
3656           case ICmpInst::ICMP_EQ:
3657             switch (RHSCC) {
3658             default: assert(0 && "Unknown integer condition code!");
3659             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3660             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3661             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3662               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3663             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3664             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3665             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3666               return ReplaceInstUsesWith(I, LHS);
3667             }
3668           case ICmpInst::ICMP_NE:
3669             switch (RHSCC) {
3670             default: assert(0 && "Unknown integer condition code!");
3671             case ICmpInst::ICMP_ULT:
3672               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3673                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3674               break;                        // (X != 13 & X u< 15) -> no change
3675             case ICmpInst::ICMP_SLT:
3676               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3677                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3678               break;                        // (X != 13 & X s< 15) -> no change
3679             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3680             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3681             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3682               return ReplaceInstUsesWith(I, RHS);
3683             case ICmpInst::ICMP_NE:
3684               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3685                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3686                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3687                                                       LHSVal->getName()+".off");
3688                 InsertNewInstBefore(Add, I);
3689                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3690                                     ConstantInt::get(Add->getType(), 1));
3691               }
3692               break;                        // (X != 13 & X != 15) -> no change
3693             }
3694             break;
3695           case ICmpInst::ICMP_ULT:
3696             switch (RHSCC) {
3697             default: assert(0 && "Unknown integer condition code!");
3698             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3699             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3700               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3701             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3702               break;
3703             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3704             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3705               return ReplaceInstUsesWith(I, LHS);
3706             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3707               break;
3708             }
3709             break;
3710           case ICmpInst::ICMP_SLT:
3711             switch (RHSCC) {
3712             default: assert(0 && "Unknown integer condition code!");
3713             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3714             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3715               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3716             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3717               break;
3718             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3719             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3720               return ReplaceInstUsesWith(I, LHS);
3721             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3722               break;
3723             }
3724             break;
3725           case ICmpInst::ICMP_UGT:
3726             switch (RHSCC) {
3727             default: assert(0 && "Unknown integer condition code!");
3728             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3729             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3730               return ReplaceInstUsesWith(I, RHS);
3731             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3732               break;
3733             case ICmpInst::ICMP_NE:
3734               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3735                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3736               break;                        // (X u> 13 & X != 15) -> no change
3737             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3738               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3739                                      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, LHSVal, 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(LHSVal, AddOne(LHSCst), RHSCst, true, 
3758                                      true, I);
3759             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3760               break;
3761             }
3762             break;
3763           }
3764         }
3765   }
3766
3767   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3768   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3769     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3770       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3771         const Type *SrcTy = Op0C->getOperand(0)->getType();
3772         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3773             // Only do this if the casts both really cause code to be generated.
3774             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3775                               I.getType(), TD) &&
3776             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3777                               I.getType(), TD)) {
3778           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3779                                                          Op1C->getOperand(0),
3780                                                          I.getName());
3781           InsertNewInstBefore(NewOp, I);
3782           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3783         }
3784       }
3785     
3786   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3787   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3788     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3789       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3790           SI0->getOperand(1) == SI1->getOperand(1) &&
3791           (SI0->hasOneUse() || SI1->hasOneUse())) {
3792         Instruction *NewOp =
3793           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3794                                                         SI1->getOperand(0),
3795                                                         SI0->getName()), I);
3796         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
3797                                       SI1->getOperand(1));
3798       }
3799   }
3800
3801   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3802   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3803     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3804       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3805           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3806         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3807           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3808             // If either of the constants are nans, then the whole thing returns
3809             // false.
3810             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3811               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3812             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3813                                 RHS->getOperand(0));
3814           }
3815     }
3816   }
3817
3818   return Changed ? &I : 0;
3819 }
3820
3821 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3822 /// in the result.  If it does, and if the specified byte hasn't been filled in
3823 /// yet, fill it in and return false.
3824 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3825   Instruction *I = dyn_cast<Instruction>(V);
3826   if (I == 0) return true;
3827
3828   // If this is an or instruction, it is an inner node of the bswap.
3829   if (I->getOpcode() == Instruction::Or)
3830     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3831            CollectBSwapParts(I->getOperand(1), ByteValues);
3832   
3833   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3834   // If this is a shift by a constant int, and it is "24", then its operand
3835   // defines a byte.  We only handle unsigned types here.
3836   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3837     // Not shifting the entire input by N-1 bytes?
3838     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3839         8*(ByteValues.size()-1))
3840       return true;
3841     
3842     unsigned DestNo;
3843     if (I->getOpcode() == Instruction::Shl) {
3844       // X << 24 defines the top byte with the lowest of the input bytes.
3845       DestNo = ByteValues.size()-1;
3846     } else {
3847       // X >>u 24 defines the low byte with the highest of the input bytes.
3848       DestNo = 0;
3849     }
3850     
3851     // If the destination byte value is already defined, the values are or'd
3852     // together, which isn't a bswap (unless it's an or of the same bits).
3853     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3854       return true;
3855     ByteValues[DestNo] = I->getOperand(0);
3856     return false;
3857   }
3858   
3859   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3860   // don't have this.
3861   Value *Shift = 0, *ShiftLHS = 0;
3862   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3863   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3864       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3865     return true;
3866   Instruction *SI = cast<Instruction>(Shift);
3867
3868   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3869   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3870       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3871     return true;
3872   
3873   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3874   unsigned DestByte;
3875   if (AndAmt->getValue().getActiveBits() > 64)
3876     return true;
3877   uint64_t AndAmtVal = AndAmt->getZExtValue();
3878   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3879     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3880       break;
3881   // Unknown mask for bswap.
3882   if (DestByte == ByteValues.size()) return true;
3883   
3884   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3885   unsigned SrcByte;
3886   if (SI->getOpcode() == Instruction::Shl)
3887     SrcByte = DestByte - ShiftBytes;
3888   else
3889     SrcByte = DestByte + ShiftBytes;
3890   
3891   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3892   if (SrcByte != ByteValues.size()-DestByte-1)
3893     return true;
3894   
3895   // If the destination byte value is already defined, the values are or'd
3896   // together, which isn't a bswap (unless it's an or of the same bits).
3897   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3898     return true;
3899   ByteValues[DestByte] = SI->getOperand(0);
3900   return false;
3901 }
3902
3903 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3904 /// If so, insert the new bswap intrinsic and return it.
3905 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3906   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3907   if (!ITy || ITy->getBitWidth() % 16) 
3908     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3909   
3910   /// ByteValues - For each byte of the result, we keep track of which value
3911   /// defines each byte.
3912   SmallVector<Value*, 8> ByteValues;
3913   ByteValues.resize(ITy->getBitWidth()/8);
3914     
3915   // Try to find all the pieces corresponding to the bswap.
3916   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3917       CollectBSwapParts(I.getOperand(1), ByteValues))
3918     return 0;
3919   
3920   // Check to see if all of the bytes come from the same value.
3921   Value *V = ByteValues[0];
3922   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3923   
3924   // Check to make sure that all of the bytes come from the same value.
3925   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3926     if (ByteValues[i] != V)
3927       return 0;
3928   const Type *Tys[] = { ITy };
3929   Module *M = I.getParent()->getParent()->getParent();
3930   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3931   return CallInst::Create(F, V);
3932 }
3933
3934
3935 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3936   bool Changed = SimplifyCommutative(I);
3937   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3938
3939   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3940     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3941
3942   // or X, X = X
3943   if (Op0 == Op1)
3944     return ReplaceInstUsesWith(I, Op0);
3945
3946   // See if we can simplify any instructions used by the instruction whose sole 
3947   // purpose is to compute bits we don't care about.
3948   if (!isa<VectorType>(I.getType())) {
3949     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3950     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3951     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3952                              KnownZero, KnownOne))
3953       return &I;
3954   } else if (isa<ConstantAggregateZero>(Op1)) {
3955     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3956   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3957     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3958       return ReplaceInstUsesWith(I, I.getOperand(1));
3959   }
3960     
3961
3962   
3963   // or X, -1 == -1
3964   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3965     ConstantInt *C1 = 0; Value *X = 0;
3966     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3967     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3968       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3969       InsertNewInstBefore(Or, I);
3970       Or->takeName(Op0);
3971       return BinaryOperator::CreateAnd(Or, 
3972                ConstantInt::get(RHS->getValue() | C1->getValue()));
3973     }
3974
3975     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3976     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3977       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3978       InsertNewInstBefore(Or, I);
3979       Or->takeName(Op0);
3980       return BinaryOperator::CreateXor(Or,
3981                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3982     }
3983
3984     // Try to fold constant and into select arguments.
3985     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3986       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3987         return R;
3988     if (isa<PHINode>(Op0))
3989       if (Instruction *NV = FoldOpIntoPhi(I))
3990         return NV;
3991   }
3992
3993   Value *A = 0, *B = 0;
3994   ConstantInt *C1 = 0, *C2 = 0;
3995
3996   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3997     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3998       return ReplaceInstUsesWith(I, Op1);
3999   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4000     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4001       return ReplaceInstUsesWith(I, Op0);
4002
4003   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4004   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4005   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4006       match(Op1, m_Or(m_Value(), m_Value())) ||
4007       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4008        match(Op1, m_Shift(m_Value(), m_Value())))) {
4009     if (Instruction *BSwap = MatchBSwap(I))
4010       return BSwap;
4011   }
4012   
4013   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4014   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4015       MaskedValueIsZero(Op1, C1->getValue())) {
4016     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4017     InsertNewInstBefore(NOr, I);
4018     NOr->takeName(Op0);
4019     return BinaryOperator::CreateXor(NOr, C1);
4020   }
4021
4022   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4023   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4024       MaskedValueIsZero(Op0, C1->getValue())) {
4025     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4026     InsertNewInstBefore(NOr, I);
4027     NOr->takeName(Op0);
4028     return BinaryOperator::CreateXor(NOr, C1);
4029   }
4030
4031   // (A & C)|(B & D)
4032   Value *C = 0, *D = 0;
4033   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4034       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4035     Value *V1 = 0, *V2 = 0, *V3 = 0;
4036     C1 = dyn_cast<ConstantInt>(C);
4037     C2 = dyn_cast<ConstantInt>(D);
4038     if (C1 && C2) {  // (A & C1)|(B & C2)
4039       // If we have: ((V + N) & C1) | (V & C2)
4040       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4041       // replace with V+N.
4042       if (C1->getValue() == ~C2->getValue()) {
4043         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4044             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4045           // Add commutes, try both ways.
4046           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4047             return ReplaceInstUsesWith(I, A);
4048           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4049             return ReplaceInstUsesWith(I, A);
4050         }
4051         // Or commutes, try both ways.
4052         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4053             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4054           // Add commutes, try both ways.
4055           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4056             return ReplaceInstUsesWith(I, B);
4057           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4058             return ReplaceInstUsesWith(I, B);
4059         }
4060       }
4061       V1 = 0; V2 = 0; V3 = 0;
4062     }
4063     
4064     // Check to see if we have any common things being and'ed.  If so, find the
4065     // terms for V1 & (V2|V3).
4066     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4067       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4068         V1 = A, V2 = C, V3 = D;
4069       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4070         V1 = A, V2 = B, V3 = C;
4071       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4072         V1 = C, V2 = A, V3 = D;
4073       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4074         V1 = C, V2 = A, V3 = B;
4075       
4076       if (V1) {
4077         Value *Or =
4078           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4079         return BinaryOperator::CreateAnd(V1, Or);
4080       }
4081     }
4082   }
4083   
4084   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4085   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4086     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4087       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4088           SI0->getOperand(1) == SI1->getOperand(1) &&
4089           (SI0->hasOneUse() || SI1->hasOneUse())) {
4090         Instruction *NewOp =
4091         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4092                                                      SI1->getOperand(0),
4093                                                      SI0->getName()), I);
4094         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4095                                       SI1->getOperand(1));
4096       }
4097   }
4098
4099   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4100     if (A == Op1)   // ~A | A == -1
4101       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4102   } else {
4103     A = 0;
4104   }
4105   // Note, A is still live here!
4106   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4107     if (Op0 == B)
4108       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4109
4110     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4111     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4112       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4113                                               I.getName()+".demorgan"), I);
4114       return BinaryOperator::CreateNot(And);
4115     }
4116   }
4117
4118   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4119   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4120     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4121       return R;
4122
4123     Value *LHSVal, *RHSVal;
4124     ConstantInt *LHSCst, *RHSCst;
4125     ICmpInst::Predicate LHSCC, RHSCC;
4126     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4127       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4128         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4129             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4130             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4131             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4132             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4133             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4134             // We can't fold (ugt x, C) | (sgt x, C2).
4135             PredicatesFoldable(LHSCC, RHSCC)) {
4136           // Ensure that the larger constant is on the RHS.
4137           ICmpInst *LHS = cast<ICmpInst>(Op0);
4138           bool NeedsSwap;
4139           if (ICmpInst::isSignedPredicate(LHSCC))
4140             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4141           else
4142             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4143             
4144           if (NeedsSwap) {
4145             std::swap(LHS, RHS);
4146             std::swap(LHSCst, RHSCst);
4147             std::swap(LHSCC, RHSCC);
4148           }
4149
4150           // At this point, we know we have have two icmp instructions
4151           // comparing a value against two constants and or'ing the result
4152           // together.  Because of the above check, we know that we only have
4153           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4154           // FoldICmpLogical check above), that the two constants are not
4155           // equal.
4156           assert(LHSCst != RHSCst && "Compares not folded above?");
4157
4158           switch (LHSCC) {
4159           default: assert(0 && "Unknown integer condition code!");
4160           case ICmpInst::ICMP_EQ:
4161             switch (RHSCC) {
4162             default: assert(0 && "Unknown integer condition code!");
4163             case ICmpInst::ICMP_EQ:
4164               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4165                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4166                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4167                                                       LHSVal->getName()+".off");
4168                 InsertNewInstBefore(Add, I);
4169                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4170                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4171               }
4172               break;                         // (X == 13 | X == 15) -> no change
4173             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4174             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4175               break;
4176             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4177             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4178             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4179               return ReplaceInstUsesWith(I, RHS);
4180             }
4181             break;
4182           case ICmpInst::ICMP_NE:
4183             switch (RHSCC) {
4184             default: assert(0 && "Unknown integer condition code!");
4185             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4186             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4187             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4188               return ReplaceInstUsesWith(I, LHS);
4189             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4190             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4191             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4192               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4193             }
4194             break;
4195           case ICmpInst::ICMP_ULT:
4196             switch (RHSCC) {
4197             default: assert(0 && "Unknown integer condition code!");
4198             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4199               break;
4200             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4201               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4202               // this can cause overflow.
4203               if (RHSCst->isMaxValue(false))
4204                 return ReplaceInstUsesWith(I, LHS);
4205               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4206                                      false, I);
4207             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4208               break;
4209             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4210             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4211               return ReplaceInstUsesWith(I, RHS);
4212             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4213               break;
4214             }
4215             break;
4216           case ICmpInst::ICMP_SLT:
4217             switch (RHSCC) {
4218             default: assert(0 && "Unknown integer condition code!");
4219             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4220               break;
4221             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4222               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4223               // this can cause overflow.
4224               if (RHSCst->isMaxValue(true))
4225                 return ReplaceInstUsesWith(I, LHS);
4226               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4227                                      false, I);
4228             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4229               break;
4230             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4231             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4232               return ReplaceInstUsesWith(I, RHS);
4233             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4234               break;
4235             }
4236             break;
4237           case ICmpInst::ICMP_UGT:
4238             switch (RHSCC) {
4239             default: assert(0 && "Unknown integer condition code!");
4240             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4241             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4242               return ReplaceInstUsesWith(I, LHS);
4243             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4244               break;
4245             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4246             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4247               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4248             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4249               break;
4250             }
4251             break;
4252           case ICmpInst::ICMP_SGT:
4253             switch (RHSCC) {
4254             default: assert(0 && "Unknown integer condition code!");
4255             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4256             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4257               return ReplaceInstUsesWith(I, LHS);
4258             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4259               break;
4260             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4261             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4262               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4263             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4264               break;
4265             }
4266             break;
4267           }
4268         }
4269   }
4270     
4271   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4272   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4273     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4274       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4275         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4276             !isa<ICmpInst>(Op1C->getOperand(0))) {
4277           const Type *SrcTy = Op0C->getOperand(0)->getType();
4278           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4279               // Only do this if the casts both really cause code to be
4280               // generated.
4281               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4282                                 I.getType(), TD) &&
4283               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4284                                 I.getType(), TD)) {
4285             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4286                                                           Op1C->getOperand(0),
4287                                                           I.getName());
4288             InsertNewInstBefore(NewOp, I);
4289             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4290           }
4291         }
4292       }
4293   }
4294   
4295     
4296   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4297   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4298     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4299       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4300           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4301           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4302         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4303           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4304             // If either of the constants are nans, then the whole thing returns
4305             // true.
4306             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4307               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4308             
4309             // Otherwise, no need to compare the two constants, compare the
4310             // rest.
4311             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4312                                 RHS->getOperand(0));
4313           }
4314     }
4315   }
4316
4317   return Changed ? &I : 0;
4318 }
4319
4320 namespace {
4321
4322 // XorSelf - Implements: X ^ X --> 0
4323 struct XorSelf {
4324   Value *RHS;
4325   XorSelf(Value *rhs) : RHS(rhs) {}
4326   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4327   Instruction *apply(BinaryOperator &Xor) const {
4328     return &Xor;
4329   }
4330 };
4331
4332 }
4333
4334 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4335   bool Changed = SimplifyCommutative(I);
4336   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4337
4338   if (isa<UndefValue>(Op1)) {
4339     if (isa<UndefValue>(Op0))
4340       // Handle undef ^ undef -> 0 special case. This is a common
4341       // idiom (misuse).
4342       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4343     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4344   }
4345
4346   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4347   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4348     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4349     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4350   }
4351   
4352   // See if we can simplify any instructions used by the instruction whose sole 
4353   // purpose is to compute bits we don't care about.
4354   if (!isa<VectorType>(I.getType())) {
4355     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4356     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4357     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4358                              KnownZero, KnownOne))
4359       return &I;
4360   } else if (isa<ConstantAggregateZero>(Op1)) {
4361     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4362   }
4363
4364   // Is this a ~ operation?
4365   if (Value *NotOp = dyn_castNotVal(&I)) {
4366     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4367     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4368     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4369       if (Op0I->getOpcode() == Instruction::And || 
4370           Op0I->getOpcode() == Instruction::Or) {
4371         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4372         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4373           Instruction *NotY =
4374             BinaryOperator::CreateNot(Op0I->getOperand(1),
4375                                       Op0I->getOperand(1)->getName()+".not");
4376           InsertNewInstBefore(NotY, I);
4377           if (Op0I->getOpcode() == Instruction::And)
4378             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4379           else
4380             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4381         }
4382       }
4383     }
4384   }
4385   
4386   
4387   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4388     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4389     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4390       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4391         return new ICmpInst(ICI->getInversePredicate(),
4392                             ICI->getOperand(0), ICI->getOperand(1));
4393
4394       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4395         return new FCmpInst(FCI->getInversePredicate(),
4396                             FCI->getOperand(0), FCI->getOperand(1));
4397     }
4398
4399     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4400     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4401       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4402         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4403           Instruction::CastOps Opcode = Op0C->getOpcode();
4404           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4405             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4406                                              Op0C->getDestTy())) {
4407               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4408                                      CI->getOpcode(), CI->getInversePredicate(),
4409                                      CI->getOperand(0), CI->getOperand(1)), I);
4410               NewCI->takeName(CI);
4411               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4412             }
4413           }
4414         }
4415       }
4416     }
4417
4418     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4419       // ~(c-X) == X-c-1 == X+(-c-1)
4420       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4421         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4422           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4423           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4424                                               ConstantInt::get(I.getType(), 1));
4425           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4426         }
4427           
4428       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4429         if (Op0I->getOpcode() == Instruction::Add) {
4430           // ~(X-c) --> (-c-1)-X
4431           if (RHS->isAllOnesValue()) {
4432             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4433             return BinaryOperator::CreateSub(
4434                            ConstantExpr::getSub(NegOp0CI,
4435                                              ConstantInt::get(I.getType(), 1)),
4436                                           Op0I->getOperand(0));
4437           } else if (RHS->getValue().isSignBit()) {
4438             // (X + C) ^ signbit -> (X + C + signbit)
4439             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4440             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4441
4442           }
4443         } else if (Op0I->getOpcode() == Instruction::Or) {
4444           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4445           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4446             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4447             // Anything in both C1 and C2 is known to be zero, remove it from
4448             // NewRHS.
4449             Constant *CommonBits = And(Op0CI, RHS);
4450             NewRHS = ConstantExpr::getAnd(NewRHS, 
4451                                           ConstantExpr::getNot(CommonBits));
4452             AddToWorkList(Op0I);
4453             I.setOperand(0, Op0I->getOperand(0));
4454             I.setOperand(1, NewRHS);
4455             return &I;
4456           }
4457         }
4458       }
4459     }
4460
4461     // Try to fold constant and into select arguments.
4462     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4463       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4464         return R;
4465     if (isa<PHINode>(Op0))
4466       if (Instruction *NV = FoldOpIntoPhi(I))
4467         return NV;
4468   }
4469
4470   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4471     if (X == Op1)
4472       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4473
4474   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4475     if (X == Op0)
4476       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4477
4478   
4479   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4480   if (Op1I) {
4481     Value *A, *B;
4482     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4483       if (A == Op0) {              // B^(B|A) == (A|B)^B
4484         Op1I->swapOperands();
4485         I.swapOperands();
4486         std::swap(Op0, Op1);
4487       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4488         I.swapOperands();     // Simplified below.
4489         std::swap(Op0, Op1);
4490       }
4491     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4492       if (Op0 == A)                                          // A^(A^B) == B
4493         return ReplaceInstUsesWith(I, B);
4494       else if (Op0 == B)                                     // A^(B^A) == B
4495         return ReplaceInstUsesWith(I, A);
4496     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4497       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4498         Op1I->swapOperands();
4499         std::swap(A, B);
4500       }
4501       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4502         I.swapOperands();     // Simplified below.
4503         std::swap(Op0, Op1);
4504       }
4505     }
4506   }
4507   
4508   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4509   if (Op0I) {
4510     Value *A, *B;
4511     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4512       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4513         std::swap(A, B);
4514       if (B == Op1) {                                // (A|B)^B == A & ~B
4515         Instruction *NotB =
4516           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4517         return BinaryOperator::CreateAnd(A, NotB);
4518       }
4519     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4520       if (Op1 == A)                                          // (A^B)^A == B
4521         return ReplaceInstUsesWith(I, B);
4522       else if (Op1 == B)                                     // (B^A)^A == B
4523         return ReplaceInstUsesWith(I, A);
4524     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4525       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4526         std::swap(A, B);
4527       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4528           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4529         Instruction *N =
4530           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4531         return BinaryOperator::CreateAnd(N, Op1);
4532       }
4533     }
4534   }
4535   
4536   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4537   if (Op0I && Op1I && Op0I->isShift() && 
4538       Op0I->getOpcode() == Op1I->getOpcode() && 
4539       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4540       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4541     Instruction *NewOp =
4542       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4543                                                     Op1I->getOperand(0),
4544                                                     Op0I->getName()), I);
4545     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4546                                   Op1I->getOperand(1));
4547   }
4548     
4549   if (Op0I && Op1I) {
4550     Value *A, *B, *C, *D;
4551     // (A & B)^(A | B) -> A ^ B
4552     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4553         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4554       if ((A == C && B == D) || (A == D && B == C)) 
4555         return BinaryOperator::CreateXor(A, B);
4556     }
4557     // (A | B)^(A & B) -> A ^ B
4558     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4559         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4560       if ((A == C && B == D) || (A == D && B == C)) 
4561         return BinaryOperator::CreateXor(A, B);
4562     }
4563     
4564     // (A & B)^(C & D)
4565     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4566         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4567         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4568       // (X & Y)^(X & Y) -> (Y^Z) & X
4569       Value *X = 0, *Y = 0, *Z = 0;
4570       if (A == C)
4571         X = A, Y = B, Z = D;
4572       else if (A == D)
4573         X = A, Y = B, Z = C;
4574       else if (B == C)
4575         X = B, Y = A, Z = D;
4576       else if (B == D)
4577         X = B, Y = A, Z = C;
4578       
4579       if (X) {
4580         Instruction *NewOp =
4581         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4582         return BinaryOperator::CreateAnd(NewOp, X);
4583       }
4584     }
4585   }
4586     
4587   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4588   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4589     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4590       return R;
4591
4592   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4593   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4594     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4595       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4596         const Type *SrcTy = Op0C->getOperand(0)->getType();
4597         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4598             // Only do this if the casts both really cause code to be generated.
4599             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4600                               I.getType(), TD) &&
4601             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4602                               I.getType(), TD)) {
4603           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4604                                                          Op1C->getOperand(0),
4605                                                          I.getName());
4606           InsertNewInstBefore(NewOp, I);
4607           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4608         }
4609       }
4610   }
4611
4612   return Changed ? &I : 0;
4613 }
4614
4615 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4616 /// overflowed for this type.
4617 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4618                             ConstantInt *In2, bool IsSigned = false) {
4619   Result = cast<ConstantInt>(Add(In1, In2));
4620
4621   if (IsSigned)
4622     if (In2->getValue().isNegative())
4623       return Result->getValue().sgt(In1->getValue());
4624     else
4625       return Result->getValue().slt(In1->getValue());
4626   else
4627     return Result->getValue().ult(In1->getValue());
4628 }
4629
4630 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4631 /// code necessary to compute the offset from the base pointer (without adding
4632 /// in the base pointer).  Return the result as a signed integer of intptr size.
4633 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4634   TargetData &TD = IC.getTargetData();
4635   gep_type_iterator GTI = gep_type_begin(GEP);
4636   const Type *IntPtrTy = TD.getIntPtrType();
4637   Value *Result = Constant::getNullValue(IntPtrTy);
4638
4639   // Build a mask for high order bits.
4640   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4641   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4642
4643   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4644        ++i, ++GTI) {
4645     Value *Op = *i;
4646     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4647     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4648       if (OpC->isZero()) continue;
4649       
4650       // Handle a struct index, which adds its field offset to the pointer.
4651       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4652         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4653         
4654         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4655           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4656         else
4657           Result = IC.InsertNewInstBefore(
4658                    BinaryOperator::CreateAdd(Result,
4659                                              ConstantInt::get(IntPtrTy, Size),
4660                                              GEP->getName()+".offs"), I);
4661         continue;
4662       }
4663       
4664       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4665       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4666       Scale = ConstantExpr::getMul(OC, Scale);
4667       if (Constant *RC = dyn_cast<Constant>(Result))
4668         Result = ConstantExpr::getAdd(RC, Scale);
4669       else {
4670         // Emit an add instruction.
4671         Result = IC.InsertNewInstBefore(
4672            BinaryOperator::CreateAdd(Result, Scale,
4673                                      GEP->getName()+".offs"), I);
4674       }
4675       continue;
4676     }
4677     // Convert to correct type.
4678     if (Op->getType() != IntPtrTy) {
4679       if (Constant *OpC = dyn_cast<Constant>(Op))
4680         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4681       else
4682         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4683                                                  Op->getName()+".c"), I);
4684     }
4685     if (Size != 1) {
4686       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4687       if (Constant *OpC = dyn_cast<Constant>(Op))
4688         Op = ConstantExpr::getMul(OpC, Scale);
4689       else    // We'll let instcombine(mul) convert this to a shl if possible.
4690         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4691                                                   GEP->getName()+".idx"), I);
4692     }
4693
4694     // Emit an add instruction.
4695     if (isa<Constant>(Op) && isa<Constant>(Result))
4696       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4697                                     cast<Constant>(Result));
4698     else
4699       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4700                                                   GEP->getName()+".offs"), I);
4701   }
4702   return Result;
4703 }
4704
4705
4706 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4707 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
4708 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
4709 /// complex, and scales are involved.  The above expression would also be legal
4710 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
4711 /// later form is less amenable to optimization though, and we are allowed to
4712 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4713 ///
4714 /// If we can't emit an optimized form for this expression, this returns null.
4715 /// 
4716 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4717                                           InstCombiner &IC) {
4718   TargetData &TD = IC.getTargetData();
4719   gep_type_iterator GTI = gep_type_begin(GEP);
4720
4721   // Check to see if this gep only has a single variable index.  If so, and if
4722   // any constant indices are a multiple of its scale, then we can compute this
4723   // in terms of the scale of the variable index.  For example, if the GEP
4724   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4725   // because the expression will cross zero at the same point.
4726   unsigned i, e = GEP->getNumOperands();
4727   int64_t Offset = 0;
4728   for (i = 1; i != e; ++i, ++GTI) {
4729     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4730       // Compute the aggregate offset of constant indices.
4731       if (CI->isZero()) continue;
4732
4733       // Handle a struct index, which adds its field offset to the pointer.
4734       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4735         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4736       } else {
4737         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4738         Offset += Size*CI->getSExtValue();
4739       }
4740     } else {
4741       // Found our variable index.
4742       break;
4743     }
4744   }
4745   
4746   // If there are no variable indices, we must have a constant offset, just
4747   // evaluate it the general way.
4748   if (i == e) return 0;
4749   
4750   Value *VariableIdx = GEP->getOperand(i);
4751   // Determine the scale factor of the variable element.  For example, this is
4752   // 4 if the variable index is into an array of i32.
4753   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4754   
4755   // Verify that there are no other variable indices.  If so, emit the hard way.
4756   for (++i, ++GTI; i != e; ++i, ++GTI) {
4757     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4758     if (!CI) return 0;
4759    
4760     // Compute the aggregate offset of constant indices.
4761     if (CI->isZero()) continue;
4762     
4763     // Handle a struct index, which adds its field offset to the pointer.
4764     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4765       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4766     } else {
4767       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4768       Offset += Size*CI->getSExtValue();
4769     }
4770   }
4771   
4772   // Okay, we know we have a single variable index, which must be a
4773   // pointer/array/vector index.  If there is no offset, life is simple, return
4774   // the index.
4775   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4776   if (Offset == 0) {
4777     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
4778     // we don't need to bother extending: the extension won't affect where the
4779     // computation crosses zero.
4780     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4781       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4782                                   VariableIdx->getNameStart(), &I);
4783     return VariableIdx;
4784   }
4785   
4786   // Otherwise, there is an index.  The computation we will do will be modulo
4787   // the pointer size, so get it.
4788   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4789   
4790   Offset &= PtrSizeMask;
4791   VariableScale &= PtrSizeMask;
4792
4793   // To do this transformation, any constant index must be a multiple of the
4794   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
4795   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
4796   // multiple of the variable scale.
4797   int64_t NewOffs = Offset / (int64_t)VariableScale;
4798   if (Offset != NewOffs*(int64_t)VariableScale)
4799     return 0;
4800
4801   // Okay, we can do this evaluation.  Start by converting the index to intptr.
4802   const Type *IntPtrTy = TD.getIntPtrType();
4803   if (VariableIdx->getType() != IntPtrTy)
4804     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4805                                               true /*SExt*/, 
4806                                               VariableIdx->getNameStart(), &I);
4807   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4808   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4809 }
4810
4811
4812 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4813 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4814 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4815                                        ICmpInst::Predicate Cond,
4816                                        Instruction &I) {
4817   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4818
4819   // Look through bitcasts.
4820   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4821     RHS = BCI->getOperand(0);
4822
4823   Value *PtrBase = GEPLHS->getOperand(0);
4824   if (PtrBase == RHS) {
4825     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4826     // This transformation (ignoring the base and scales) is valid because we
4827     // know pointers can't overflow.  See if we can output an optimized form.
4828     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4829     
4830     // If not, synthesize the offset the hard way.
4831     if (Offset == 0)
4832       Offset = EmitGEPOffset(GEPLHS, I, *this);
4833     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4834                         Constant::getNullValue(Offset->getType()));
4835   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4836     // If the base pointers are different, but the indices are the same, just
4837     // compare the base pointer.
4838     if (PtrBase != GEPRHS->getOperand(0)) {
4839       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4840       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4841                         GEPRHS->getOperand(0)->getType();
4842       if (IndicesTheSame)
4843         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4844           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4845             IndicesTheSame = false;
4846             break;
4847           }
4848
4849       // If all indices are the same, just compare the base pointers.
4850       if (IndicesTheSame)
4851         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4852                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4853
4854       // Otherwise, the base pointers are different and the indices are
4855       // different, bail out.
4856       return 0;
4857     }
4858
4859     // If one of the GEPs has all zero indices, recurse.
4860     bool AllZeros = true;
4861     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4862       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4863           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4864         AllZeros = false;
4865         break;
4866       }
4867     if (AllZeros)
4868       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4869                           ICmpInst::getSwappedPredicate(Cond), I);
4870
4871     // If the other GEP has all zero indices, recurse.
4872     AllZeros = true;
4873     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4874       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4875           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4876         AllZeros = false;
4877         break;
4878       }
4879     if (AllZeros)
4880       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4881
4882     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4883       // If the GEPs only differ by one index, compare it.
4884       unsigned NumDifferences = 0;  // Keep track of # differences.
4885       unsigned DiffOperand = 0;     // The operand that differs.
4886       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4887         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4888           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4889                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4890             // Irreconcilable differences.
4891             NumDifferences = 2;
4892             break;
4893           } else {
4894             if (NumDifferences++) break;
4895             DiffOperand = i;
4896           }
4897         }
4898
4899       if (NumDifferences == 0)   // SAME GEP?
4900         return ReplaceInstUsesWith(I, // No comparison is needed here.
4901                                    ConstantInt::get(Type::Int1Ty,
4902                                              ICmpInst::isTrueWhenEqual(Cond)));
4903
4904       else if (NumDifferences == 1) {
4905         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4906         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4907         // Make sure we do a signed comparison here.
4908         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4909       }
4910     }
4911
4912     // Only lower this if the icmp is the only user of the GEP or if we expect
4913     // the result to fold to a constant!
4914     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4915         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4916       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4917       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4918       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4919       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4920     }
4921   }
4922   return 0;
4923 }
4924
4925 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4926 ///
4927 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4928                                                 Instruction *LHSI,
4929                                                 Constant *RHSC) {
4930   if (!isa<ConstantFP>(RHSC)) return 0;
4931   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4932   
4933   // Get the width of the mantissa.  We don't want to hack on conversions that
4934   // might lose information from the integer, e.g. "i64 -> float"
4935   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4936   if (MantissaWidth == -1) return 0;  // Unknown.
4937   
4938   // Check to see that the input is converted from an integer type that is small
4939   // enough that preserves all bits.  TODO: check here for "known" sign bits.
4940   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4941   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4942   
4943   // If this is a uitofp instruction, we need an extra bit to hold the sign.
4944   if (isa<UIToFPInst>(LHSI))
4945     ++InputSize;
4946   
4947   // If the conversion would lose info, don't hack on this.
4948   if ((int)InputSize > MantissaWidth)
4949     return 0;
4950   
4951   // Otherwise, we can potentially simplify the comparison.  We know that it
4952   // will always come through as an integer value and we know the constant is
4953   // not a NAN (it would have been previously simplified).
4954   assert(!RHS.isNaN() && "NaN comparison not already folded!");
4955   
4956   ICmpInst::Predicate Pred;
4957   switch (I.getPredicate()) {
4958   default: assert(0 && "Unexpected predicate!");
4959   case FCmpInst::FCMP_UEQ:
4960   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4961   case FCmpInst::FCMP_UGT:
4962   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4963   case FCmpInst::FCMP_UGE:
4964   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4965   case FCmpInst::FCMP_ULT:
4966   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4967   case FCmpInst::FCMP_ULE:
4968   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4969   case FCmpInst::FCMP_UNE:
4970   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4971   case FCmpInst::FCMP_ORD:
4972     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4973   case FCmpInst::FCMP_UNO:
4974     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4975   }
4976   
4977   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4978   
4979   // Now we know that the APFloat is a normal number, zero or inf.
4980   
4981   // See if the FP constant is too large for the integer.  For example,
4982   // comparing an i8 to 300.0.
4983   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4984   
4985   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
4986   // and large values. 
4987   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4988   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4989                         APFloat::rmNearestTiesToEven);
4990   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
4991     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4992         Pred == ICmpInst::ICMP_SLE)
4993       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4994     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4995   }
4996   
4997   // See if the RHS value is < SignedMin.
4998   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4999   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5000                         APFloat::rmNearestTiesToEven);
5001   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5002     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5003         Pred == ICmpInst::ICMP_SGE)
5004       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5005     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5006   }
5007
5008   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5009   // it may still be fractional.  See if it is fractional by casting the FP
5010   // value to the integer value and back, checking for equality.  Don't do this
5011   // for zero, because -0.0 is not fractional.
5012   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5013   if (!RHS.isZero() &&
5014       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5015     // If we had a comparison against a fractional value, we have to adjust
5016     // the compare predicate and sometimes the value.  RHSC is rounded towards
5017     // zero at this point.
5018     switch (Pred) {
5019     default: assert(0 && "Unexpected integer comparison!");
5020     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5021       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5022     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5023       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5024     case ICmpInst::ICMP_SLE:
5025       // (float)int <= 4.4   --> int <= 4
5026       // (float)int <= -4.4  --> int < -4
5027       if (RHS.isNegative())
5028         Pred = ICmpInst::ICMP_SLT;
5029       break;
5030     case ICmpInst::ICMP_SLT:
5031       // (float)int < -4.4   --> int < -4
5032       // (float)int < 4.4    --> int <= 4
5033       if (!RHS.isNegative())
5034         Pred = ICmpInst::ICMP_SLE;
5035       break;
5036     case ICmpInst::ICMP_SGT:
5037       // (float)int > 4.4    --> int > 4
5038       // (float)int > -4.4   --> int >= -4
5039       if (RHS.isNegative())
5040         Pred = ICmpInst::ICMP_SGE;
5041       break;
5042     case ICmpInst::ICMP_SGE:
5043       // (float)int >= -4.4   --> int >= -4
5044       // (float)int >= 4.4    --> int > 4
5045       if (!RHS.isNegative())
5046         Pred = ICmpInst::ICMP_SGT;
5047       break;
5048     }
5049   }
5050
5051   // Lower this FP comparison into an appropriate integer version of the
5052   // comparison.
5053   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5054 }
5055
5056 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5057   bool Changed = SimplifyCompare(I);
5058   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5059
5060   // Fold trivial predicates.
5061   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5062     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5063   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5064     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5065   
5066   // Simplify 'fcmp pred X, X'
5067   if (Op0 == Op1) {
5068     switch (I.getPredicate()) {
5069     default: assert(0 && "Unknown predicate!");
5070     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5071     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5072     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5073       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5074     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5075     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5076     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5077       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5078       
5079     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5080     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5081     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5082     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5083       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5084       I.setPredicate(FCmpInst::FCMP_UNO);
5085       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5086       return &I;
5087       
5088     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5089     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5090     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5091     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5092       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5093       I.setPredicate(FCmpInst::FCMP_ORD);
5094       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5095       return &I;
5096     }
5097   }
5098     
5099   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5100     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5101
5102   // Handle fcmp with constant RHS
5103   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5104     // If the constant is a nan, see if we can fold the comparison based on it.
5105     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5106       if (CFP->getValueAPF().isNaN()) {
5107         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5108           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5109         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5110                "Comparison must be either ordered or unordered!");
5111         // True if unordered.
5112         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5113       }
5114     }
5115     
5116     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5117       switch (LHSI->getOpcode()) {
5118       case Instruction::PHI:
5119         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5120         // block.  If in the same block, we're encouraging jump threading.  If
5121         // not, we are just pessimizing the code by making an i1 phi.
5122         if (LHSI->getParent() == I.getParent())
5123           if (Instruction *NV = FoldOpIntoPhi(I))
5124             return NV;
5125         break;
5126       case Instruction::SIToFP:
5127       case Instruction::UIToFP:
5128         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5129           return NV;
5130         break;
5131       case Instruction::Select:
5132         // If either operand of the select is a constant, we can fold the
5133         // comparison into the select arms, which will cause one to be
5134         // constant folded and the select turned into a bitwise or.
5135         Value *Op1 = 0, *Op2 = 0;
5136         if (LHSI->hasOneUse()) {
5137           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5138             // Fold the known value into the constant operand.
5139             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5140             // Insert a new FCmp of the other select operand.
5141             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5142                                                       LHSI->getOperand(2), RHSC,
5143                                                       I.getName()), I);
5144           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5145             // Fold the known value into the constant operand.
5146             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5147             // Insert a new FCmp of the other select operand.
5148             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5149                                                       LHSI->getOperand(1), RHSC,
5150                                                       I.getName()), I);
5151           }
5152         }
5153
5154         if (Op1)
5155           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5156         break;
5157       }
5158   }
5159
5160   return Changed ? &I : 0;
5161 }
5162
5163 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5164   bool Changed = SimplifyCompare(I);
5165   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5166   const Type *Ty = Op0->getType();
5167
5168   // icmp X, X
5169   if (Op0 == Op1)
5170     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5171                                                    I.isTrueWhenEqual()));
5172
5173   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5174     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5175   
5176   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5177   // addresses never equal each other!  We already know that Op0 != Op1.
5178   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5179        isa<ConstantPointerNull>(Op0)) &&
5180       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5181        isa<ConstantPointerNull>(Op1)))
5182     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5183                                                    !I.isTrueWhenEqual()));
5184
5185   // icmp's with boolean values can always be turned into bitwise operations
5186   if (Ty == Type::Int1Ty) {
5187     switch (I.getPredicate()) {
5188     default: assert(0 && "Invalid icmp instruction!");
5189     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5190       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5191       InsertNewInstBefore(Xor, I);
5192       return BinaryOperator::CreateNot(Xor);
5193     }
5194     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5195       return BinaryOperator::CreateXor(Op0, Op1);
5196
5197     case ICmpInst::ICMP_UGT:
5198       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5199       // FALL THROUGH
5200     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5201       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5202       InsertNewInstBefore(Not, I);
5203       return BinaryOperator::CreateAnd(Not, Op1);
5204     }
5205     case ICmpInst::ICMP_SGT:
5206       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5207       // FALL THROUGH
5208     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5209       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5210       InsertNewInstBefore(Not, I);
5211       return BinaryOperator::CreateAnd(Not, Op0);
5212     }
5213     case ICmpInst::ICMP_UGE:
5214       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5215       // FALL THROUGH
5216     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5217       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5218       InsertNewInstBefore(Not, I);
5219       return BinaryOperator::CreateOr(Not, Op1);
5220     }
5221     case ICmpInst::ICMP_SGE:
5222       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5223       // FALL THROUGH
5224     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5225       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5226       InsertNewInstBefore(Not, I);
5227       return BinaryOperator::CreateOr(Not, Op0);
5228     }
5229     }
5230   }
5231
5232   // See if we are doing a comparison between a constant and an instruction that
5233   // can be folded into the comparison.
5234   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5235     Value *A, *B;
5236     
5237     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5238     if (I.isEquality() && CI->isNullValue() &&
5239         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5240       // (icmp cond A B) if cond is equality
5241       return new ICmpInst(I.getPredicate(), A, B);
5242     }
5243     
5244     // If we have a icmp le or icmp ge instruction, turn it into the appropriate
5245     // icmp lt or icmp gt instruction.  This allows us to rely on them being
5246     // folded in the code below.
5247     switch (I.getPredicate()) {
5248     default: break;
5249     case ICmpInst::ICMP_ULE:
5250       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5251         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5252       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5253     case ICmpInst::ICMP_SLE:
5254       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5255         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5256       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5257     case ICmpInst::ICMP_UGE:
5258       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5259         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5260       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5261     case ICmpInst::ICMP_SGE:
5262       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5263         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5264       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5265     }
5266     
5267     // See if we can fold the comparison based on range information we can get
5268     // by checking whether bits are known to be zero or one in the input.
5269     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5270     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5271     
5272     // If this comparison is a normal comparison, it demands all
5273     // bits, if it is a sign bit comparison, it only demands the sign bit.
5274     bool UnusedBit;
5275     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5276     
5277     if (SimplifyDemandedBits(Op0, 
5278                              isSignBit ? APInt::getSignBit(BitWidth)
5279                                        : APInt::getAllOnesValue(BitWidth),
5280                              KnownZero, KnownOne, 0))
5281       return &I;
5282         
5283     // Given the known and unknown bits, compute a range that the LHS could be
5284     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5285     // EQ and NE we use unsigned values.
5286     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5287     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5288       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5289     else
5290       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5291     
5292     // If Min and Max are known to be the same, then SimplifyDemandedBits
5293     // figured out that the LHS is a constant.  Just constant fold this now so
5294     // that code below can assume that Min != Max.
5295     if (Min == Max)
5296       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5297                                                           ConstantInt::get(Min),
5298                                                           CI));
5299     
5300     // Based on the range information we know about the LHS, see if we can
5301     // simplify this comparison.  For example, (x&4) < 8  is always true.
5302     const APInt &RHSVal = CI->getValue();
5303     switch (I.getPredicate()) {  // LE/GE have been folded already.
5304     default: assert(0 && "Unknown icmp opcode!");
5305     case ICmpInst::ICMP_EQ:
5306       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5307         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5308       break;
5309     case ICmpInst::ICMP_NE:
5310       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5311         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5312       break;
5313     case ICmpInst::ICMP_ULT:
5314       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5315         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5316       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5317         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5318       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5319         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5320       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5321         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5322         
5323       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5324       if (CI->isMinValue(true))
5325         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5326                             ConstantInt::getAllOnesValue(Op0->getType()));
5327       break;
5328     case ICmpInst::ICMP_UGT:
5329       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5330         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5331       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5332         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5333         
5334       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5335         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5336       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5337         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5338       
5339       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5340       if (CI->isMaxValue(true))
5341         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5342                             ConstantInt::getNullValue(Op0->getType()));
5343       break;
5344     case ICmpInst::ICMP_SLT:
5345       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5346         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5347       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5348         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5349       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5350         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5351       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5352         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5353       break;
5354     case ICmpInst::ICMP_SGT: 
5355       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5356         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5357       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5358         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5359         
5360       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5361         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5362       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5363         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5364       break;
5365     }
5366           
5367     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5368     // instruction, see if that instruction also has constants so that the 
5369     // instruction can be folded into the icmp 
5370     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5371       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5372         return Res;
5373   }
5374
5375   // Handle icmp with constant (but not simple integer constant) RHS
5376   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5377     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5378       switch (LHSI->getOpcode()) {
5379       case Instruction::GetElementPtr:
5380         if (RHSC->isNullValue()) {
5381           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5382           bool isAllZeros = true;
5383           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5384             if (!isa<Constant>(LHSI->getOperand(i)) ||
5385                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5386               isAllZeros = false;
5387               break;
5388             }
5389           if (isAllZeros)
5390             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5391                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5392         }
5393         break;
5394
5395       case Instruction::PHI:
5396         // Only fold icmp into the PHI if the phi and fcmp are in the same
5397         // block.  If in the same block, we're encouraging jump threading.  If
5398         // not, we are just pessimizing the code by making an i1 phi.
5399         if (LHSI->getParent() == I.getParent())
5400           if (Instruction *NV = FoldOpIntoPhi(I))
5401             return NV;
5402         break;
5403       case Instruction::Select: {
5404         // If either operand of the select is a constant, we can fold the
5405         // comparison into the select arms, which will cause one to be
5406         // constant folded and the select turned into a bitwise or.
5407         Value *Op1 = 0, *Op2 = 0;
5408         if (LHSI->hasOneUse()) {
5409           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5410             // Fold the known value into the constant operand.
5411             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5412             // Insert a new ICmp of the other select operand.
5413             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5414                                                    LHSI->getOperand(2), RHSC,
5415                                                    I.getName()), I);
5416           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5417             // Fold the known value into the constant operand.
5418             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5419             // Insert a new ICmp of the other select operand.
5420             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5421                                                    LHSI->getOperand(1), RHSC,
5422                                                    I.getName()), I);
5423           }
5424         }
5425
5426         if (Op1)
5427           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5428         break;
5429       }
5430       case Instruction::Malloc:
5431         // If we have (malloc != null), and if the malloc has a single use, we
5432         // can assume it is successful and remove the malloc.
5433         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5434           AddToWorkList(LHSI);
5435           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5436                                                          !I.isTrueWhenEqual()));
5437         }
5438         break;
5439       }
5440   }
5441
5442   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5443   if (User *GEP = dyn_castGetElementPtr(Op0))
5444     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5445       return NI;
5446   if (User *GEP = dyn_castGetElementPtr(Op1))
5447     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5448                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5449       return NI;
5450
5451   // Test to see if the operands of the icmp are casted versions of other
5452   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5453   // now.
5454   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5455     if (isa<PointerType>(Op0->getType()) && 
5456         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5457       // We keep moving the cast from the left operand over to the right
5458       // operand, where it can often be eliminated completely.
5459       Op0 = CI->getOperand(0);
5460
5461       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5462       // so eliminate it as well.
5463       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5464         Op1 = CI2->getOperand(0);
5465
5466       // If Op1 is a constant, we can fold the cast into the constant.
5467       if (Op0->getType() != Op1->getType()) {
5468         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5469           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5470         } else {
5471           // Otherwise, cast the RHS right before the icmp
5472           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5473         }
5474       }
5475       return new ICmpInst(I.getPredicate(), Op0, Op1);
5476     }
5477   }
5478   
5479   if (isa<CastInst>(Op0)) {
5480     // Handle the special case of: icmp (cast bool to X), <cst>
5481     // This comes up when you have code like
5482     //   int X = A < B;
5483     //   if (X) ...
5484     // For generality, we handle any zero-extension of any operand comparison
5485     // with a constant or another cast from the same type.
5486     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5487       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5488         return R;
5489   }
5490   
5491   // See if it's the same type of instruction on the left and right.
5492   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5493     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
5494       if (Op0I->getOpcode() == Op1I->getOpcode() &&
5495           Op0I->getOperand(1) == Op1I->getOperand(1)) {
5496         switch (Op0I->getOpcode()) {
5497         default: break;
5498         case Instruction::Add:
5499         case Instruction::Sub:
5500         case Instruction::Xor:
5501           if (I.isEquality()) {
5502             // icmp eq/ne a+x, b+x --> icmp eq/ne a, b
5503             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5504                                 Op1I->getOperand(0));
5505           } else {
5506             // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
5507             if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5508               if (CI->getValue().isSignBit()) {
5509                 ICmpInst::Predicate Pred = I.isSignedPredicate()
5510                                                ? I.getUnsignedPredicate()
5511                                                : I.getSignedPredicate();
5512                 return new ICmpInst(Pred, Op0I->getOperand(0),
5513                                     Op1I->getOperand(0));
5514               }
5515             }
5516           }
5517           break;
5518         case Instruction::Mul:
5519           // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5520           // Mask = -1 >> count-trailing-zeros(Cst).
5521           if (Op0I->hasOneUse() && Op1I->hasOneUse() && I.isEquality()) {
5522             if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5523               if (!CI->isZero() && !CI->isOne()) {
5524                 const APInt &AP = CI->getValue();
5525                 ConstantInt *Mask =
5526                     ConstantInt::get(APInt::getLowBitsSet(AP.getBitWidth(),
5527                                                           AP.getBitWidth() -
5528                                                       AP.countTrailingZeros()));
5529                 Instruction *And1 =
5530                     BinaryOperator::CreateAnd(Op0I->getOperand(0), Mask);
5531                 Instruction *And2 =
5532                     BinaryOperator::CreateAnd(Op1I->getOperand(0), Mask);
5533                 InsertNewInstBefore(And1, I);
5534                 InsertNewInstBefore(And2, I);
5535                 return new ICmpInst(I.getPredicate(), And1, And2);
5536               }
5537             }
5538           }
5539           break;
5540         }
5541       }
5542     }
5543   }
5544   
5545   // ~x < ~y --> y < x
5546   { Value *A, *B;
5547     if (match(Op0, m_Not(m_Value(A))) &&
5548         match(Op1, m_Not(m_Value(B))))
5549       return new ICmpInst(I.getPredicate(), B, A);
5550   }
5551   
5552   if (I.isEquality()) {
5553     Value *A, *B, *C, *D;
5554     
5555     // -x == -y --> x == y
5556     if (match(Op0, m_Neg(m_Value(A))) &&
5557         match(Op1, m_Neg(m_Value(B))))
5558       return new ICmpInst(I.getPredicate(), A, B);
5559     
5560     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5561       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5562         Value *OtherVal = A == Op1 ? B : A;
5563         return new ICmpInst(I.getPredicate(), OtherVal,
5564                             Constant::getNullValue(A->getType()));
5565       }
5566
5567       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5568         // A^c1 == C^c2 --> A == C^(c1^c2)
5569         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5570           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5571             if (Op1->hasOneUse()) {
5572               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5573               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5574               return new ICmpInst(I.getPredicate(), A,
5575                                   InsertNewInstBefore(Xor, I));
5576             }
5577         
5578         // A^B == A^D -> B == D
5579         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5580         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5581         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5582         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5583       }
5584     }
5585     
5586     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5587         (A == Op0 || B == Op0)) {
5588       // A == (A^B)  ->  B == 0
5589       Value *OtherVal = A == Op0 ? B : A;
5590       return new ICmpInst(I.getPredicate(), OtherVal,
5591                           Constant::getNullValue(A->getType()));
5592     }
5593     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5594       // (A-B) == A  ->  B == 0
5595       return new ICmpInst(I.getPredicate(), B,
5596                           Constant::getNullValue(B->getType()));
5597     }
5598     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5599       // A == (A-B)  ->  B == 0
5600       return new ICmpInst(I.getPredicate(), B,
5601                           Constant::getNullValue(B->getType()));
5602     }
5603     
5604     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5605     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5606         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5607         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5608       Value *X = 0, *Y = 0, *Z = 0;
5609       
5610       if (A == C) {
5611         X = B; Y = D; Z = A;
5612       } else if (A == D) {
5613         X = B; Y = C; Z = A;
5614       } else if (B == C) {
5615         X = A; Y = D; Z = B;
5616       } else if (B == D) {
5617         X = A; Y = C; Z = B;
5618       }
5619       
5620       if (X) {   // Build (X^Y) & Z
5621         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5622         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5623         I.setOperand(0, Op1);
5624         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5625         return &I;
5626       }
5627     }
5628   }
5629   return Changed ? &I : 0;
5630 }
5631
5632
5633 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5634 /// and CmpRHS are both known to be integer constants.
5635 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5636                                           ConstantInt *DivRHS) {
5637   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5638   const APInt &CmpRHSV = CmpRHS->getValue();
5639   
5640   // FIXME: If the operand types don't match the type of the divide 
5641   // then don't attempt this transform. The code below doesn't have the
5642   // logic to deal with a signed divide and an unsigned compare (and
5643   // vice versa). This is because (x /s C1) <s C2  produces different 
5644   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5645   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5646   // work. :(  The if statement below tests that condition and bails 
5647   // if it finds it. 
5648   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5649   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5650     return 0;
5651   if (DivRHS->isZero())
5652     return 0; // The ProdOV computation fails on divide by zero.
5653
5654   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5655   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5656   // C2 (CI). By solving for X we can turn this into a range check 
5657   // instead of computing a divide. 
5658   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5659
5660   // Determine if the product overflows by seeing if the product is
5661   // not equal to the divide. Make sure we do the same kind of divide
5662   // as in the LHS instruction that we're folding. 
5663   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5664                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5665
5666   // Get the ICmp opcode
5667   ICmpInst::Predicate Pred = ICI.getPredicate();
5668
5669   // Figure out the interval that is being checked.  For example, a comparison
5670   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5671   // Compute this interval based on the constants involved and the signedness of
5672   // the compare/divide.  This computes a half-open interval, keeping track of
5673   // whether either value in the interval overflows.  After analysis each
5674   // overflow variable is set to 0 if it's corresponding bound variable is valid
5675   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5676   int LoOverflow = 0, HiOverflow = 0;
5677   ConstantInt *LoBound = 0, *HiBound = 0;
5678   
5679   
5680   if (!DivIsSigned) {  // udiv
5681     // e.g. X/5 op 3  --> [15, 20)
5682     LoBound = Prod;
5683     HiOverflow = LoOverflow = ProdOV;
5684     if (!HiOverflow)
5685       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5686   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5687     if (CmpRHSV == 0) {       // (X / pos) op 0
5688       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5689       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5690       HiBound = DivRHS;
5691     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5692       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5693       HiOverflow = LoOverflow = ProdOV;
5694       if (!HiOverflow)
5695         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5696     } else {                       // (X / pos) op neg
5697       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5698       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5699       LoOverflow = AddWithOverflow(LoBound, Prod,
5700                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5701       HiBound = AddOne(Prod);
5702       HiOverflow = ProdOV ? -1 : 0;
5703     }
5704   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5705     if (CmpRHSV == 0) {       // (X / neg) op 0
5706       // e.g. X/-5 op 0  --> [-4, 5)
5707       LoBound = AddOne(DivRHS);
5708       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5709       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5710         HiOverflow = 1;            // [INTMIN+1, overflow)
5711         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5712       }
5713     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5714       // e.g. X/-5 op 3  --> [-19, -14)
5715       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5716       if (!LoOverflow)
5717         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5718       HiBound = AddOne(Prod);
5719     } else {                       // (X / neg) op neg
5720       // e.g. X/-5 op -3  --> [15, 20)
5721       LoBound = Prod;
5722       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5723       HiBound = Subtract(Prod, DivRHS);
5724     }
5725     
5726     // Dividing by a negative swaps the condition.  LT <-> GT
5727     Pred = ICmpInst::getSwappedPredicate(Pred);
5728   }
5729
5730   Value *X = DivI->getOperand(0);
5731   switch (Pred) {
5732   default: assert(0 && "Unhandled icmp opcode!");
5733   case ICmpInst::ICMP_EQ:
5734     if (LoOverflow && HiOverflow)
5735       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5736     else if (HiOverflow)
5737       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5738                           ICmpInst::ICMP_UGE, X, LoBound);
5739     else if (LoOverflow)
5740       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5741                           ICmpInst::ICMP_ULT, X, HiBound);
5742     else
5743       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5744   case ICmpInst::ICMP_NE:
5745     if (LoOverflow && HiOverflow)
5746       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5747     else if (HiOverflow)
5748       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5749                           ICmpInst::ICMP_ULT, X, LoBound);
5750     else if (LoOverflow)
5751       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5752                           ICmpInst::ICMP_UGE, X, HiBound);
5753     else
5754       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5755   case ICmpInst::ICMP_ULT:
5756   case ICmpInst::ICMP_SLT:
5757     if (LoOverflow == +1)   // Low bound is greater than input range.
5758       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5759     if (LoOverflow == -1)   // Low bound is less than input range.
5760       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5761     return new ICmpInst(Pred, X, LoBound);
5762   case ICmpInst::ICMP_UGT:
5763   case ICmpInst::ICMP_SGT:
5764     if (HiOverflow == +1)       // High bound greater than input range.
5765       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5766     else if (HiOverflow == -1)  // High bound less than input range.
5767       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5768     if (Pred == ICmpInst::ICMP_UGT)
5769       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5770     else
5771       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5772   }
5773 }
5774
5775
5776 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5777 ///
5778 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5779                                                           Instruction *LHSI,
5780                                                           ConstantInt *RHS) {
5781   const APInt &RHSV = RHS->getValue();
5782   
5783   switch (LHSI->getOpcode()) {
5784   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5785     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5786       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5787       // fold the xor.
5788       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5789           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5790         Value *CompareVal = LHSI->getOperand(0);
5791         
5792         // If the sign bit of the XorCST is not set, there is no change to
5793         // the operation, just stop using the Xor.
5794         if (!XorCST->getValue().isNegative()) {
5795           ICI.setOperand(0, CompareVal);
5796           AddToWorkList(LHSI);
5797           return &ICI;
5798         }
5799         
5800         // Was the old condition true if the operand is positive?
5801         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5802         
5803         // If so, the new one isn't.
5804         isTrueIfPositive ^= true;
5805         
5806         if (isTrueIfPositive)
5807           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5808         else
5809           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5810       }
5811
5812       // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
5813       if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
5814         const APInt &SignBit = XorCST->getValue();
5815         ICmpInst::Predicate Pred = ICI.isSignedPredicate()
5816                                        ? ICI.getUnsignedPredicate()
5817                                        : ICI.getSignedPredicate();
5818         return new ICmpInst(Pred, LHSI->getOperand(0),
5819                             ConstantInt::get(RHSV ^ SignBit));
5820       }
5821     }
5822     break;
5823   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5824     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5825         LHSI->getOperand(0)->hasOneUse()) {
5826       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5827       
5828       // If the LHS is an AND of a truncating cast, we can widen the
5829       // and/compare to be the input width without changing the value
5830       // produced, eliminating a cast.
5831       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5832         // We can do this transformation if either the AND constant does not
5833         // have its sign bit set or if it is an equality comparison. 
5834         // Extending a relational comparison when we're checking the sign
5835         // bit would not work.
5836         if (Cast->hasOneUse() &&
5837             (ICI.isEquality() ||
5838              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5839           uint32_t BitWidth = 
5840             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5841           APInt NewCST = AndCST->getValue();
5842           NewCST.zext(BitWidth);
5843           APInt NewCI = RHSV;
5844           NewCI.zext(BitWidth);
5845           Instruction *NewAnd = 
5846             BinaryOperator::CreateAnd(Cast->getOperand(0),
5847                                       ConstantInt::get(NewCST),LHSI->getName());
5848           InsertNewInstBefore(NewAnd, ICI);
5849           return new ICmpInst(ICI.getPredicate(), NewAnd,
5850                               ConstantInt::get(NewCI));
5851         }
5852       }
5853       
5854       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5855       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5856       // happens a LOT in code produced by the C front-end, for bitfield
5857       // access.
5858       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5859       if (Shift && !Shift->isShift())
5860         Shift = 0;
5861       
5862       ConstantInt *ShAmt;
5863       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5864       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5865       const Type *AndTy = AndCST->getType();          // Type of the and.
5866       
5867       // We can fold this as long as we can't shift unknown bits
5868       // into the mask.  This can only happen with signed shift
5869       // rights, as they sign-extend.
5870       if (ShAmt) {
5871         bool CanFold = Shift->isLogicalShift();
5872         if (!CanFold) {
5873           // To test for the bad case of the signed shr, see if any
5874           // of the bits shifted in could be tested after the mask.
5875           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5876           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5877           
5878           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5879           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5880                AndCST->getValue()) == 0)
5881             CanFold = true;
5882         }
5883         
5884         if (CanFold) {
5885           Constant *NewCst;
5886           if (Shift->getOpcode() == Instruction::Shl)
5887             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5888           else
5889             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5890           
5891           // Check to see if we are shifting out any of the bits being
5892           // compared.
5893           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5894             // If we shifted bits out, the fold is not going to work out.
5895             // As a special case, check to see if this means that the
5896             // result is always true or false now.
5897             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5898               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5899             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5900               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5901           } else {
5902             ICI.setOperand(1, NewCst);
5903             Constant *NewAndCST;
5904             if (Shift->getOpcode() == Instruction::Shl)
5905               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5906             else
5907               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5908             LHSI->setOperand(1, NewAndCST);
5909             LHSI->setOperand(0, Shift->getOperand(0));
5910             AddToWorkList(Shift); // Shift is dead.
5911             AddUsesToWorkList(ICI);
5912             return &ICI;
5913           }
5914         }
5915       }
5916       
5917       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5918       // preferable because it allows the C<<Y expression to be hoisted out
5919       // of a loop if Y is invariant and X is not.
5920       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5921           ICI.isEquality() && !Shift->isArithmeticShift() &&
5922           isa<Instruction>(Shift->getOperand(0))) {
5923         // Compute C << Y.
5924         Value *NS;
5925         if (Shift->getOpcode() == Instruction::LShr) {
5926           NS = BinaryOperator::CreateShl(AndCST, 
5927                                          Shift->getOperand(1), "tmp");
5928         } else {
5929           // Insert a logical shift.
5930           NS = BinaryOperator::CreateLShr(AndCST,
5931                                           Shift->getOperand(1), "tmp");
5932         }
5933         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5934         
5935         // Compute X & (C << Y).
5936         Instruction *NewAnd = 
5937           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5938         InsertNewInstBefore(NewAnd, ICI);
5939         
5940         ICI.setOperand(0, NewAnd);
5941         return &ICI;
5942       }
5943     }
5944     break;
5945     
5946   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5947     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5948     if (!ShAmt) break;
5949     
5950     uint32_t TypeBits = RHSV.getBitWidth();
5951     
5952     // Check that the shift amount is in range.  If not, don't perform
5953     // undefined shifts.  When the shift is visited it will be
5954     // simplified.
5955     if (ShAmt->uge(TypeBits))
5956       break;
5957     
5958     if (ICI.isEquality()) {
5959       // If we are comparing against bits always shifted out, the
5960       // comparison cannot succeed.
5961       Constant *Comp =
5962         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5963       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5964         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5965         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5966         return ReplaceInstUsesWith(ICI, Cst);
5967       }
5968       
5969       if (LHSI->hasOneUse()) {
5970         // Otherwise strength reduce the shift into an and.
5971         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5972         Constant *Mask =
5973           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5974         
5975         Instruction *AndI =
5976           BinaryOperator::CreateAnd(LHSI->getOperand(0),
5977                                     Mask, LHSI->getName()+".mask");
5978         Value *And = InsertNewInstBefore(AndI, ICI);
5979         return new ICmpInst(ICI.getPredicate(), And,
5980                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5981       }
5982     }
5983     
5984     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5985     bool TrueIfSigned = false;
5986     if (LHSI->hasOneUse() &&
5987         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5988       // (X << 31) <s 0  --> (X&1) != 0
5989       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5990                                            (TypeBits-ShAmt->getZExtValue()-1));
5991       Instruction *AndI =
5992         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5993                                   Mask, LHSI->getName()+".mask");
5994       Value *And = InsertNewInstBefore(AndI, ICI);
5995       
5996       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5997                           And, Constant::getNullValue(And->getType()));
5998     }
5999     break;
6000   }
6001     
6002   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6003   case Instruction::AShr: {
6004     // Only handle equality comparisons of shift-by-constant.
6005     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6006     if (!ShAmt || !ICI.isEquality()) break;
6007
6008     // Check that the shift amount is in range.  If not, don't perform
6009     // undefined shifts.  When the shift is visited it will be
6010     // simplified.
6011     uint32_t TypeBits = RHSV.getBitWidth();
6012     if (ShAmt->uge(TypeBits))
6013       break;
6014     
6015     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6016       
6017     // If we are comparing against bits always shifted out, the
6018     // comparison cannot succeed.
6019     APInt Comp = RHSV << ShAmtVal;
6020     if (LHSI->getOpcode() == Instruction::LShr)
6021       Comp = Comp.lshr(ShAmtVal);
6022     else
6023       Comp = Comp.ashr(ShAmtVal);
6024     
6025     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6026       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6027       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6028       return ReplaceInstUsesWith(ICI, Cst);
6029     }
6030     
6031     // Otherwise, check to see if the bits shifted out are known to be zero.
6032     // If so, we can compare against the unshifted value:
6033     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6034     if (LHSI->hasOneUse() &&
6035         MaskedValueIsZero(LHSI->getOperand(0), 
6036                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6037       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6038                           ConstantExpr::getShl(RHS, ShAmt));
6039     }
6040       
6041     if (LHSI->hasOneUse()) {
6042       // Otherwise strength reduce the shift into an and.
6043       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6044       Constant *Mask = ConstantInt::get(Val);
6045       
6046       Instruction *AndI =
6047         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6048                                   Mask, LHSI->getName()+".mask");
6049       Value *And = InsertNewInstBefore(AndI, ICI);
6050       return new ICmpInst(ICI.getPredicate(), And,
6051                           ConstantExpr::getShl(RHS, ShAmt));
6052     }
6053     break;
6054   }
6055     
6056   case Instruction::SDiv:
6057   case Instruction::UDiv:
6058     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6059     // Fold this div into the comparison, producing a range check. 
6060     // Determine, based on the divide type, what the range is being 
6061     // checked.  If there is an overflow on the low or high side, remember 
6062     // it, otherwise compute the range [low, hi) bounding the new value.
6063     // See: InsertRangeTest above for the kinds of replacements possible.
6064     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6065       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6066                                           DivRHS))
6067         return R;
6068     break;
6069
6070   case Instruction::Add:
6071     // Fold: icmp pred (add, X, C1), C2
6072
6073     if (!ICI.isEquality()) {
6074       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6075       if (!LHSC) break;
6076       const APInt &LHSV = LHSC->getValue();
6077
6078       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6079                             .subtract(LHSV);
6080
6081       if (ICI.isSignedPredicate()) {
6082         if (CR.getLower().isSignBit()) {
6083           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6084                               ConstantInt::get(CR.getUpper()));
6085         } else if (CR.getUpper().isSignBit()) {
6086           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6087                               ConstantInt::get(CR.getLower()));
6088         }
6089       } else {
6090         if (CR.getLower().isMinValue()) {
6091           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6092                               ConstantInt::get(CR.getUpper()));
6093         } else if (CR.getUpper().isMinValue()) {
6094           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6095                               ConstantInt::get(CR.getLower()));
6096         }
6097       }
6098     }
6099     break;
6100   }
6101   
6102   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6103   if (ICI.isEquality()) {
6104     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6105     
6106     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6107     // the second operand is a constant, simplify a bit.
6108     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6109       switch (BO->getOpcode()) {
6110       case Instruction::SRem:
6111         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6112         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6113           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6114           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6115             Instruction *NewRem =
6116               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6117                                          BO->getName());
6118             InsertNewInstBefore(NewRem, ICI);
6119             return new ICmpInst(ICI.getPredicate(), NewRem, 
6120                                 Constant::getNullValue(BO->getType()));
6121           }
6122         }
6123         break;
6124       case Instruction::Add:
6125         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6126         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6127           if (BO->hasOneUse())
6128             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6129                                 Subtract(RHS, BOp1C));
6130         } else if (RHSV == 0) {
6131           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6132           // efficiently invertible, or if the add has just this one use.
6133           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6134           
6135           if (Value *NegVal = dyn_castNegVal(BOp1))
6136             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6137           else if (Value *NegVal = dyn_castNegVal(BOp0))
6138             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6139           else if (BO->hasOneUse()) {
6140             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6141             InsertNewInstBefore(Neg, ICI);
6142             Neg->takeName(BO);
6143             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6144           }
6145         }
6146         break;
6147       case Instruction::Xor:
6148         // For the xor case, we can xor two constants together, eliminating
6149         // the explicit xor.
6150         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6151           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6152                               ConstantExpr::getXor(RHS, BOC));
6153         
6154         // FALLTHROUGH
6155       case Instruction::Sub:
6156         // Replace (([sub|xor] A, B) != 0) with (A != B)
6157         if (RHSV == 0)
6158           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6159                               BO->getOperand(1));
6160         break;
6161         
6162       case Instruction::Or:
6163         // If bits are being or'd in that are not present in the constant we
6164         // are comparing against, then the comparison could never succeed!
6165         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6166           Constant *NotCI = ConstantExpr::getNot(RHS);
6167           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6168             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6169                                                              isICMP_NE));
6170         }
6171         break;
6172         
6173       case Instruction::And:
6174         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6175           // If bits are being compared against that are and'd out, then the
6176           // comparison can never succeed!
6177           if ((RHSV & ~BOC->getValue()) != 0)
6178             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6179                                                              isICMP_NE));
6180           
6181           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6182           if (RHS == BOC && RHSV.isPowerOf2())
6183             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6184                                 ICmpInst::ICMP_NE, LHSI,
6185                                 Constant::getNullValue(RHS->getType()));
6186           
6187           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6188           if (BOC->getValue().isSignBit()) {
6189             Value *X = BO->getOperand(0);
6190             Constant *Zero = Constant::getNullValue(X->getType());
6191             ICmpInst::Predicate pred = isICMP_NE ? 
6192               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6193             return new ICmpInst(pred, X, Zero);
6194           }
6195           
6196           // ((X & ~7) == 0) --> X < 8
6197           if (RHSV == 0 && isHighOnes(BOC)) {
6198             Value *X = BO->getOperand(0);
6199             Constant *NegX = ConstantExpr::getNeg(BOC);
6200             ICmpInst::Predicate pred = isICMP_NE ? 
6201               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6202             return new ICmpInst(pred, X, NegX);
6203           }
6204         }
6205       default: break;
6206       }
6207     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6208       // Handle icmp {eq|ne} <intrinsic>, intcst.
6209       if (II->getIntrinsicID() == Intrinsic::bswap) {
6210         AddToWorkList(II);
6211         ICI.setOperand(0, II->getOperand(1));
6212         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6213         return &ICI;
6214       }
6215     }
6216   } else {  // Not a ICMP_EQ/ICMP_NE
6217             // If the LHS is a cast from an integral value of the same size, 
6218             // then since we know the RHS is a constant, try to simlify.
6219     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6220       Value *CastOp = Cast->getOperand(0);
6221       const Type *SrcTy = CastOp->getType();
6222       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6223       if (SrcTy->isInteger() && 
6224           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6225         // If this is an unsigned comparison, try to make the comparison use
6226         // smaller constant values.
6227         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6228           // X u< 128 => X s> -1
6229           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6230                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6231         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6232                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6233           // X u> 127 => X s< 0
6234           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6235                               Constant::getNullValue(SrcTy));
6236         }
6237       }
6238     }
6239   }
6240   return 0;
6241 }
6242
6243 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6244 /// We only handle extending casts so far.
6245 ///
6246 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6247   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6248   Value *LHSCIOp        = LHSCI->getOperand(0);
6249   const Type *SrcTy     = LHSCIOp->getType();
6250   const Type *DestTy    = LHSCI->getType();
6251   Value *RHSCIOp;
6252
6253   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6254   // integer type is the same size as the pointer type.
6255   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6256       getTargetData().getPointerSizeInBits() == 
6257          cast<IntegerType>(DestTy)->getBitWidth()) {
6258     Value *RHSOp = 0;
6259     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6260       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6261     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6262       RHSOp = RHSC->getOperand(0);
6263       // If the pointer types don't match, insert a bitcast.
6264       if (LHSCIOp->getType() != RHSOp->getType())
6265         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6266     }
6267
6268     if (RHSOp)
6269       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6270   }
6271   
6272   // The code below only handles extension cast instructions, so far.
6273   // Enforce this.
6274   if (LHSCI->getOpcode() != Instruction::ZExt &&
6275       LHSCI->getOpcode() != Instruction::SExt)
6276     return 0;
6277
6278   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6279   bool isSignedCmp = ICI.isSignedPredicate();
6280
6281   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6282     // Not an extension from the same type?
6283     RHSCIOp = CI->getOperand(0);
6284     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6285       return 0;
6286     
6287     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6288     // and the other is a zext), then we can't handle this.
6289     if (CI->getOpcode() != LHSCI->getOpcode())
6290       return 0;
6291
6292     // Deal with equality cases early.
6293     if (ICI.isEquality())
6294       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6295
6296     // A signed comparison of sign extended values simplifies into a
6297     // signed comparison.
6298     if (isSignedCmp && isSignedExt)
6299       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6300
6301     // The other three cases all fold into an unsigned comparison.
6302     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6303   }
6304
6305   // If we aren't dealing with a constant on the RHS, exit early
6306   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6307   if (!CI)
6308     return 0;
6309
6310   // Compute the constant that would happen if we truncated to SrcTy then
6311   // reextended to DestTy.
6312   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6313   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6314
6315   // If the re-extended constant didn't change...
6316   if (Res2 == CI) {
6317     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6318     // For example, we might have:
6319     //    %A = sext short %X to uint
6320     //    %B = icmp ugt uint %A, 1330
6321     // It is incorrect to transform this into 
6322     //    %B = icmp ugt short %X, 1330 
6323     // because %A may have negative value. 
6324     //
6325     // However, we allow this when the compare is EQ/NE, because they are
6326     // signless.
6327     if (isSignedExt == isSignedCmp || ICI.isEquality())
6328       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6329     return 0;
6330   }
6331
6332   // The re-extended constant changed so the constant cannot be represented 
6333   // in the shorter type. Consequently, we cannot emit a simple comparison.
6334
6335   // First, handle some easy cases. We know the result cannot be equal at this
6336   // point so handle the ICI.isEquality() cases
6337   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6338     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6339   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6340     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6341
6342   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6343   // should have been folded away previously and not enter in here.
6344   Value *Result;
6345   if (isSignedCmp) {
6346     // We're performing a signed comparison.
6347     if (cast<ConstantInt>(CI)->getValue().isNegative())
6348       Result = ConstantInt::getFalse();          // X < (small) --> false
6349     else
6350       Result = ConstantInt::getTrue();           // X < (large) --> true
6351   } else {
6352     // We're performing an unsigned comparison.
6353     if (isSignedExt) {
6354       // We're performing an unsigned comp with a sign extended value.
6355       // This is true if the input is >= 0. [aka >s -1]
6356       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6357       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6358                                    NegOne, ICI.getName()), ICI);
6359     } else {
6360       // Unsigned extend & unsigned compare -> always true.
6361       Result = ConstantInt::getTrue();
6362     }
6363   }
6364
6365   // Finally, return the value computed.
6366   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6367       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6368     return ReplaceInstUsesWith(ICI, Result);
6369
6370   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6371           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6372          "ICmp should be folded!");
6373   if (Constant *CI = dyn_cast<Constant>(Result))
6374     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6375   return BinaryOperator::CreateNot(Result);
6376 }
6377
6378 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6379   return commonShiftTransforms(I);
6380 }
6381
6382 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6383   return commonShiftTransforms(I);
6384 }
6385
6386 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6387   if (Instruction *R = commonShiftTransforms(I))
6388     return R;
6389   
6390   Value *Op0 = I.getOperand(0);
6391   
6392   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6393   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6394     if (CSI->isAllOnesValue())
6395       return ReplaceInstUsesWith(I, CSI);
6396   
6397   // See if we can turn a signed shr into an unsigned shr.
6398   if (!isa<VectorType>(I.getType()) &&
6399       MaskedValueIsZero(Op0,
6400                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6401     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6402   
6403   return 0;
6404 }
6405
6406 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6407   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6408   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6409
6410   // shl X, 0 == X and shr X, 0 == X
6411   // shl 0, X == 0 and shr 0, X == 0
6412   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6413       Op0 == Constant::getNullValue(Op0->getType()))
6414     return ReplaceInstUsesWith(I, Op0);
6415   
6416   if (isa<UndefValue>(Op0)) {            
6417     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6418       return ReplaceInstUsesWith(I, Op0);
6419     else                                    // undef << X -> 0, undef >>u X -> 0
6420       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6421   }
6422   if (isa<UndefValue>(Op1)) {
6423     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6424       return ReplaceInstUsesWith(I, Op0);          
6425     else                                     // X << undef, X >>u undef -> 0
6426       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6427   }
6428
6429   // Try to fold constant and into select arguments.
6430   if (isa<Constant>(Op0))
6431     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6432       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6433         return R;
6434
6435   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6436     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6437       return Res;
6438   return 0;
6439 }
6440
6441 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6442                                                BinaryOperator &I) {
6443   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6444
6445   // See if we can simplify any instructions used by the instruction whose sole 
6446   // purpose is to compute bits we don't care about.
6447   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6448   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6449   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6450                            KnownZero, KnownOne))
6451     return &I;
6452   
6453   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6454   // of a signed value.
6455   //
6456   if (Op1->uge(TypeBits)) {
6457     if (I.getOpcode() != Instruction::AShr)
6458       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6459     else {
6460       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6461       return &I;
6462     }
6463   }
6464   
6465   // ((X*C1) << C2) == (X * (C1 << C2))
6466   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6467     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6468       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6469         return BinaryOperator::CreateMul(BO->getOperand(0),
6470                                          ConstantExpr::getShl(BOOp, Op1));
6471   
6472   // Try to fold constant and into select arguments.
6473   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6474     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6475       return R;
6476   if (isa<PHINode>(Op0))
6477     if (Instruction *NV = FoldOpIntoPhi(I))
6478       return NV;
6479   
6480   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6481   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6482     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6483     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6484     // place.  Don't try to do this transformation in this case.  Also, we
6485     // require that the input operand is a shift-by-constant so that we have
6486     // confidence that the shifts will get folded together.  We could do this
6487     // xform in more cases, but it is unlikely to be profitable.
6488     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6489         isa<ConstantInt>(TrOp->getOperand(1))) {
6490       // Okay, we'll do this xform.  Make the shift of shift.
6491       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6492       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6493                                                 I.getName());
6494       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6495
6496       // For logical shifts, the truncation has the effect of making the high
6497       // part of the register be zeros.  Emulate this by inserting an AND to
6498       // clear the top bits as needed.  This 'and' will usually be zapped by
6499       // other xforms later if dead.
6500       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6501       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6502       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6503       
6504       // The mask we constructed says what the trunc would do if occurring
6505       // between the shifts.  We want to know the effect *after* the second
6506       // shift.  We know that it is a logical shift by a constant, so adjust the
6507       // mask as appropriate.
6508       if (I.getOpcode() == Instruction::Shl)
6509         MaskV <<= Op1->getZExtValue();
6510       else {
6511         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6512         MaskV = MaskV.lshr(Op1->getZExtValue());
6513       }
6514
6515       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6516                                                    TI->getName());
6517       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6518
6519       // Return the value truncated to the interesting size.
6520       return new TruncInst(And, I.getType());
6521     }
6522   }
6523   
6524   if (Op0->hasOneUse()) {
6525     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6526       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6527       Value *V1, *V2;
6528       ConstantInt *CC;
6529       switch (Op0BO->getOpcode()) {
6530         default: break;
6531         case Instruction::Add:
6532         case Instruction::And:
6533         case Instruction::Or:
6534         case Instruction::Xor: {
6535           // These operators commute.
6536           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6537           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6538               match(Op0BO->getOperand(1),
6539                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6540             Instruction *YS = BinaryOperator::CreateShl(
6541                                             Op0BO->getOperand(0), Op1,
6542                                             Op0BO->getName());
6543             InsertNewInstBefore(YS, I); // (Y << C)
6544             Instruction *X = 
6545               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6546                                      Op0BO->getOperand(1)->getName());
6547             InsertNewInstBefore(X, I);  // (X + (Y << C))
6548             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6549             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6550                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6551           }
6552           
6553           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6554           Value *Op0BOOp1 = Op0BO->getOperand(1);
6555           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6556               match(Op0BOOp1, 
6557                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6558               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6559               V2 == Op1) {
6560             Instruction *YS = BinaryOperator::CreateShl(
6561                                                      Op0BO->getOperand(0), Op1,
6562                                                      Op0BO->getName());
6563             InsertNewInstBefore(YS, I); // (Y << C)
6564             Instruction *XM =
6565               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6566                                         V1->getName()+".mask");
6567             InsertNewInstBefore(XM, I); // X & (CC << C)
6568             
6569             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6570           }
6571         }
6572           
6573         // FALL THROUGH.
6574         case Instruction::Sub: {
6575           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6576           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6577               match(Op0BO->getOperand(0),
6578                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6579             Instruction *YS = BinaryOperator::CreateShl(
6580                                                      Op0BO->getOperand(1), Op1,
6581                                                      Op0BO->getName());
6582             InsertNewInstBefore(YS, I); // (Y << C)
6583             Instruction *X =
6584               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6585                                      Op0BO->getOperand(0)->getName());
6586             InsertNewInstBefore(X, I);  // (X + (Y << C))
6587             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6588             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6589                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6590           }
6591           
6592           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6593           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6594               match(Op0BO->getOperand(0),
6595                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6596                           m_ConstantInt(CC))) && V2 == Op1 &&
6597               cast<BinaryOperator>(Op0BO->getOperand(0))
6598                   ->getOperand(0)->hasOneUse()) {
6599             Instruction *YS = BinaryOperator::CreateShl(
6600                                                      Op0BO->getOperand(1), Op1,
6601                                                      Op0BO->getName());
6602             InsertNewInstBefore(YS, I); // (Y << C)
6603             Instruction *XM =
6604               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6605                                         V1->getName()+".mask");
6606             InsertNewInstBefore(XM, I); // X & (CC << C)
6607             
6608             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6609           }
6610           
6611           break;
6612         }
6613       }
6614       
6615       
6616       // If the operand is an bitwise operator with a constant RHS, and the
6617       // shift is the only use, we can pull it out of the shift.
6618       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6619         bool isValid = true;     // Valid only for And, Or, Xor
6620         bool highBitSet = false; // Transform if high bit of constant set?
6621         
6622         switch (Op0BO->getOpcode()) {
6623           default: isValid = false; break;   // Do not perform transform!
6624           case Instruction::Add:
6625             isValid = isLeftShift;
6626             break;
6627           case Instruction::Or:
6628           case Instruction::Xor:
6629             highBitSet = false;
6630             break;
6631           case Instruction::And:
6632             highBitSet = true;
6633             break;
6634         }
6635         
6636         // If this is a signed shift right, and the high bit is modified
6637         // by the logical operation, do not perform the transformation.
6638         // The highBitSet boolean indicates the value of the high bit of
6639         // the constant which would cause it to be modified for this
6640         // operation.
6641         //
6642         if (isValid && I.getOpcode() == Instruction::AShr)
6643           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6644         
6645         if (isValid) {
6646           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6647           
6648           Instruction *NewShift =
6649             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6650           InsertNewInstBefore(NewShift, I);
6651           NewShift->takeName(Op0BO);
6652           
6653           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6654                                         NewRHS);
6655         }
6656       }
6657     }
6658   }
6659   
6660   // Find out if this is a shift of a shift by a constant.
6661   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6662   if (ShiftOp && !ShiftOp->isShift())
6663     ShiftOp = 0;
6664   
6665   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6666     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6667     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6668     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6669     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6670     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6671     Value *X = ShiftOp->getOperand(0);
6672     
6673     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6674     if (AmtSum > TypeBits)
6675       AmtSum = TypeBits;
6676     
6677     const IntegerType *Ty = cast<IntegerType>(I.getType());
6678     
6679     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6680     if (I.getOpcode() == ShiftOp->getOpcode()) {
6681       return BinaryOperator::Create(I.getOpcode(), X,
6682                                     ConstantInt::get(Ty, AmtSum));
6683     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6684                I.getOpcode() == Instruction::AShr) {
6685       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6686       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6687     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6688                I.getOpcode() == Instruction::LShr) {
6689       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6690       Instruction *Shift =
6691         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6692       InsertNewInstBefore(Shift, I);
6693
6694       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6695       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6696     }
6697     
6698     // Okay, if we get here, one shift must be left, and the other shift must be
6699     // right.  See if the amounts are equal.
6700     if (ShiftAmt1 == ShiftAmt2) {
6701       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6702       if (I.getOpcode() == Instruction::Shl) {
6703         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6704         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6705       }
6706       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6707       if (I.getOpcode() == Instruction::LShr) {
6708         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6709         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6710       }
6711       // We can simplify ((X << C) >>s C) into a trunc + sext.
6712       // NOTE: we could do this for any C, but that would make 'unusual' integer
6713       // types.  For now, just stick to ones well-supported by the code
6714       // generators.
6715       const Type *SExtType = 0;
6716       switch (Ty->getBitWidth() - ShiftAmt1) {
6717       case 1  :
6718       case 8  :
6719       case 16 :
6720       case 32 :
6721       case 64 :
6722       case 128:
6723         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6724         break;
6725       default: break;
6726       }
6727       if (SExtType) {
6728         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6729         InsertNewInstBefore(NewTrunc, I);
6730         return new SExtInst(NewTrunc, Ty);
6731       }
6732       // Otherwise, we can't handle it yet.
6733     } else if (ShiftAmt1 < ShiftAmt2) {
6734       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6735       
6736       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6737       if (I.getOpcode() == Instruction::Shl) {
6738         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6739                ShiftOp->getOpcode() == Instruction::AShr);
6740         Instruction *Shift =
6741           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6742         InsertNewInstBefore(Shift, I);
6743         
6744         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6745         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6746       }
6747       
6748       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6749       if (I.getOpcode() == Instruction::LShr) {
6750         assert(ShiftOp->getOpcode() == Instruction::Shl);
6751         Instruction *Shift =
6752           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6753         InsertNewInstBefore(Shift, I);
6754         
6755         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6756         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6757       }
6758       
6759       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6760     } else {
6761       assert(ShiftAmt2 < ShiftAmt1);
6762       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6763
6764       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6765       if (I.getOpcode() == Instruction::Shl) {
6766         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6767                ShiftOp->getOpcode() == Instruction::AShr);
6768         Instruction *Shift =
6769           BinaryOperator::Create(ShiftOp->getOpcode(), X,
6770                                  ConstantInt::get(Ty, ShiftDiff));
6771         InsertNewInstBefore(Shift, I);
6772         
6773         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6774         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6775       }
6776       
6777       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6778       if (I.getOpcode() == Instruction::LShr) {
6779         assert(ShiftOp->getOpcode() == Instruction::Shl);
6780         Instruction *Shift =
6781           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6782         InsertNewInstBefore(Shift, I);
6783         
6784         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6785         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6786       }
6787       
6788       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6789     }
6790   }
6791   return 0;
6792 }
6793
6794
6795 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6796 /// expression.  If so, decompose it, returning some value X, such that Val is
6797 /// X*Scale+Offset.
6798 ///
6799 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6800                                         int &Offset) {
6801   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6802   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6803     Offset = CI->getZExtValue();
6804     Scale  = 0;
6805     return ConstantInt::get(Type::Int32Ty, 0);
6806   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6807     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6808       if (I->getOpcode() == Instruction::Shl) {
6809         // This is a value scaled by '1 << the shift amt'.
6810         Scale = 1U << RHS->getZExtValue();
6811         Offset = 0;
6812         return I->getOperand(0);
6813       } else if (I->getOpcode() == Instruction::Mul) {
6814         // This value is scaled by 'RHS'.
6815         Scale = RHS->getZExtValue();
6816         Offset = 0;
6817         return I->getOperand(0);
6818       } else if (I->getOpcode() == Instruction::Add) {
6819         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6820         // where C1 is divisible by C2.
6821         unsigned SubScale;
6822         Value *SubVal = 
6823           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6824         Offset += RHS->getZExtValue();
6825         Scale = SubScale;
6826         return SubVal;
6827       }
6828     }
6829   }
6830
6831   // Otherwise, we can't look past this.
6832   Scale = 1;
6833   Offset = 0;
6834   return Val;
6835 }
6836
6837
6838 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6839 /// try to eliminate the cast by moving the type information into the alloc.
6840 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6841                                                    AllocationInst &AI) {
6842   const PointerType *PTy = cast<PointerType>(CI.getType());
6843   
6844   // Remove any uses of AI that are dead.
6845   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6846   
6847   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6848     Instruction *User = cast<Instruction>(*UI++);
6849     if (isInstructionTriviallyDead(User)) {
6850       while (UI != E && *UI == User)
6851         ++UI; // If this instruction uses AI more than once, don't break UI.
6852       
6853       ++NumDeadInst;
6854       DOUT << "IC: DCE: " << *User;
6855       EraseInstFromFunction(*User);
6856     }
6857   }
6858   
6859   // Get the type really allocated and the type casted to.
6860   const Type *AllocElTy = AI.getAllocatedType();
6861   const Type *CastElTy = PTy->getElementType();
6862   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6863
6864   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6865   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6866   if (CastElTyAlign < AllocElTyAlign) return 0;
6867
6868   // If the allocation has multiple uses, only promote it if we are strictly
6869   // increasing the alignment of the resultant allocation.  If we keep it the
6870   // same, we open the door to infinite loops of various kinds.
6871   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6872
6873   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6874   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6875   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6876
6877   // See if we can satisfy the modulus by pulling a scale out of the array
6878   // size argument.
6879   unsigned ArraySizeScale;
6880   int ArrayOffset;
6881   Value *NumElements = // See if the array size is a decomposable linear expr.
6882     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6883  
6884   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6885   // do the xform.
6886   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6887       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6888
6889   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6890   Value *Amt = 0;
6891   if (Scale == 1) {
6892     Amt = NumElements;
6893   } else {
6894     // If the allocation size is constant, form a constant mul expression
6895     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6896     if (isa<ConstantInt>(NumElements))
6897       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6898     // otherwise multiply the amount and the number of elements
6899     else if (Scale != 1) {
6900       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6901       Amt = InsertNewInstBefore(Tmp, AI);
6902     }
6903   }
6904   
6905   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6906     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6907     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6908     Amt = InsertNewInstBefore(Tmp, AI);
6909   }
6910   
6911   AllocationInst *New;
6912   if (isa<MallocInst>(AI))
6913     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6914   else
6915     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6916   InsertNewInstBefore(New, AI);
6917   New->takeName(&AI);
6918   
6919   // If the allocation has multiple uses, insert a cast and change all things
6920   // that used it to use the new cast.  This will also hack on CI, but it will
6921   // die soon.
6922   if (!AI.hasOneUse()) {
6923     AddUsesToWorkList(AI);
6924     // New is the allocation instruction, pointer typed. AI is the original
6925     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6926     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6927     InsertNewInstBefore(NewCast, AI);
6928     AI.replaceAllUsesWith(NewCast);
6929   }
6930   return ReplaceInstUsesWith(CI, New);
6931 }
6932
6933 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6934 /// and return it as type Ty without inserting any new casts and without
6935 /// changing the computed value.  This is used by code that tries to decide
6936 /// whether promoting or shrinking integer operations to wider or smaller types
6937 /// will allow us to eliminate a truncate or extend.
6938 ///
6939 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6940 /// extension operation if Ty is larger.
6941 ///
6942 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
6943 /// should return true if trunc(V) can be computed by computing V in the smaller
6944 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
6945 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6946 /// efficiently truncated.
6947 ///
6948 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6949 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6950 /// the final result.
6951 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6952                                               unsigned CastOpc,
6953                                               int &NumCastsRemoved) {
6954   // We can always evaluate constants in another type.
6955   if (isa<ConstantInt>(V))
6956     return true;
6957   
6958   Instruction *I = dyn_cast<Instruction>(V);
6959   if (!I) return false;
6960   
6961   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6962   
6963   // If this is an extension or truncate, we can often eliminate it.
6964   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6965     // If this is a cast from the destination type, we can trivially eliminate
6966     // it, and this will remove a cast overall.
6967     if (I->getOperand(0)->getType() == Ty) {
6968       // If the first operand is itself a cast, and is eliminable, do not count
6969       // this as an eliminable cast.  We would prefer to eliminate those two
6970       // casts first.
6971       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
6972         ++NumCastsRemoved;
6973       return true;
6974     }
6975   }
6976
6977   // We can't extend or shrink something that has multiple uses: doing so would
6978   // require duplicating the instruction in general, which isn't profitable.
6979   if (!I->hasOneUse()) return false;
6980
6981   switch (I->getOpcode()) {
6982   case Instruction::Add:
6983   case Instruction::Sub:
6984   case Instruction::Mul:
6985   case Instruction::And:
6986   case Instruction::Or:
6987   case Instruction::Xor:
6988     // These operators can all arbitrarily be extended or truncated.
6989     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6990                                       NumCastsRemoved) &&
6991            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6992                                       NumCastsRemoved);
6993
6994   case Instruction::Shl:
6995     // If we are truncating the result of this SHL, and if it's a shift of a
6996     // constant amount, we can always perform a SHL in a smaller type.
6997     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6998       uint32_t BitWidth = Ty->getBitWidth();
6999       if (BitWidth < OrigTy->getBitWidth() && 
7000           CI->getLimitedValue(BitWidth) < BitWidth)
7001         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7002                                           NumCastsRemoved);
7003     }
7004     break;
7005   case Instruction::LShr:
7006     // If this is a truncate of a logical shr, we can truncate it to a smaller
7007     // lshr iff we know that the bits we would otherwise be shifting in are
7008     // already zeros.
7009     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7010       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7011       uint32_t BitWidth = Ty->getBitWidth();
7012       if (BitWidth < OrigBitWidth &&
7013           MaskedValueIsZero(I->getOperand(0),
7014             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7015           CI->getLimitedValue(BitWidth) < BitWidth) {
7016         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7017                                           NumCastsRemoved);
7018       }
7019     }
7020     break;
7021   case Instruction::ZExt:
7022   case Instruction::SExt:
7023   case Instruction::Trunc:
7024     // If this is the same kind of case as our original (e.g. zext+zext), we
7025     // can safely replace it.  Note that replacing it does not reduce the number
7026     // of casts in the input.
7027     if (I->getOpcode() == CastOpc)
7028       return true;
7029     break;
7030   case Instruction::Select: {
7031     SelectInst *SI = cast<SelectInst>(I);
7032     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7033                                       NumCastsRemoved) &&
7034            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7035                                       NumCastsRemoved);
7036   }
7037   case Instruction::PHI: {
7038     // We can change a phi if we can change all operands.
7039     PHINode *PN = cast<PHINode>(I);
7040     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7041       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7042                                       NumCastsRemoved))
7043         return false;
7044     return true;
7045   }
7046   default:
7047     // TODO: Can handle more cases here.
7048     break;
7049   }
7050   
7051   return false;
7052 }
7053
7054 /// EvaluateInDifferentType - Given an expression that 
7055 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7056 /// evaluate the expression.
7057 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7058                                              bool isSigned) {
7059   if (Constant *C = dyn_cast<Constant>(V))
7060     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7061
7062   // Otherwise, it must be an instruction.
7063   Instruction *I = cast<Instruction>(V);
7064   Instruction *Res = 0;
7065   switch (I->getOpcode()) {
7066   case Instruction::Add:
7067   case Instruction::Sub:
7068   case Instruction::Mul:
7069   case Instruction::And:
7070   case Instruction::Or:
7071   case Instruction::Xor:
7072   case Instruction::AShr:
7073   case Instruction::LShr:
7074   case Instruction::Shl: {
7075     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7076     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7077     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7078                                  LHS, RHS);
7079     break;
7080   }    
7081   case Instruction::Trunc:
7082   case Instruction::ZExt:
7083   case Instruction::SExt:
7084     // If the source type of the cast is the type we're trying for then we can
7085     // just return the source.  There's no need to insert it because it is not
7086     // new.
7087     if (I->getOperand(0)->getType() == Ty)
7088       return I->getOperand(0);
7089     
7090     // Otherwise, must be the same type of cast, so just reinsert a new one.
7091     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7092                            Ty);
7093     break;
7094   case Instruction::Select: {
7095     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7096     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7097     Res = SelectInst::Create(I->getOperand(0), True, False);
7098     break;
7099   }
7100   case Instruction::PHI: {
7101     PHINode *OPN = cast<PHINode>(I);
7102     PHINode *NPN = PHINode::Create(Ty);
7103     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7104       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7105       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7106     }
7107     Res = NPN;
7108     break;
7109   }
7110   default: 
7111     // TODO: Can handle more cases here.
7112     assert(0 && "Unreachable!");
7113     break;
7114   }
7115   
7116   Res->takeName(I);
7117   return InsertNewInstBefore(Res, *I);
7118 }
7119
7120 /// @brief Implement the transforms common to all CastInst visitors.
7121 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7122   Value *Src = CI.getOperand(0);
7123
7124   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7125   // eliminate it now.
7126   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7127     if (Instruction::CastOps opc = 
7128         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7129       // The first cast (CSrc) is eliminable so we need to fix up or replace
7130       // the second cast (CI). CSrc will then have a good chance of being dead.
7131       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7132     }
7133   }
7134
7135   // If we are casting a select then fold the cast into the select
7136   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7137     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7138       return NV;
7139
7140   // If we are casting a PHI then fold the cast into the PHI
7141   if (isa<PHINode>(Src))
7142     if (Instruction *NV = FoldOpIntoPhi(CI))
7143       return NV;
7144   
7145   return 0;
7146 }
7147
7148 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7149 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7150   Value *Src = CI.getOperand(0);
7151   
7152   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7153     // If casting the result of a getelementptr instruction with no offset, turn
7154     // this into a cast of the original pointer!
7155     if (GEP->hasAllZeroIndices()) {
7156       // Changing the cast operand is usually not a good idea but it is safe
7157       // here because the pointer operand is being replaced with another 
7158       // pointer operand so the opcode doesn't need to change.
7159       AddToWorkList(GEP);
7160       CI.setOperand(0, GEP->getOperand(0));
7161       return &CI;
7162     }
7163     
7164     // If the GEP has a single use, and the base pointer is a bitcast, and the
7165     // GEP computes a constant offset, see if we can convert these three
7166     // instructions into fewer.  This typically happens with unions and other
7167     // non-type-safe code.
7168     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7169       if (GEP->hasAllConstantIndices()) {
7170         // We are guaranteed to get a constant from EmitGEPOffset.
7171         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7172         int64_t Offset = OffsetV->getSExtValue();
7173         
7174         // Get the base pointer input of the bitcast, and the type it points to.
7175         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7176         const Type *GEPIdxTy =
7177           cast<PointerType>(OrigBase->getType())->getElementType();
7178         if (GEPIdxTy->isSized()) {
7179           SmallVector<Value*, 8> NewIndices;
7180           
7181           // Start with the index over the outer type.  Note that the type size
7182           // might be zero (even if the offset isn't zero) if the indexed type
7183           // is something like [0 x {int, int}]
7184           const Type *IntPtrTy = TD->getIntPtrType();
7185           int64_t FirstIdx = 0;
7186           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7187             FirstIdx = Offset/TySize;
7188             Offset %= TySize;
7189           
7190             // Handle silly modulus not returning values values [0..TySize).
7191             if (Offset < 0) {
7192               --FirstIdx;
7193               Offset += TySize;
7194               assert(Offset >= 0);
7195             }
7196             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7197           }
7198           
7199           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7200
7201           // Index into the types.  If we fail, set OrigBase to null.
7202           while (Offset) {
7203             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7204               const StructLayout *SL = TD->getStructLayout(STy);
7205               if (Offset < (int64_t)SL->getSizeInBytes()) {
7206                 unsigned Elt = SL->getElementContainingOffset(Offset);
7207                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7208               
7209                 Offset -= SL->getElementOffset(Elt);
7210                 GEPIdxTy = STy->getElementType(Elt);
7211               } else {
7212                 // Otherwise, we can't index into this, bail out.
7213                 Offset = 0;
7214                 OrigBase = 0;
7215               }
7216             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7217               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7218               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7219                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7220                 Offset %= EltSize;
7221               } else {
7222                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7223               }
7224               GEPIdxTy = STy->getElementType();
7225             } else {
7226               // Otherwise, we can't index into this, bail out.
7227               Offset = 0;
7228               OrigBase = 0;
7229             }
7230           }
7231           if (OrigBase) {
7232             // If we were able to index down into an element, create the GEP
7233             // and bitcast the result.  This eliminates one bitcast, potentially
7234             // two.
7235             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7236                                                           NewIndices.begin(),
7237                                                           NewIndices.end(), "");
7238             InsertNewInstBefore(NGEP, CI);
7239             NGEP->takeName(GEP);
7240             
7241             if (isa<BitCastInst>(CI))
7242               return new BitCastInst(NGEP, CI.getType());
7243             assert(isa<PtrToIntInst>(CI));
7244             return new PtrToIntInst(NGEP, CI.getType());
7245           }
7246         }
7247       }      
7248     }
7249   }
7250     
7251   return commonCastTransforms(CI);
7252 }
7253
7254
7255
7256 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7257 /// integer types. This function implements the common transforms for all those
7258 /// cases.
7259 /// @brief Implement the transforms common to CastInst with integer operands
7260 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7261   if (Instruction *Result = commonCastTransforms(CI))
7262     return Result;
7263
7264   Value *Src = CI.getOperand(0);
7265   const Type *SrcTy = Src->getType();
7266   const Type *DestTy = CI.getType();
7267   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7268   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7269
7270   // See if we can simplify any instructions used by the LHS whose sole 
7271   // purpose is to compute bits we don't care about.
7272   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7273   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7274                            KnownZero, KnownOne))
7275     return &CI;
7276
7277   // If the source isn't an instruction or has more than one use then we
7278   // can't do anything more. 
7279   Instruction *SrcI = dyn_cast<Instruction>(Src);
7280   if (!SrcI || !Src->hasOneUse())
7281     return 0;
7282
7283   // Attempt to propagate the cast into the instruction for int->int casts.
7284   int NumCastsRemoved = 0;
7285   if (!isa<BitCastInst>(CI) &&
7286       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7287                                  CI.getOpcode(), NumCastsRemoved)) {
7288     // If this cast is a truncate, evaluting in a different type always
7289     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7290     // we need to do an AND to maintain the clear top-part of the computation,
7291     // so we require that the input have eliminated at least one cast.  If this
7292     // is a sign extension, we insert two new casts (to do the extension) so we
7293     // require that two casts have been eliminated.
7294     bool DoXForm;
7295     switch (CI.getOpcode()) {
7296     default:
7297       // All the others use floating point so we shouldn't actually 
7298       // get here because of the check above.
7299       assert(0 && "Unknown cast type");
7300     case Instruction::Trunc:
7301       DoXForm = true;
7302       break;
7303     case Instruction::ZExt:
7304       DoXForm = NumCastsRemoved >= 1;
7305       break;
7306     case Instruction::SExt:
7307       DoXForm = NumCastsRemoved >= 2;
7308       break;
7309     }
7310     
7311     if (DoXForm) {
7312       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7313                                            CI.getOpcode() == Instruction::SExt);
7314       assert(Res->getType() == DestTy);
7315       switch (CI.getOpcode()) {
7316       default: assert(0 && "Unknown cast type!");
7317       case Instruction::Trunc:
7318       case Instruction::BitCast:
7319         // Just replace this cast with the result.
7320         return ReplaceInstUsesWith(CI, Res);
7321       case Instruction::ZExt: {
7322         // We need to emit an AND to clear the high bits.
7323         assert(SrcBitSize < DestBitSize && "Not a zext?");
7324         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7325                                                             SrcBitSize));
7326         return BinaryOperator::CreateAnd(Res, C);
7327       }
7328       case Instruction::SExt:
7329         // We need to emit a cast to truncate, then a cast to sext.
7330         return CastInst::Create(Instruction::SExt,
7331             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7332                              CI), DestTy);
7333       }
7334     }
7335   }
7336   
7337   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7338   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7339
7340   switch (SrcI->getOpcode()) {
7341   case Instruction::Add:
7342   case Instruction::Mul:
7343   case Instruction::And:
7344   case Instruction::Or:
7345   case Instruction::Xor:
7346     // If we are discarding information, rewrite.
7347     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7348       // Don't insert two casts if they cannot be eliminated.  We allow 
7349       // two casts to be inserted if the sizes are the same.  This could 
7350       // only be converting signedness, which is a noop.
7351       if (DestBitSize == SrcBitSize || 
7352           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7353           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7354         Instruction::CastOps opcode = CI.getOpcode();
7355         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7356         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7357         return BinaryOperator::Create(
7358             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7359       }
7360     }
7361
7362     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7363     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7364         SrcI->getOpcode() == Instruction::Xor &&
7365         Op1 == ConstantInt::getTrue() &&
7366         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7367       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7368       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7369     }
7370     break;
7371   case Instruction::SDiv:
7372   case Instruction::UDiv:
7373   case Instruction::SRem:
7374   case Instruction::URem:
7375     // If we are just changing the sign, rewrite.
7376     if (DestBitSize == SrcBitSize) {
7377       // Don't insert two casts if they cannot be eliminated.  We allow 
7378       // two casts to be inserted if the sizes are the same.  This could 
7379       // only be converting signedness, which is a noop.
7380       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7381           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7382         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7383                                               Op0, DestTy, SrcI);
7384         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7385                                               Op1, DestTy, SrcI);
7386         return BinaryOperator::Create(
7387           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7388       }
7389     }
7390     break;
7391
7392   case Instruction::Shl:
7393     // Allow changing the sign of the source operand.  Do not allow 
7394     // changing the size of the shift, UNLESS the shift amount is a 
7395     // constant.  We must not change variable sized shifts to a smaller 
7396     // size, because it is undefined to shift more bits out than exist 
7397     // in the value.
7398     if (DestBitSize == SrcBitSize ||
7399         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7400       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7401           Instruction::BitCast : Instruction::Trunc);
7402       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7403       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7404       return BinaryOperator::CreateShl(Op0c, Op1c);
7405     }
7406     break;
7407   case Instruction::AShr:
7408     // If this is a signed shr, and if all bits shifted in are about to be
7409     // truncated off, turn it into an unsigned shr to allow greater
7410     // simplifications.
7411     if (DestBitSize < SrcBitSize &&
7412         isa<ConstantInt>(Op1)) {
7413       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7414       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7415         // Insert the new logical shift right.
7416         return BinaryOperator::CreateLShr(Op0, Op1);
7417       }
7418     }
7419     break;
7420   }
7421   return 0;
7422 }
7423
7424 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7425   if (Instruction *Result = commonIntCastTransforms(CI))
7426     return Result;
7427   
7428   Value *Src = CI.getOperand(0);
7429   const Type *Ty = CI.getType();
7430   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7431   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7432   
7433   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7434     switch (SrcI->getOpcode()) {
7435     default: break;
7436     case Instruction::LShr:
7437       // We can shrink lshr to something smaller if we know the bits shifted in
7438       // are already zeros.
7439       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7440         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7441         
7442         // Get a mask for the bits shifting in.
7443         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7444         Value* SrcIOp0 = SrcI->getOperand(0);
7445         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7446           if (ShAmt >= DestBitWidth)        // All zeros.
7447             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7448
7449           // Okay, we can shrink this.  Truncate the input, then return a new
7450           // shift.
7451           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7452           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7453                                        Ty, CI);
7454           return BinaryOperator::CreateLShr(V1, V2);
7455         }
7456       } else {     // This is a variable shr.
7457         
7458         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7459         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7460         // loop-invariant and CSE'd.
7461         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7462           Value *One = ConstantInt::get(SrcI->getType(), 1);
7463
7464           Value *V = InsertNewInstBefore(
7465               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7466                                      "tmp"), CI);
7467           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7468                                                             SrcI->getOperand(0),
7469                                                             "tmp"), CI);
7470           Value *Zero = Constant::getNullValue(V->getType());
7471           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7472         }
7473       }
7474       break;
7475     }
7476   }
7477   
7478   return 0;
7479 }
7480
7481 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7482 /// in order to eliminate the icmp.
7483 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7484                                              bool DoXform) {
7485   // If we are just checking for a icmp eq of a single bit and zext'ing it
7486   // to an integer, then shift the bit to the appropriate place and then
7487   // cast to integer to avoid the comparison.
7488   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7489     const APInt &Op1CV = Op1C->getValue();
7490       
7491     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7492     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7493     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7494         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7495       if (!DoXform) return ICI;
7496
7497       Value *In = ICI->getOperand(0);
7498       Value *Sh = ConstantInt::get(In->getType(),
7499                                    In->getType()->getPrimitiveSizeInBits()-1);
7500       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7501                                                         In->getName()+".lobit"),
7502                                CI);
7503       if (In->getType() != CI.getType())
7504         In = CastInst::CreateIntegerCast(In, CI.getType(),
7505                                          false/*ZExt*/, "tmp", &CI);
7506
7507       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7508         Constant *One = ConstantInt::get(In->getType(), 1);
7509         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7510                                                          In->getName()+".not"),
7511                                  CI);
7512       }
7513
7514       return ReplaceInstUsesWith(CI, In);
7515     }
7516       
7517       
7518       
7519     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7520     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7521     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7522     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7523     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7524     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7525     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7526     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7527     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7528         // This only works for EQ and NE
7529         ICI->isEquality()) {
7530       // If Op1C some other power of two, convert:
7531       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7532       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7533       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7534       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7535         
7536       APInt KnownZeroMask(~KnownZero);
7537       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7538         if (!DoXform) return ICI;
7539
7540         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7541         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7542           // (X&4) == 2 --> false
7543           // (X&4) != 2 --> true
7544           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7545           Res = ConstantExpr::getZExt(Res, CI.getType());
7546           return ReplaceInstUsesWith(CI, Res);
7547         }
7548           
7549         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7550         Value *In = ICI->getOperand(0);
7551         if (ShiftAmt) {
7552           // Perform a logical shr by shiftamt.
7553           // Insert the shift to put the result in the low bit.
7554           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7555                                   ConstantInt::get(In->getType(), ShiftAmt),
7556                                                    In->getName()+".lobit"), CI);
7557         }
7558           
7559         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7560           Constant *One = ConstantInt::get(In->getType(), 1);
7561           In = BinaryOperator::CreateXor(In, One, "tmp");
7562           InsertNewInstBefore(cast<Instruction>(In), CI);
7563         }
7564           
7565         if (CI.getType() == In->getType())
7566           return ReplaceInstUsesWith(CI, In);
7567         else
7568           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7569       }
7570     }
7571   }
7572
7573   return 0;
7574 }
7575
7576 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7577   // If one of the common conversion will work ..
7578   if (Instruction *Result = commonIntCastTransforms(CI))
7579     return Result;
7580
7581   Value *Src = CI.getOperand(0);
7582
7583   // If this is a cast of a cast
7584   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7585     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7586     // types and if the sizes are just right we can convert this into a logical
7587     // 'and' which will be much cheaper than the pair of casts.
7588     if (isa<TruncInst>(CSrc)) {
7589       // Get the sizes of the types involved
7590       Value *A = CSrc->getOperand(0);
7591       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7592       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7593       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7594       // If we're actually extending zero bits and the trunc is a no-op
7595       if (MidSize < DstSize && SrcSize == DstSize) {
7596         // Replace both of the casts with an And of the type mask.
7597         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7598         Constant *AndConst = ConstantInt::get(AndValue);
7599         Instruction *And = 
7600           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7601         // Unfortunately, if the type changed, we need to cast it back.
7602         if (And->getType() != CI.getType()) {
7603           And->setName(CSrc->getName()+".mask");
7604           InsertNewInstBefore(And, CI);
7605           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7606         }
7607         return And;
7608       }
7609     }
7610   }
7611
7612   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7613     return transformZExtICmp(ICI, CI);
7614
7615   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7616   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7617     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7618     // of the (zext icmp) will be transformed.
7619     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7620     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7621     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7622         (transformZExtICmp(LHS, CI, false) ||
7623          transformZExtICmp(RHS, CI, false))) {
7624       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7625       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7626       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7627     }
7628   }
7629
7630   return 0;
7631 }
7632
7633 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7634   if (Instruction *I = commonIntCastTransforms(CI))
7635     return I;
7636   
7637   Value *Src = CI.getOperand(0);
7638   
7639   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7640   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7641   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7642     // If we are just checking for a icmp eq of a single bit and zext'ing it
7643     // to an integer, then shift the bit to the appropriate place and then
7644     // cast to integer to avoid the comparison.
7645     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7646       const APInt &Op1CV = Op1C->getValue();
7647       
7648       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7649       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7650       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7651           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7652         Value *In = ICI->getOperand(0);
7653         Value *Sh = ConstantInt::get(In->getType(),
7654                                      In->getType()->getPrimitiveSizeInBits()-1);
7655         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7656                                                         In->getName()+".lobit"),
7657                                  CI);
7658         if (In->getType() != CI.getType())
7659           In = CastInst::CreateIntegerCast(In, CI.getType(),
7660                                            true/*SExt*/, "tmp", &CI);
7661         
7662         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7663           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7664                                      In->getName()+".not"), CI);
7665         
7666         return ReplaceInstUsesWith(CI, In);
7667       }
7668     }
7669   }
7670
7671   // See if the value being truncated is already sign extended.  If so, just
7672   // eliminate the trunc/sext pair.
7673   if (getOpcode(Src) == Instruction::Trunc) {
7674     Value *Op = cast<User>(Src)->getOperand(0);
7675     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
7676     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
7677     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7678     unsigned NumSignBits = ComputeNumSignBits(Op);
7679
7680     if (OpBits == DestBits) {
7681       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7682       // bits, it is already ready.
7683       if (NumSignBits > DestBits-MidBits)
7684         return ReplaceInstUsesWith(CI, Op);
7685     } else if (OpBits < DestBits) {
7686       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7687       // bits, just sext from i32.
7688       if (NumSignBits > OpBits-MidBits)
7689         return new SExtInst(Op, CI.getType(), "tmp");
7690     } else {
7691       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7692       // bits, just truncate to i32.
7693       if (NumSignBits > OpBits-MidBits)
7694         return new TruncInst(Op, CI.getType(), "tmp");
7695     }
7696   }
7697
7698   // If the input is a shl/ashr pair of a same constant, then this is a sign
7699   // extension from a smaller value.  If we could trust arbitrary bitwidth
7700   // integers, we could turn this into a truncate to the smaller bit and then
7701   // use a sext for the whole extension.  Since we don't, look deeper and check
7702   // for a truncate.  If the source and dest are the same type, eliminate the
7703   // trunc and extend and just do shifts.  For example, turn:
7704   //   %a = trunc i32 %i to i8
7705   //   %b = shl i8 %a, 6
7706   //   %c = ashr i8 %b, 6
7707   //   %d = sext i8 %c to i32
7708   // into:
7709   //   %a = shl i32 %i, 30
7710   //   %d = ashr i32 %a, 30
7711   Value *A = 0;
7712   ConstantInt *BA = 0, *CA = 0;
7713   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
7714                         m_ConstantInt(CA))) &&
7715       BA == CA && isa<TruncInst>(A)) {
7716     Value *I = cast<TruncInst>(A)->getOperand(0);
7717     if (I->getType() == CI.getType()) {
7718       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
7719       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
7720       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
7721       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
7722       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
7723                                                         CI.getName()), CI);
7724       return BinaryOperator::CreateAShr(I, ShAmtV);
7725     }
7726   }
7727   
7728   return 0;
7729 }
7730
7731 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7732 /// in the specified FP type without changing its value.
7733 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7734   APFloat F = CFP->getValueAPF();
7735   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7736     return ConstantFP::get(F);
7737   return 0;
7738 }
7739
7740 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7741 /// through it until we get the source value.
7742 static Value *LookThroughFPExtensions(Value *V) {
7743   if (Instruction *I = dyn_cast<Instruction>(V))
7744     if (I->getOpcode() == Instruction::FPExt)
7745       return LookThroughFPExtensions(I->getOperand(0));
7746   
7747   // If this value is a constant, return the constant in the smallest FP type
7748   // that can accurately represent it.  This allows us to turn
7749   // (float)((double)X+2.0) into x+2.0f.
7750   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7751     if (CFP->getType() == Type::PPC_FP128Ty)
7752       return V;  // No constant folding of this.
7753     // See if the value can be truncated to float and then reextended.
7754     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7755       return V;
7756     if (CFP->getType() == Type::DoubleTy)
7757       return V;  // Won't shrink.
7758     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7759       return V;
7760     // Don't try to shrink to various long double types.
7761   }
7762   
7763   return V;
7764 }
7765
7766 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7767   if (Instruction *I = commonCastTransforms(CI))
7768     return I;
7769   
7770   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7771   // smaller than the destination type, we can eliminate the truncate by doing
7772   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7773   // many builtins (sqrt, etc).
7774   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7775   if (OpI && OpI->hasOneUse()) {
7776     switch (OpI->getOpcode()) {
7777     default: break;
7778     case Instruction::Add:
7779     case Instruction::Sub:
7780     case Instruction::Mul:
7781     case Instruction::FDiv:
7782     case Instruction::FRem:
7783       const Type *SrcTy = OpI->getType();
7784       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7785       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7786       if (LHSTrunc->getType() != SrcTy && 
7787           RHSTrunc->getType() != SrcTy) {
7788         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7789         // If the source types were both smaller than the destination type of
7790         // the cast, do this xform.
7791         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7792             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7793           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7794                                       CI.getType(), CI);
7795           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7796                                       CI.getType(), CI);
7797           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7798         }
7799       }
7800       break;  
7801     }
7802   }
7803   return 0;
7804 }
7805
7806 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7807   return commonCastTransforms(CI);
7808 }
7809
7810 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7811   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7812   if (OpI == 0)
7813     return commonCastTransforms(FI);
7814
7815   // fptoui(uitofp(X)) --> X
7816   // fptoui(sitofp(X)) --> X
7817   // This is safe if the intermediate type has enough bits in its mantissa to
7818   // accurately represent all values of X.  For example, do not do this with
7819   // i64->float->i64.  This is also safe for sitofp case, because any negative
7820   // 'X' value would cause an undefined result for the fptoui. 
7821   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7822       OpI->getOperand(0)->getType() == FI.getType() &&
7823       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7824                     OpI->getType()->getFPMantissaWidth())
7825     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
7826
7827   return commonCastTransforms(FI);
7828 }
7829
7830 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7831   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7832   if (OpI == 0)
7833     return commonCastTransforms(FI);
7834   
7835   // fptosi(sitofp(X)) --> X
7836   // fptosi(uitofp(X)) --> X
7837   // This is safe if the intermediate type has enough bits in its mantissa to
7838   // accurately represent all values of X.  For example, do not do this with
7839   // i64->float->i64.  This is also safe for sitofp case, because any negative
7840   // 'X' value would cause an undefined result for the fptoui. 
7841   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7842       OpI->getOperand(0)->getType() == FI.getType() &&
7843       (int)FI.getType()->getPrimitiveSizeInBits() <= 
7844                     OpI->getType()->getFPMantissaWidth())
7845     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
7846   
7847   return commonCastTransforms(FI);
7848 }
7849
7850 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7851   return commonCastTransforms(CI);
7852 }
7853
7854 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7855   return commonCastTransforms(CI);
7856 }
7857
7858 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7859   return commonPointerCastTransforms(CI);
7860 }
7861
7862 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7863   if (Instruction *I = commonCastTransforms(CI))
7864     return I;
7865   
7866   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7867   if (!DestPointee->isSized()) return 0;
7868
7869   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7870   ConstantInt *Cst;
7871   Value *X;
7872   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7873                                     m_ConstantInt(Cst)))) {
7874     // If the source and destination operands have the same type, see if this
7875     // is a single-index GEP.
7876     if (X->getType() == CI.getType()) {
7877       // Get the size of the pointee type.
7878       uint64_t Size = TD->getABITypeSize(DestPointee);
7879
7880       // Convert the constant to intptr type.
7881       APInt Offset = Cst->getValue();
7882       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7883
7884       // If Offset is evenly divisible by Size, we can do this xform.
7885       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7886         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7887         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7888       }
7889     }
7890     // TODO: Could handle other cases, e.g. where add is indexing into field of
7891     // struct etc.
7892   } else if (CI.getOperand(0)->hasOneUse() &&
7893              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7894     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7895     // "inttoptr+GEP" instead of "add+intptr".
7896     
7897     // Get the size of the pointee type.
7898     uint64_t Size = TD->getABITypeSize(DestPointee);
7899     
7900     // Convert the constant to intptr type.
7901     APInt Offset = Cst->getValue();
7902     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7903     
7904     // If Offset is evenly divisible by Size, we can do this xform.
7905     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7906       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7907       
7908       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7909                                                             "tmp"), CI);
7910       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7911     }
7912   }
7913   return 0;
7914 }
7915
7916 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7917   // If the operands are integer typed then apply the integer transforms,
7918   // otherwise just apply the common ones.
7919   Value *Src = CI.getOperand(0);
7920   const Type *SrcTy = Src->getType();
7921   const Type *DestTy = CI.getType();
7922
7923   if (SrcTy->isInteger() && DestTy->isInteger()) {
7924     if (Instruction *Result = commonIntCastTransforms(CI))
7925       return Result;
7926   } else if (isa<PointerType>(SrcTy)) {
7927     if (Instruction *I = commonPointerCastTransforms(CI))
7928       return I;
7929   } else {
7930     if (Instruction *Result = commonCastTransforms(CI))
7931       return Result;
7932   }
7933
7934
7935   // Get rid of casts from one type to the same type. These are useless and can
7936   // be replaced by the operand.
7937   if (DestTy == Src->getType())
7938     return ReplaceInstUsesWith(CI, Src);
7939
7940   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7941     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7942     const Type *DstElTy = DstPTy->getElementType();
7943     const Type *SrcElTy = SrcPTy->getElementType();
7944     
7945     // If the address spaces don't match, don't eliminate the bitcast, which is
7946     // required for changing types.
7947     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7948       return 0;
7949     
7950     // If we are casting a malloc or alloca to a pointer to a type of the same
7951     // size, rewrite the allocation instruction to allocate the "right" type.
7952     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7953       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7954         return V;
7955     
7956     // If the source and destination are pointers, and this cast is equivalent
7957     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7958     // This can enhance SROA and other transforms that want type-safe pointers.
7959     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7960     unsigned NumZeros = 0;
7961     while (SrcElTy != DstElTy && 
7962            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7963            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7964       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7965       ++NumZeros;
7966     }
7967
7968     // If we found a path from the src to dest, create the getelementptr now.
7969     if (SrcElTy == DstElTy) {
7970       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7971       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
7972                                        ((Instruction*) NULL));
7973     }
7974   }
7975
7976   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7977     if (SVI->hasOneUse()) {
7978       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7979       // a bitconvert to a vector with the same # elts.
7980       if (isa<VectorType>(DestTy) && 
7981           cast<VectorType>(DestTy)->getNumElements() == 
7982                 SVI->getType()->getNumElements()) {
7983         CastInst *Tmp;
7984         // If either of the operands is a cast from CI.getType(), then
7985         // evaluating the shuffle in the casted destination's type will allow
7986         // us to eliminate at least one cast.
7987         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7988              Tmp->getOperand(0)->getType() == DestTy) ||
7989             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7990              Tmp->getOperand(0)->getType() == DestTy)) {
7991           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7992                                                SVI->getOperand(0), DestTy, &CI);
7993           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7994                                                SVI->getOperand(1), DestTy, &CI);
7995           // Return a new shuffle vector.  Use the same element ID's, as we
7996           // know the vector types match #elts.
7997           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7998         }
7999       }
8000     }
8001   }
8002   return 0;
8003 }
8004
8005 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8006 ///   %C = or %A, %B
8007 ///   %D = select %cond, %C, %A
8008 /// into:
8009 ///   %C = select %cond, %B, 0
8010 ///   %D = or %A, %C
8011 ///
8012 /// Assuming that the specified instruction is an operand to the select, return
8013 /// a bitmask indicating which operands of this instruction are foldable if they
8014 /// equal the other incoming value of the select.
8015 ///
8016 static unsigned GetSelectFoldableOperands(Instruction *I) {
8017   switch (I->getOpcode()) {
8018   case Instruction::Add:
8019   case Instruction::Mul:
8020   case Instruction::And:
8021   case Instruction::Or:
8022   case Instruction::Xor:
8023     return 3;              // Can fold through either operand.
8024   case Instruction::Sub:   // Can only fold on the amount subtracted.
8025   case Instruction::Shl:   // Can only fold on the shift amount.
8026   case Instruction::LShr:
8027   case Instruction::AShr:
8028     return 1;
8029   default:
8030     return 0;              // Cannot fold
8031   }
8032 }
8033
8034 /// GetSelectFoldableConstant - For the same transformation as the previous
8035 /// function, return the identity constant that goes into the select.
8036 static Constant *GetSelectFoldableConstant(Instruction *I) {
8037   switch (I->getOpcode()) {
8038   default: assert(0 && "This cannot happen!"); abort();
8039   case Instruction::Add:
8040   case Instruction::Sub:
8041   case Instruction::Or:
8042   case Instruction::Xor:
8043   case Instruction::Shl:
8044   case Instruction::LShr:
8045   case Instruction::AShr:
8046     return Constant::getNullValue(I->getType());
8047   case Instruction::And:
8048     return Constant::getAllOnesValue(I->getType());
8049   case Instruction::Mul:
8050     return ConstantInt::get(I->getType(), 1);
8051   }
8052 }
8053
8054 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8055 /// have the same opcode and only one use each.  Try to simplify this.
8056 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8057                                           Instruction *FI) {
8058   if (TI->getNumOperands() == 1) {
8059     // If this is a non-volatile load or a cast from the same type,
8060     // merge.
8061     if (TI->isCast()) {
8062       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8063         return 0;
8064     } else {
8065       return 0;  // unknown unary op.
8066     }
8067
8068     // Fold this by inserting a select from the input values.
8069     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8070                                            FI->getOperand(0), SI.getName()+".v");
8071     InsertNewInstBefore(NewSI, SI);
8072     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8073                             TI->getType());
8074   }
8075
8076   // Only handle binary operators here.
8077   if (!isa<BinaryOperator>(TI))
8078     return 0;
8079
8080   // Figure out if the operations have any operands in common.
8081   Value *MatchOp, *OtherOpT, *OtherOpF;
8082   bool MatchIsOpZero;
8083   if (TI->getOperand(0) == FI->getOperand(0)) {
8084     MatchOp  = TI->getOperand(0);
8085     OtherOpT = TI->getOperand(1);
8086     OtherOpF = FI->getOperand(1);
8087     MatchIsOpZero = true;
8088   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8089     MatchOp  = TI->getOperand(1);
8090     OtherOpT = TI->getOperand(0);
8091     OtherOpF = FI->getOperand(0);
8092     MatchIsOpZero = false;
8093   } else if (!TI->isCommutative()) {
8094     return 0;
8095   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8096     MatchOp  = TI->getOperand(0);
8097     OtherOpT = TI->getOperand(1);
8098     OtherOpF = FI->getOperand(0);
8099     MatchIsOpZero = true;
8100   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8101     MatchOp  = TI->getOperand(1);
8102     OtherOpT = TI->getOperand(0);
8103     OtherOpF = FI->getOperand(1);
8104     MatchIsOpZero = true;
8105   } else {
8106     return 0;
8107   }
8108
8109   // If we reach here, they do have operations in common.
8110   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8111                                          OtherOpF, SI.getName()+".v");
8112   InsertNewInstBefore(NewSI, SI);
8113
8114   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8115     if (MatchIsOpZero)
8116       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8117     else
8118       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8119   }
8120   assert(0 && "Shouldn't get here");
8121   return 0;
8122 }
8123
8124 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8125   Value *CondVal = SI.getCondition();
8126   Value *TrueVal = SI.getTrueValue();
8127   Value *FalseVal = SI.getFalseValue();
8128
8129   // select true, X, Y  -> X
8130   // select false, X, Y -> Y
8131   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8132     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8133
8134   // select C, X, X -> X
8135   if (TrueVal == FalseVal)
8136     return ReplaceInstUsesWith(SI, TrueVal);
8137
8138   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8139     return ReplaceInstUsesWith(SI, FalseVal);
8140   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8141     return ReplaceInstUsesWith(SI, TrueVal);
8142   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8143     if (isa<Constant>(TrueVal))
8144       return ReplaceInstUsesWith(SI, TrueVal);
8145     else
8146       return ReplaceInstUsesWith(SI, FalseVal);
8147   }
8148
8149   if (SI.getType() == Type::Int1Ty) {
8150     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8151       if (C->getZExtValue()) {
8152         // Change: A = select B, true, C --> A = or B, C
8153         return BinaryOperator::CreateOr(CondVal, FalseVal);
8154       } else {
8155         // Change: A = select B, false, C --> A = and !B, C
8156         Value *NotCond =
8157           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8158                                              "not."+CondVal->getName()), SI);
8159         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8160       }
8161     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8162       if (C->getZExtValue() == false) {
8163         // Change: A = select B, C, false --> A = and B, C
8164         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8165       } else {
8166         // Change: A = select B, C, true --> A = or !B, C
8167         Value *NotCond =
8168           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8169                                              "not."+CondVal->getName()), SI);
8170         return BinaryOperator::CreateOr(NotCond, TrueVal);
8171       }
8172     }
8173     
8174     // select a, b, a  -> a&b
8175     // select a, a, b  -> a|b
8176     if (CondVal == TrueVal)
8177       return BinaryOperator::CreateOr(CondVal, FalseVal);
8178     else if (CondVal == FalseVal)
8179       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8180   }
8181
8182   // Selecting between two integer constants?
8183   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8184     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8185       // select C, 1, 0 -> zext C to int
8186       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8187         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8188       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8189         // select C, 0, 1 -> zext !C to int
8190         Value *NotCond =
8191           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8192                                                "not."+CondVal->getName()), SI);
8193         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8194       }
8195       
8196       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8197
8198       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8199
8200         // (x <s 0) ? -1 : 0 -> ashr x, 31
8201         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8202           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8203             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8204               // The comparison constant and the result are not neccessarily the
8205               // same width. Make an all-ones value by inserting a AShr.
8206               Value *X = IC->getOperand(0);
8207               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8208               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8209               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8210                                                         ShAmt, "ones");
8211               InsertNewInstBefore(SRA, SI);
8212               
8213               // Finally, convert to the type of the select RHS.  We figure out
8214               // if this requires a SExt, Trunc or BitCast based on the sizes.
8215               Instruction::CastOps opc = Instruction::BitCast;
8216               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8217               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8218               if (SRASize < SISize)
8219                 opc = Instruction::SExt;
8220               else if (SRASize > SISize)
8221                 opc = Instruction::Trunc;
8222               return CastInst::Create(opc, SRA, SI.getType());
8223             }
8224           }
8225
8226
8227         // If one of the constants is zero (we know they can't both be) and we
8228         // have an icmp instruction with zero, and we have an 'and' with the
8229         // non-constant value, eliminate this whole mess.  This corresponds to
8230         // cases like this: ((X & 27) ? 27 : 0)
8231         if (TrueValC->isZero() || FalseValC->isZero())
8232           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8233               cast<Constant>(IC->getOperand(1))->isNullValue())
8234             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8235               if (ICA->getOpcode() == Instruction::And &&
8236                   isa<ConstantInt>(ICA->getOperand(1)) &&
8237                   (ICA->getOperand(1) == TrueValC ||
8238                    ICA->getOperand(1) == FalseValC) &&
8239                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8240                 // Okay, now we know that everything is set up, we just don't
8241                 // know whether we have a icmp_ne or icmp_eq and whether the 
8242                 // true or false val is the zero.
8243                 bool ShouldNotVal = !TrueValC->isZero();
8244                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8245                 Value *V = ICA;
8246                 if (ShouldNotVal)
8247                   V = InsertNewInstBefore(BinaryOperator::Create(
8248                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8249                 return ReplaceInstUsesWith(SI, V);
8250               }
8251       }
8252     }
8253
8254   // See if we are selecting two values based on a comparison of the two values.
8255   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8256     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8257       // Transform (X == Y) ? X : Y  -> Y
8258       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8259         // This is not safe in general for floating point:  
8260         // consider X== -0, Y== +0.
8261         // It becomes safe if either operand is a nonzero constant.
8262         ConstantFP *CFPt, *CFPf;
8263         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8264               !CFPt->getValueAPF().isZero()) ||
8265             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8266              !CFPf->getValueAPF().isZero()))
8267         return ReplaceInstUsesWith(SI, FalseVal);
8268       }
8269       // Transform (X != Y) ? X : Y  -> X
8270       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8271         return ReplaceInstUsesWith(SI, TrueVal);
8272       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8273
8274     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8275       // Transform (X == Y) ? Y : X  -> X
8276       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8277         // This is not safe in general for floating point:  
8278         // consider X== -0, Y== +0.
8279         // It becomes safe if either operand is a nonzero constant.
8280         ConstantFP *CFPt, *CFPf;
8281         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8282               !CFPt->getValueAPF().isZero()) ||
8283             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8284              !CFPf->getValueAPF().isZero()))
8285           return ReplaceInstUsesWith(SI, FalseVal);
8286       }
8287       // Transform (X != Y) ? Y : X  -> Y
8288       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8289         return ReplaceInstUsesWith(SI, TrueVal);
8290       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8291     }
8292   }
8293
8294   // See if we are selecting two values based on a comparison of the two values.
8295   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8296     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8297       // Transform (X == Y) ? X : Y  -> Y
8298       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8299         return ReplaceInstUsesWith(SI, FalseVal);
8300       // Transform (X != Y) ? X : Y  -> X
8301       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8302         return ReplaceInstUsesWith(SI, TrueVal);
8303       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8304
8305     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8306       // Transform (X == Y) ? Y : X  -> X
8307       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8308         return ReplaceInstUsesWith(SI, FalseVal);
8309       // Transform (X != Y) ? Y : X  -> Y
8310       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8311         return ReplaceInstUsesWith(SI, TrueVal);
8312       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8313     }
8314   }
8315
8316   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8317     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8318       if (TI->hasOneUse() && FI->hasOneUse()) {
8319         Instruction *AddOp = 0, *SubOp = 0;
8320
8321         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8322         if (TI->getOpcode() == FI->getOpcode())
8323           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8324             return IV;
8325
8326         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8327         // even legal for FP.
8328         if (TI->getOpcode() == Instruction::Sub &&
8329             FI->getOpcode() == Instruction::Add) {
8330           AddOp = FI; SubOp = TI;
8331         } else if (FI->getOpcode() == Instruction::Sub &&
8332                    TI->getOpcode() == Instruction::Add) {
8333           AddOp = TI; SubOp = FI;
8334         }
8335
8336         if (AddOp) {
8337           Value *OtherAddOp = 0;
8338           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8339             OtherAddOp = AddOp->getOperand(1);
8340           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8341             OtherAddOp = AddOp->getOperand(0);
8342           }
8343
8344           if (OtherAddOp) {
8345             // So at this point we know we have (Y -> OtherAddOp):
8346             //        select C, (add X, Y), (sub X, Z)
8347             Value *NegVal;  // Compute -Z
8348             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8349               NegVal = ConstantExpr::getNeg(C);
8350             } else {
8351               NegVal = InsertNewInstBefore(
8352                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8353             }
8354
8355             Value *NewTrueOp = OtherAddOp;
8356             Value *NewFalseOp = NegVal;
8357             if (AddOp != TI)
8358               std::swap(NewTrueOp, NewFalseOp);
8359             Instruction *NewSel =
8360               SelectInst::Create(CondVal, NewTrueOp,
8361                                  NewFalseOp, SI.getName() + ".p");
8362
8363             NewSel = InsertNewInstBefore(NewSel, SI);
8364             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8365           }
8366         }
8367       }
8368
8369   // See if we can fold the select into one of our operands.
8370   if (SI.getType()->isInteger()) {
8371     // See the comment above GetSelectFoldableOperands for a description of the
8372     // transformation we are doing here.
8373     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8374       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8375           !isa<Constant>(FalseVal))
8376         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8377           unsigned OpToFold = 0;
8378           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8379             OpToFold = 1;
8380           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8381             OpToFold = 2;
8382           }
8383
8384           if (OpToFold) {
8385             Constant *C = GetSelectFoldableConstant(TVI);
8386             Instruction *NewSel =
8387               SelectInst::Create(SI.getCondition(),
8388                                  TVI->getOperand(2-OpToFold), C);
8389             InsertNewInstBefore(NewSel, SI);
8390             NewSel->takeName(TVI);
8391             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8392               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8393             else {
8394               assert(0 && "Unknown instruction!!");
8395             }
8396           }
8397         }
8398
8399     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8400       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8401           !isa<Constant>(TrueVal))
8402         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8403           unsigned OpToFold = 0;
8404           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8405             OpToFold = 1;
8406           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8407             OpToFold = 2;
8408           }
8409
8410           if (OpToFold) {
8411             Constant *C = GetSelectFoldableConstant(FVI);
8412             Instruction *NewSel =
8413               SelectInst::Create(SI.getCondition(), C,
8414                                  FVI->getOperand(2-OpToFold));
8415             InsertNewInstBefore(NewSel, SI);
8416             NewSel->takeName(FVI);
8417             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8418               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8419             else
8420               assert(0 && "Unknown instruction!!");
8421           }
8422         }
8423   }
8424
8425   if (BinaryOperator::isNot(CondVal)) {
8426     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8427     SI.setOperand(1, FalseVal);
8428     SI.setOperand(2, TrueVal);
8429     return &SI;
8430   }
8431
8432   return 0;
8433 }
8434
8435 /// EnforceKnownAlignment - If the specified pointer points to an object that
8436 /// we control, modify the object's alignment to PrefAlign. This isn't
8437 /// often possible though. If alignment is important, a more reliable approach
8438 /// is to simply align all global variables and allocation instructions to
8439 /// their preferred alignment from the beginning.
8440 ///
8441 static unsigned EnforceKnownAlignment(Value *V,
8442                                       unsigned Align, unsigned PrefAlign) {
8443
8444   User *U = dyn_cast<User>(V);
8445   if (!U) return Align;
8446
8447   switch (getOpcode(U)) {
8448   default: break;
8449   case Instruction::BitCast:
8450     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8451   case Instruction::GetElementPtr: {
8452     // If all indexes are zero, it is just the alignment of the base pointer.
8453     bool AllZeroOperands = true;
8454     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8455       if (!isa<Constant>(*i) ||
8456           !cast<Constant>(*i)->isNullValue()) {
8457         AllZeroOperands = false;
8458         break;
8459       }
8460
8461     if (AllZeroOperands) {
8462       // Treat this like a bitcast.
8463       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8464     }
8465     break;
8466   }
8467   }
8468
8469   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8470     // If there is a large requested alignment and we can, bump up the alignment
8471     // of the global.
8472     if (!GV->isDeclaration()) {
8473       GV->setAlignment(PrefAlign);
8474       Align = PrefAlign;
8475     }
8476   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8477     // If there is a requested alignment and if this is an alloca, round up.  We
8478     // don't do this for malloc, because some systems can't respect the request.
8479     if (isa<AllocaInst>(AI)) {
8480       AI->setAlignment(PrefAlign);
8481       Align = PrefAlign;
8482     }
8483   }
8484
8485   return Align;
8486 }
8487
8488 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8489 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8490 /// and it is more than the alignment of the ultimate object, see if we can
8491 /// increase the alignment of the ultimate object, making this check succeed.
8492 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8493                                                   unsigned PrefAlign) {
8494   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8495                       sizeof(PrefAlign) * CHAR_BIT;
8496   APInt Mask = APInt::getAllOnesValue(BitWidth);
8497   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8498   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8499   unsigned TrailZ = KnownZero.countTrailingOnes();
8500   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8501
8502   if (PrefAlign > Align)
8503     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8504   
8505     // We don't need to make any adjustment.
8506   return Align;
8507 }
8508
8509 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8510   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8511   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8512   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8513   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8514
8515   if (CopyAlign < MinAlign) {
8516     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8517     return MI;
8518   }
8519   
8520   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8521   // load/store.
8522   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8523   if (MemOpLength == 0) return 0;
8524   
8525   // Source and destination pointer types are always "i8*" for intrinsic.  See
8526   // if the size is something we can handle with a single primitive load/store.
8527   // A single load+store correctly handles overlapping memory in the memmove
8528   // case.
8529   unsigned Size = MemOpLength->getZExtValue();
8530   if (Size == 0) return MI;  // Delete this mem transfer.
8531   
8532   if (Size > 8 || (Size&(Size-1)))
8533     return 0;  // If not 1/2/4/8 bytes, exit.
8534   
8535   // Use an integer load+store unless we can find something better.
8536   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8537   
8538   // Memcpy forces the use of i8* for the source and destination.  That means
8539   // that if you're using memcpy to move one double around, you'll get a cast
8540   // from double* to i8*.  We'd much rather use a double load+store rather than
8541   // an i64 load+store, here because this improves the odds that the source or
8542   // dest address will be promotable.  See if we can find a better type than the
8543   // integer datatype.
8544   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8545     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8546     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8547       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8548       // down through these levels if so.
8549       while (!SrcETy->isSingleValueType()) {
8550         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8551           if (STy->getNumElements() == 1)
8552             SrcETy = STy->getElementType(0);
8553           else
8554             break;
8555         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8556           if (ATy->getNumElements() == 1)
8557             SrcETy = ATy->getElementType();
8558           else
8559             break;
8560         } else
8561           break;
8562       }
8563       
8564       if (SrcETy->isSingleValueType())
8565         NewPtrTy = PointerType::getUnqual(SrcETy);
8566     }
8567   }
8568   
8569   
8570   // If the memcpy/memmove provides better alignment info than we can
8571   // infer, use it.
8572   SrcAlign = std::max(SrcAlign, CopyAlign);
8573   DstAlign = std::max(DstAlign, CopyAlign);
8574   
8575   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8576   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8577   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8578   InsertNewInstBefore(L, *MI);
8579   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8580
8581   // Set the size of the copy to 0, it will be deleted on the next iteration.
8582   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8583   return MI;
8584 }
8585
8586 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8587   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8588   if (MI->getAlignment()->getZExtValue() < Alignment) {
8589     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8590     return MI;
8591   }
8592   
8593   // Extract the length and alignment and fill if they are constant.
8594   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8595   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8596   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8597     return 0;
8598   uint64_t Len = LenC->getZExtValue();
8599   Alignment = MI->getAlignment()->getZExtValue();
8600   
8601   // If the length is zero, this is a no-op
8602   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8603   
8604   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8605   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8606     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
8607     
8608     Value *Dest = MI->getDest();
8609     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8610
8611     // Alignment 0 is identity for alignment 1 for memset, but not store.
8612     if (Alignment == 0) Alignment = 1;
8613     
8614     // Extract the fill value and store.
8615     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8616     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8617                                       Alignment), *MI);
8618     
8619     // Set the size of the copy to 0, it will be deleted on the next iteration.
8620     MI->setLength(Constant::getNullValue(LenC->getType()));
8621     return MI;
8622   }
8623
8624   return 0;
8625 }
8626
8627
8628 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8629 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8630 /// the heavy lifting.
8631 ///
8632 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8633   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8634   if (!II) return visitCallSite(&CI);
8635   
8636   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8637   // visitCallSite.
8638   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8639     bool Changed = false;
8640
8641     // memmove/cpy/set of zero bytes is a noop.
8642     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8643       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8644
8645       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8646         if (CI->getZExtValue() == 1) {
8647           // Replace the instruction with just byte operations.  We would
8648           // transform other cases to loads/stores, but we don't know if
8649           // alignment is sufficient.
8650         }
8651     }
8652
8653     // If we have a memmove and the source operation is a constant global,
8654     // then the source and dest pointers can't alias, so we can change this
8655     // into a call to memcpy.
8656     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8657       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8658         if (GVSrc->isConstant()) {
8659           Module *M = CI.getParent()->getParent()->getParent();
8660           Intrinsic::ID MemCpyID;
8661           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8662             MemCpyID = Intrinsic::memcpy_i32;
8663           else
8664             MemCpyID = Intrinsic::memcpy_i64;
8665           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8666           Changed = true;
8667         }
8668
8669       // memmove(x,x,size) -> noop.
8670       if (MMI->getSource() == MMI->getDest())
8671         return EraseInstFromFunction(CI);
8672     }
8673
8674     // If we can determine a pointer alignment that is bigger than currently
8675     // set, update the alignment.
8676     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8677       if (Instruction *I = SimplifyMemTransfer(MI))
8678         return I;
8679     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8680       if (Instruction *I = SimplifyMemSet(MSI))
8681         return I;
8682     }
8683           
8684     if (Changed) return II;
8685   }
8686   
8687   switch (II->getIntrinsicID()) {
8688   default: break;
8689   case Intrinsic::bswap:
8690     // bswap(bswap(x)) -> x
8691     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8692       if (Operand->getIntrinsicID() == Intrinsic::bswap)
8693         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8694     break;
8695   case Intrinsic::ppc_altivec_lvx:
8696   case Intrinsic::ppc_altivec_lvxl:
8697   case Intrinsic::x86_sse_loadu_ps:
8698   case Intrinsic::x86_sse2_loadu_pd:
8699   case Intrinsic::x86_sse2_loadu_dq:
8700     // Turn PPC lvx     -> load if the pointer is known aligned.
8701     // Turn X86 loadups -> load if the pointer is known aligned.
8702     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8703       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8704                                        PointerType::getUnqual(II->getType()),
8705                                        CI);
8706       return new LoadInst(Ptr);
8707     }
8708     break;
8709   case Intrinsic::ppc_altivec_stvx:
8710   case Intrinsic::ppc_altivec_stvxl:
8711     // Turn stvx -> store if the pointer is known aligned.
8712     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8713       const Type *OpPtrTy = 
8714         PointerType::getUnqual(II->getOperand(1)->getType());
8715       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8716       return new StoreInst(II->getOperand(1), Ptr);
8717     }
8718     break;
8719   case Intrinsic::x86_sse_storeu_ps:
8720   case Intrinsic::x86_sse2_storeu_pd:
8721   case Intrinsic::x86_sse2_storeu_dq:
8722     // Turn X86 storeu -> store if the pointer is known aligned.
8723     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8724       const Type *OpPtrTy = 
8725         PointerType::getUnqual(II->getOperand(2)->getType());
8726       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8727       return new StoreInst(II->getOperand(2), Ptr);
8728     }
8729     break;
8730     
8731   case Intrinsic::x86_sse_cvttss2si: {
8732     // These intrinsics only demands the 0th element of its input vector.  If
8733     // we can simplify the input based on that, do so now.
8734     uint64_t UndefElts;
8735     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8736                                               UndefElts)) {
8737       II->setOperand(1, V);
8738       return II;
8739     }
8740     break;
8741   }
8742     
8743   case Intrinsic::ppc_altivec_vperm:
8744     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8745     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8746       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8747       
8748       // Check that all of the elements are integer constants or undefs.
8749       bool AllEltsOk = true;
8750       for (unsigned i = 0; i != 16; ++i) {
8751         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8752             !isa<UndefValue>(Mask->getOperand(i))) {
8753           AllEltsOk = false;
8754           break;
8755         }
8756       }
8757       
8758       if (AllEltsOk) {
8759         // Cast the input vectors to byte vectors.
8760         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8761         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8762         Value *Result = UndefValue::get(Op0->getType());
8763         
8764         // Only extract each element once.
8765         Value *ExtractedElts[32];
8766         memset(ExtractedElts, 0, sizeof(ExtractedElts));
8767         
8768         for (unsigned i = 0; i != 16; ++i) {
8769           if (isa<UndefValue>(Mask->getOperand(i)))
8770             continue;
8771           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8772           Idx &= 31;  // Match the hardware behavior.
8773           
8774           if (ExtractedElts[Idx] == 0) {
8775             Instruction *Elt = 
8776               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8777             InsertNewInstBefore(Elt, CI);
8778             ExtractedElts[Idx] = Elt;
8779           }
8780         
8781           // Insert this value into the result vector.
8782           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8783                                              i, "tmp");
8784           InsertNewInstBefore(cast<Instruction>(Result), CI);
8785         }
8786         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8787       }
8788     }
8789     break;
8790
8791   case Intrinsic::stackrestore: {
8792     // If the save is right next to the restore, remove the restore.  This can
8793     // happen when variable allocas are DCE'd.
8794     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8795       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8796         BasicBlock::iterator BI = SS;
8797         if (&*++BI == II)
8798           return EraseInstFromFunction(CI);
8799       }
8800     }
8801     
8802     // Scan down this block to see if there is another stack restore in the
8803     // same block without an intervening call/alloca.
8804     BasicBlock::iterator BI = II;
8805     TerminatorInst *TI = II->getParent()->getTerminator();
8806     bool CannotRemove = false;
8807     for (++BI; &*BI != TI; ++BI) {
8808       if (isa<AllocaInst>(BI)) {
8809         CannotRemove = true;
8810         break;
8811       }
8812       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8813         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8814           // If there is a stackrestore below this one, remove this one.
8815           if (II->getIntrinsicID() == Intrinsic::stackrestore)
8816             return EraseInstFromFunction(CI);
8817           // Otherwise, ignore the intrinsic.
8818         } else {
8819           // If we found a non-intrinsic call, we can't remove the stack
8820           // restore.
8821           CannotRemove = true;
8822           break;
8823         }
8824       }
8825     }
8826     
8827     // If the stack restore is in a return/unwind block and if there are no
8828     // allocas or calls between the restore and the return, nuke the restore.
8829     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8830       return EraseInstFromFunction(CI);
8831     break;
8832   }
8833   }
8834
8835   return visitCallSite(II);
8836 }
8837
8838 // InvokeInst simplification
8839 //
8840 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8841   return visitCallSite(&II);
8842 }
8843
8844 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
8845 /// passed through the varargs area, we can eliminate the use of the cast.
8846 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8847                                          const CastInst * const CI,
8848                                          const TargetData * const TD,
8849                                          const int ix) {
8850   if (!CI->isLosslessCast())
8851     return false;
8852
8853   // The size of ByVal arguments is derived from the type, so we
8854   // can't change to a type with a different size.  If the size were
8855   // passed explicitly we could avoid this check.
8856   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8857     return true;
8858
8859   const Type* SrcTy = 
8860             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8861   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8862   if (!SrcTy->isSized() || !DstTy->isSized())
8863     return false;
8864   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8865     return false;
8866   return true;
8867 }
8868
8869 // visitCallSite - Improvements for call and invoke instructions.
8870 //
8871 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8872   bool Changed = false;
8873
8874   // If the callee is a constexpr cast of a function, attempt to move the cast
8875   // to the arguments of the call/invoke.
8876   if (transformConstExprCastCall(CS)) return 0;
8877
8878   Value *Callee = CS.getCalledValue();
8879
8880   if (Function *CalleeF = dyn_cast<Function>(Callee))
8881     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8882       Instruction *OldCall = CS.getInstruction();
8883       // If the call and callee calling conventions don't match, this call must
8884       // be unreachable, as the call is undefined.
8885       new StoreInst(ConstantInt::getTrue(),
8886                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8887                                     OldCall);
8888       if (!OldCall->use_empty())
8889         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8890       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8891         return EraseInstFromFunction(*OldCall);
8892       return 0;
8893     }
8894
8895   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8896     // This instruction is not reachable, just remove it.  We insert a store to
8897     // undef so that we know that this code is not reachable, despite the fact
8898     // that we can't modify the CFG here.
8899     new StoreInst(ConstantInt::getTrue(),
8900                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8901                   CS.getInstruction());
8902
8903     if (!CS.getInstruction()->use_empty())
8904       CS.getInstruction()->
8905         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8906
8907     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8908       // Don't break the CFG, insert a dummy cond branch.
8909       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8910                          ConstantInt::getTrue(), II);
8911     }
8912     return EraseInstFromFunction(*CS.getInstruction());
8913   }
8914
8915   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8916     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8917       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8918         return transformCallThroughTrampoline(CS);
8919
8920   const PointerType *PTy = cast<PointerType>(Callee->getType());
8921   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8922   if (FTy->isVarArg()) {
8923     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8924     // See if we can optimize any arguments passed through the varargs area of
8925     // the call.
8926     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8927            E = CS.arg_end(); I != E; ++I, ++ix) {
8928       CastInst *CI = dyn_cast<CastInst>(*I);
8929       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8930         *I = CI->getOperand(0);
8931         Changed = true;
8932       }
8933     }
8934   }
8935
8936   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8937     // Inline asm calls cannot throw - mark them 'nounwind'.
8938     CS.setDoesNotThrow();
8939     Changed = true;
8940   }
8941
8942   return Changed ? CS.getInstruction() : 0;
8943 }
8944
8945 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8946 // attempt to move the cast to the arguments of the call/invoke.
8947 //
8948 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8949   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8950   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8951   if (CE->getOpcode() != Instruction::BitCast || 
8952       !isa<Function>(CE->getOperand(0)))
8953     return false;
8954   Function *Callee = cast<Function>(CE->getOperand(0));
8955   Instruction *Caller = CS.getInstruction();
8956   const PAListPtr &CallerPAL = CS.getParamAttrs();
8957
8958   // Okay, this is a cast from a function to a different type.  Unless doing so
8959   // would cause a type conversion of one of our arguments, change this call to
8960   // be a direct call with arguments casted to the appropriate types.
8961   //
8962   const FunctionType *FT = Callee->getFunctionType();
8963   const Type *OldRetTy = Caller->getType();
8964   const Type *NewRetTy = FT->getReturnType();
8965
8966   if (isa<StructType>(NewRetTy))
8967     return false; // TODO: Handle multiple return values.
8968
8969   // Check to see if we are changing the return type...
8970   if (OldRetTy != NewRetTy) {
8971     if (Callee->isDeclaration() &&
8972         // Conversion is ok if changing from one pointer type to another or from
8973         // a pointer to an integer of the same size.
8974         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8975           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
8976       return false;   // Cannot transform this return value.
8977
8978     if (!Caller->use_empty() &&
8979         // void -> non-void is handled specially
8980         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8981       return false;   // Cannot transform this return value.
8982
8983     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8984       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8985       if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8986         return false;   // Attribute not compatible with transformed value.
8987     }
8988
8989     // If the callsite is an invoke instruction, and the return value is used by
8990     // a PHI node in a successor, we cannot change the return type of the call
8991     // because there is no place to put the cast instruction (without breaking
8992     // the critical edge).  Bail out in this case.
8993     if (!Caller->use_empty())
8994       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8995         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8996              UI != E; ++UI)
8997           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8998             if (PN->getParent() == II->getNormalDest() ||
8999                 PN->getParent() == II->getUnwindDest())
9000               return false;
9001   }
9002
9003   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9004   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9005
9006   CallSite::arg_iterator AI = CS.arg_begin();
9007   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9008     const Type *ParamTy = FT->getParamType(i);
9009     const Type *ActTy = (*AI)->getType();
9010
9011     if (!CastInst::isCastable(ActTy, ParamTy))
9012       return false;   // Cannot transform this parameter value.
9013
9014     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9015       return false;   // Attribute not compatible with transformed value.
9016
9017     // Converting from one pointer type to another or between a pointer and an
9018     // integer of the same size is safe even if we do not have a body.
9019     bool isConvertible = ActTy == ParamTy ||
9020       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9021        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9022     if (Callee->isDeclaration() && !isConvertible) return false;
9023   }
9024
9025   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9026       Callee->isDeclaration())
9027     return false;   // Do not delete arguments unless we have a function body.
9028
9029   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9030       !CallerPAL.isEmpty())
9031     // In this case we have more arguments than the new function type, but we
9032     // won't be dropping them.  Check that these extra arguments have attributes
9033     // that are compatible with being a vararg call argument.
9034     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9035       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9036         break;
9037       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9038       if (PAttrs & ParamAttr::VarArgsIncompatible)
9039         return false;
9040     }
9041
9042   // Okay, we decided that this is a safe thing to do: go ahead and start
9043   // inserting cast instructions as necessary...
9044   std::vector<Value*> Args;
9045   Args.reserve(NumActualArgs);
9046   SmallVector<ParamAttrsWithIndex, 8> attrVec;
9047   attrVec.reserve(NumCommonArgs);
9048
9049   // Get any return attributes.
9050   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9051
9052   // If the return value is not being used, the type may not be compatible
9053   // with the existing attributes.  Wipe out any problematic attributes.
9054   RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
9055
9056   // Add the new return attributes.
9057   if (RAttrs)
9058     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
9059
9060   AI = CS.arg_begin();
9061   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9062     const Type *ParamTy = FT->getParamType(i);
9063     if ((*AI)->getType() == ParamTy) {
9064       Args.push_back(*AI);
9065     } else {
9066       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9067           false, ParamTy, false);
9068       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9069       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9070     }
9071
9072     // Add any parameter attributes.
9073     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9074       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9075   }
9076
9077   // If the function takes more arguments than the call was taking, add them
9078   // now...
9079   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9080     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9081
9082   // If we are removing arguments to the function, emit an obnoxious warning...
9083   if (FT->getNumParams() < NumActualArgs) {
9084     if (!FT->isVarArg()) {
9085       cerr << "WARNING: While resolving call to function '"
9086            << Callee->getName() << "' arguments were dropped!\n";
9087     } else {
9088       // Add all of the arguments in their promoted form to the arg list...
9089       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9090         const Type *PTy = getPromotedType((*AI)->getType());
9091         if (PTy != (*AI)->getType()) {
9092           // Must promote to pass through va_arg area!
9093           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9094                                                                 PTy, false);
9095           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9096           InsertNewInstBefore(Cast, *Caller);
9097           Args.push_back(Cast);
9098         } else {
9099           Args.push_back(*AI);
9100         }
9101
9102         // Add any parameter attributes.
9103         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9104           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9105       }
9106     }
9107   }
9108
9109   if (NewRetTy == Type::VoidTy)
9110     Caller->setName("");   // Void type should not have a name.
9111
9112   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9113
9114   Instruction *NC;
9115   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9116     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9117                             Args.begin(), Args.end(),
9118                             Caller->getName(), Caller);
9119     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9120     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9121   } else {
9122     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9123                           Caller->getName(), Caller);
9124     CallInst *CI = cast<CallInst>(Caller);
9125     if (CI->isTailCall())
9126       cast<CallInst>(NC)->setTailCall();
9127     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9128     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9129   }
9130
9131   // Insert a cast of the return type as necessary.
9132   Value *NV = NC;
9133   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9134     if (NV->getType() != Type::VoidTy) {
9135       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9136                                                             OldRetTy, false);
9137       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9138
9139       // If this is an invoke instruction, we should insert it after the first
9140       // non-phi, instruction in the normal successor block.
9141       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9142         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9143         InsertNewInstBefore(NC, *I);
9144       } else {
9145         // Otherwise, it's a call, just insert cast right after the call instr
9146         InsertNewInstBefore(NC, *Caller);
9147       }
9148       AddUsersToWorkList(*Caller);
9149     } else {
9150       NV = UndefValue::get(Caller->getType());
9151     }
9152   }
9153
9154   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9155     Caller->replaceAllUsesWith(NV);
9156   Caller->eraseFromParent();
9157   RemoveFromWorkList(Caller);
9158   return true;
9159 }
9160
9161 // transformCallThroughTrampoline - Turn a call to a function created by the
9162 // init_trampoline intrinsic into a direct call to the underlying function.
9163 //
9164 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9165   Value *Callee = CS.getCalledValue();
9166   const PointerType *PTy = cast<PointerType>(Callee->getType());
9167   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9168   const PAListPtr &Attrs = CS.getParamAttrs();
9169
9170   // If the call already has the 'nest' attribute somewhere then give up -
9171   // otherwise 'nest' would occur twice after splicing in the chain.
9172   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9173     return 0;
9174
9175   IntrinsicInst *Tramp =
9176     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9177
9178   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9179   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9180   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9181
9182   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9183   if (!NestAttrs.isEmpty()) {
9184     unsigned NestIdx = 1;
9185     const Type *NestTy = 0;
9186     ParameterAttributes NestAttr = ParamAttr::None;
9187
9188     // Look for a parameter marked with the 'nest' attribute.
9189     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9190          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9191       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9192         // Record the parameter type and any other attributes.
9193         NestTy = *I;
9194         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9195         break;
9196       }
9197
9198     if (NestTy) {
9199       Instruction *Caller = CS.getInstruction();
9200       std::vector<Value*> NewArgs;
9201       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9202
9203       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9204       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9205
9206       // Insert the nest argument into the call argument list, which may
9207       // mean appending it.  Likewise for attributes.
9208
9209       // Add any function result attributes.
9210       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9211         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9212
9213       {
9214         unsigned Idx = 1;
9215         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9216         do {
9217           if (Idx == NestIdx) {
9218             // Add the chain argument and attributes.
9219             Value *NestVal = Tramp->getOperand(3);
9220             if (NestVal->getType() != NestTy)
9221               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9222             NewArgs.push_back(NestVal);
9223             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9224           }
9225
9226           if (I == E)
9227             break;
9228
9229           // Add the original argument and attributes.
9230           NewArgs.push_back(*I);
9231           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9232             NewAttrs.push_back
9233               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9234
9235           ++Idx, ++I;
9236         } while (1);
9237       }
9238
9239       // The trampoline may have been bitcast to a bogus type (FTy).
9240       // Handle this by synthesizing a new function type, equal to FTy
9241       // with the chain parameter inserted.
9242
9243       std::vector<const Type*> NewTypes;
9244       NewTypes.reserve(FTy->getNumParams()+1);
9245
9246       // Insert the chain's type into the list of parameter types, which may
9247       // mean appending it.
9248       {
9249         unsigned Idx = 1;
9250         FunctionType::param_iterator I = FTy->param_begin(),
9251           E = FTy->param_end();
9252
9253         do {
9254           if (Idx == NestIdx)
9255             // Add the chain's type.
9256             NewTypes.push_back(NestTy);
9257
9258           if (I == E)
9259             break;
9260
9261           // Add the original type.
9262           NewTypes.push_back(*I);
9263
9264           ++Idx, ++I;
9265         } while (1);
9266       }
9267
9268       // Replace the trampoline call with a direct call.  Let the generic
9269       // code sort out any function type mismatches.
9270       FunctionType *NewFTy =
9271         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9272       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9273         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9274       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9275
9276       Instruction *NewCaller;
9277       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9278         NewCaller = InvokeInst::Create(NewCallee,
9279                                        II->getNormalDest(), II->getUnwindDest(),
9280                                        NewArgs.begin(), NewArgs.end(),
9281                                        Caller->getName(), Caller);
9282         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9283         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9284       } else {
9285         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9286                                      Caller->getName(), Caller);
9287         if (cast<CallInst>(Caller)->isTailCall())
9288           cast<CallInst>(NewCaller)->setTailCall();
9289         cast<CallInst>(NewCaller)->
9290           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9291         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9292       }
9293       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9294         Caller->replaceAllUsesWith(NewCaller);
9295       Caller->eraseFromParent();
9296       RemoveFromWorkList(Caller);
9297       return 0;
9298     }
9299   }
9300
9301   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9302   // parameter, there is no need to adjust the argument list.  Let the generic
9303   // code sort out any function type mismatches.
9304   Constant *NewCallee =
9305     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9306   CS.setCalledFunction(NewCallee);
9307   return CS.getInstruction();
9308 }
9309
9310 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9311 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9312 /// and a single binop.
9313 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9314   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9315   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9316          isa<CmpInst>(FirstInst));
9317   unsigned Opc = FirstInst->getOpcode();
9318   Value *LHSVal = FirstInst->getOperand(0);
9319   Value *RHSVal = FirstInst->getOperand(1);
9320     
9321   const Type *LHSType = LHSVal->getType();
9322   const Type *RHSType = RHSVal->getType();
9323   
9324   // Scan to see if all operands are the same opcode, all have one use, and all
9325   // kill their operands (i.e. the operands have one use).
9326   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9327     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9328     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9329         // Verify type of the LHS matches so we don't fold cmp's of different
9330         // types or GEP's with different index types.
9331         I->getOperand(0)->getType() != LHSType ||
9332         I->getOperand(1)->getType() != RHSType)
9333       return 0;
9334
9335     // If they are CmpInst instructions, check their predicates
9336     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9337       if (cast<CmpInst>(I)->getPredicate() !=
9338           cast<CmpInst>(FirstInst)->getPredicate())
9339         return 0;
9340     
9341     // Keep track of which operand needs a phi node.
9342     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9343     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9344   }
9345   
9346   // Otherwise, this is safe to transform, determine if it is profitable.
9347
9348   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9349   // Indexes are often folded into load/store instructions, so we don't want to
9350   // hide them behind a phi.
9351   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9352     return 0;
9353   
9354   Value *InLHS = FirstInst->getOperand(0);
9355   Value *InRHS = FirstInst->getOperand(1);
9356   PHINode *NewLHS = 0, *NewRHS = 0;
9357   if (LHSVal == 0) {
9358     NewLHS = PHINode::Create(LHSType,
9359                              FirstInst->getOperand(0)->getName() + ".pn");
9360     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9361     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9362     InsertNewInstBefore(NewLHS, PN);
9363     LHSVal = NewLHS;
9364   }
9365   
9366   if (RHSVal == 0) {
9367     NewRHS = PHINode::Create(RHSType,
9368                              FirstInst->getOperand(1)->getName() + ".pn");
9369     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9370     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9371     InsertNewInstBefore(NewRHS, PN);
9372     RHSVal = NewRHS;
9373   }
9374   
9375   // Add all operands to the new PHIs.
9376   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9377     if (NewLHS) {
9378       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9379       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9380     }
9381     if (NewRHS) {
9382       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9383       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9384     }
9385   }
9386     
9387   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9388     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9389   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9390     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9391                            RHSVal);
9392   else {
9393     assert(isa<GetElementPtrInst>(FirstInst));
9394     return GetElementPtrInst::Create(LHSVal, RHSVal);
9395   }
9396 }
9397
9398 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9399 /// of the block that defines it.  This means that it must be obvious the value
9400 /// of the load is not changed from the point of the load to the end of the
9401 /// block it is in.
9402 ///
9403 /// Finally, it is safe, but not profitable, to sink a load targetting a
9404 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9405 /// to a register.
9406 static bool isSafeToSinkLoad(LoadInst *L) {
9407   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9408   
9409   for (++BBI; BBI != E; ++BBI)
9410     if (BBI->mayWriteToMemory())
9411       return false;
9412   
9413   // Check for non-address taken alloca.  If not address-taken already, it isn't
9414   // profitable to do this xform.
9415   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9416     bool isAddressTaken = false;
9417     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9418          UI != E; ++UI) {
9419       if (isa<LoadInst>(UI)) continue;
9420       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9421         // If storing TO the alloca, then the address isn't taken.
9422         if (SI->getOperand(1) == AI) continue;
9423       }
9424       isAddressTaken = true;
9425       break;
9426     }
9427     
9428     if (!isAddressTaken)
9429       return false;
9430   }
9431   
9432   return true;
9433 }
9434
9435
9436 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9437 // operator and they all are only used by the PHI, PHI together their
9438 // inputs, and do the operation once, to the result of the PHI.
9439 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9440   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9441
9442   // Scan the instruction, looking for input operations that can be folded away.
9443   // If all input operands to the phi are the same instruction (e.g. a cast from
9444   // the same type or "+42") we can pull the operation through the PHI, reducing
9445   // code size and simplifying code.
9446   Constant *ConstantOp = 0;
9447   const Type *CastSrcTy = 0;
9448   bool isVolatile = false;
9449   if (isa<CastInst>(FirstInst)) {
9450     CastSrcTy = FirstInst->getOperand(0)->getType();
9451   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9452     // Can fold binop, compare or shift here if the RHS is a constant, 
9453     // otherwise call FoldPHIArgBinOpIntoPHI.
9454     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9455     if (ConstantOp == 0)
9456       return FoldPHIArgBinOpIntoPHI(PN);
9457   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9458     isVolatile = LI->isVolatile();
9459     // We can't sink the load if the loaded value could be modified between the
9460     // load and the PHI.
9461     if (LI->getParent() != PN.getIncomingBlock(0) ||
9462         !isSafeToSinkLoad(LI))
9463       return 0;
9464     
9465     // If the PHI is of volatile loads and the load block has multiple
9466     // successors, sinking it would remove a load of the volatile value from
9467     // the path through the other successor.
9468     if (isVolatile &&
9469         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9470       return 0;
9471     
9472   } else if (isa<GetElementPtrInst>(FirstInst)) {
9473     if (FirstInst->getNumOperands() == 2)
9474       return FoldPHIArgBinOpIntoPHI(PN);
9475     // Can't handle general GEPs yet.
9476     return 0;
9477   } else {
9478     return 0;  // Cannot fold this operation.
9479   }
9480
9481   // Check to see if all arguments are the same operation.
9482   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9483     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9484     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9485     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9486       return 0;
9487     if (CastSrcTy) {
9488       if (I->getOperand(0)->getType() != CastSrcTy)
9489         return 0;  // Cast operation must match.
9490     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9491       // We can't sink the load if the loaded value could be modified between 
9492       // the load and the PHI.
9493       if (LI->isVolatile() != isVolatile ||
9494           LI->getParent() != PN.getIncomingBlock(i) ||
9495           !isSafeToSinkLoad(LI))
9496         return 0;
9497       
9498       // If the PHI is of volatile loads and the load block has multiple
9499       // successors, sinking it would remove a load of the volatile value from
9500       // the path through the other successor.
9501       if (isVolatile &&
9502           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9503         return 0;
9504
9505       
9506     } else if (I->getOperand(1) != ConstantOp) {
9507       return 0;
9508     }
9509   }
9510
9511   // Okay, they are all the same operation.  Create a new PHI node of the
9512   // correct type, and PHI together all of the LHS's of the instructions.
9513   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9514                                    PN.getName()+".in");
9515   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9516
9517   Value *InVal = FirstInst->getOperand(0);
9518   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9519
9520   // Add all operands to the new PHI.
9521   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9522     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9523     if (NewInVal != InVal)
9524       InVal = 0;
9525     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9526   }
9527
9528   Value *PhiVal;
9529   if (InVal) {
9530     // The new PHI unions all of the same values together.  This is really
9531     // common, so we handle it intelligently here for compile-time speed.
9532     PhiVal = InVal;
9533     delete NewPN;
9534   } else {
9535     InsertNewInstBefore(NewPN, PN);
9536     PhiVal = NewPN;
9537   }
9538
9539   // Insert and return the new operation.
9540   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9541     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9542   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9543     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9544   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9545     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9546                            PhiVal, ConstantOp);
9547   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9548   
9549   // If this was a volatile load that we are merging, make sure to loop through
9550   // and mark all the input loads as non-volatile.  If we don't do this, we will
9551   // insert a new volatile load and the old ones will not be deletable.
9552   if (isVolatile)
9553     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9554       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9555   
9556   return new LoadInst(PhiVal, "", isVolatile);
9557 }
9558
9559 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9560 /// that is dead.
9561 static bool DeadPHICycle(PHINode *PN,
9562                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9563   if (PN->use_empty()) return true;
9564   if (!PN->hasOneUse()) return false;
9565
9566   // Remember this node, and if we find the cycle, return.
9567   if (!PotentiallyDeadPHIs.insert(PN))
9568     return true;
9569   
9570   // Don't scan crazily complex things.
9571   if (PotentiallyDeadPHIs.size() == 16)
9572     return false;
9573
9574   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9575     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9576
9577   return false;
9578 }
9579
9580 /// PHIsEqualValue - Return true if this phi node is always equal to
9581 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9582 ///   z = some value; x = phi (y, z); y = phi (x, z)
9583 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9584                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9585   // See if we already saw this PHI node.
9586   if (!ValueEqualPHIs.insert(PN))
9587     return true;
9588   
9589   // Don't scan crazily complex things.
9590   if (ValueEqualPHIs.size() == 16)
9591     return false;
9592  
9593   // Scan the operands to see if they are either phi nodes or are equal to
9594   // the value.
9595   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9596     Value *Op = PN->getIncomingValue(i);
9597     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9598       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9599         return false;
9600     } else if (Op != NonPhiInVal)
9601       return false;
9602   }
9603   
9604   return true;
9605 }
9606
9607
9608 // PHINode simplification
9609 //
9610 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9611   // If LCSSA is around, don't mess with Phi nodes
9612   if (MustPreserveLCSSA) return 0;
9613   
9614   if (Value *V = PN.hasConstantValue())
9615     return ReplaceInstUsesWith(PN, V);
9616
9617   // If all PHI operands are the same operation, pull them through the PHI,
9618   // reducing code size.
9619   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9620       PN.getIncomingValue(0)->hasOneUse())
9621     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9622       return Result;
9623
9624   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9625   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9626   // PHI)... break the cycle.
9627   if (PN.hasOneUse()) {
9628     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9629     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9630       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9631       PotentiallyDeadPHIs.insert(&PN);
9632       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9633         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9634     }
9635    
9636     // If this phi has a single use, and if that use just computes a value for
9637     // the next iteration of a loop, delete the phi.  This occurs with unused
9638     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9639     // common case here is good because the only other things that catch this
9640     // are induction variable analysis (sometimes) and ADCE, which is only run
9641     // late.
9642     if (PHIUser->hasOneUse() &&
9643         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9644         PHIUser->use_back() == &PN) {
9645       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9646     }
9647   }
9648
9649   // We sometimes end up with phi cycles that non-obviously end up being the
9650   // same value, for example:
9651   //   z = some value; x = phi (y, z); y = phi (x, z)
9652   // where the phi nodes don't necessarily need to be in the same block.  Do a
9653   // quick check to see if the PHI node only contains a single non-phi value, if
9654   // so, scan to see if the phi cycle is actually equal to that value.
9655   {
9656     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9657     // Scan for the first non-phi operand.
9658     while (InValNo != NumOperandVals && 
9659            isa<PHINode>(PN.getIncomingValue(InValNo)))
9660       ++InValNo;
9661
9662     if (InValNo != NumOperandVals) {
9663       Value *NonPhiInVal = PN.getOperand(InValNo);
9664       
9665       // Scan the rest of the operands to see if there are any conflicts, if so
9666       // there is no need to recursively scan other phis.
9667       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9668         Value *OpVal = PN.getIncomingValue(InValNo);
9669         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9670           break;
9671       }
9672       
9673       // If we scanned over all operands, then we have one unique value plus
9674       // phi values.  Scan PHI nodes to see if they all merge in each other or
9675       // the value.
9676       if (InValNo == NumOperandVals) {
9677         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9678         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9679           return ReplaceInstUsesWith(PN, NonPhiInVal);
9680       }
9681     }
9682   }
9683   return 0;
9684 }
9685
9686 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9687                                    Instruction *InsertPoint,
9688                                    InstCombiner *IC) {
9689   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9690   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9691   // We must cast correctly to the pointer type. Ensure that we
9692   // sign extend the integer value if it is smaller as this is
9693   // used for address computation.
9694   Instruction::CastOps opcode = 
9695      (VTySize < PtrSize ? Instruction::SExt :
9696       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9697   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9698 }
9699
9700
9701 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9702   Value *PtrOp = GEP.getOperand(0);
9703   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9704   // If so, eliminate the noop.
9705   if (GEP.getNumOperands() == 1)
9706     return ReplaceInstUsesWith(GEP, PtrOp);
9707
9708   if (isa<UndefValue>(GEP.getOperand(0)))
9709     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9710
9711   bool HasZeroPointerIndex = false;
9712   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9713     HasZeroPointerIndex = C->isNullValue();
9714
9715   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9716     return ReplaceInstUsesWith(GEP, PtrOp);
9717
9718   // Eliminate unneeded casts for indices.
9719   bool MadeChange = false;
9720   
9721   gep_type_iterator GTI = gep_type_begin(GEP);
9722   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9723        i != e; ++i, ++GTI) {
9724     if (isa<SequentialType>(*GTI)) {
9725       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9726         if (CI->getOpcode() == Instruction::ZExt ||
9727             CI->getOpcode() == Instruction::SExt) {
9728           const Type *SrcTy = CI->getOperand(0)->getType();
9729           // We can eliminate a cast from i32 to i64 iff the target 
9730           // is a 32-bit pointer target.
9731           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9732             MadeChange = true;
9733             *i = CI->getOperand(0);
9734           }
9735         }
9736       }
9737       // If we are using a wider index than needed for this platform, shrink it
9738       // to what we need.  If the incoming value needs a cast instruction,
9739       // insert it.  This explicit cast can make subsequent optimizations more
9740       // obvious.
9741       Value *Op = *i;
9742       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9743         if (Constant *C = dyn_cast<Constant>(Op)) {
9744           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9745           MadeChange = true;
9746         } else {
9747           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9748                                 GEP);
9749           *i = Op;
9750           MadeChange = true;
9751         }
9752       }
9753     }
9754   }
9755   if (MadeChange) return &GEP;
9756
9757   // If this GEP instruction doesn't move the pointer, and if the input operand
9758   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9759   // real input to the dest type.
9760   if (GEP.hasAllZeroIndices()) {
9761     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9762       // If the bitcast is of an allocation, and the allocation will be
9763       // converted to match the type of the cast, don't touch this.
9764       if (isa<AllocationInst>(BCI->getOperand(0))) {
9765         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9766         if (Instruction *I = visitBitCast(*BCI)) {
9767           if (I != BCI) {
9768             I->takeName(BCI);
9769             BCI->getParent()->getInstList().insert(BCI, I);
9770             ReplaceInstUsesWith(*BCI, I);
9771           }
9772           return &GEP;
9773         }
9774       }
9775       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9776     }
9777   }
9778   
9779   // Combine Indices - If the source pointer to this getelementptr instruction
9780   // is a getelementptr instruction, combine the indices of the two
9781   // getelementptr instructions into a single instruction.
9782   //
9783   SmallVector<Value*, 8> SrcGEPOperands;
9784   if (User *Src = dyn_castGetElementPtr(PtrOp))
9785     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9786
9787   if (!SrcGEPOperands.empty()) {
9788     // Note that if our source is a gep chain itself that we wait for that
9789     // chain to be resolved before we perform this transformation.  This
9790     // avoids us creating a TON of code in some cases.
9791     //
9792     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9793         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9794       return 0;   // Wait until our source is folded to completion.
9795
9796     SmallVector<Value*, 8> Indices;
9797
9798     // Find out whether the last index in the source GEP is a sequential idx.
9799     bool EndsWithSequential = false;
9800     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9801            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9802       EndsWithSequential = !isa<StructType>(*I);
9803
9804     // Can we combine the two pointer arithmetics offsets?
9805     if (EndsWithSequential) {
9806       // Replace: gep (gep %P, long B), long A, ...
9807       // With:    T = long A+B; gep %P, T, ...
9808       //
9809       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9810       if (SO1 == Constant::getNullValue(SO1->getType())) {
9811         Sum = GO1;
9812       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9813         Sum = SO1;
9814       } else {
9815         // If they aren't the same type, convert both to an integer of the
9816         // target's pointer size.
9817         if (SO1->getType() != GO1->getType()) {
9818           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9819             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9820           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9821             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9822           } else {
9823             unsigned PS = TD->getPointerSizeInBits();
9824             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9825               // Convert GO1 to SO1's type.
9826               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9827
9828             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9829               // Convert SO1 to GO1's type.
9830               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9831             } else {
9832               const Type *PT = TD->getIntPtrType();
9833               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9834               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9835             }
9836           }
9837         }
9838         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9839           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9840         else {
9841           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9842           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9843         }
9844       }
9845
9846       // Recycle the GEP we already have if possible.
9847       if (SrcGEPOperands.size() == 2) {
9848         GEP.setOperand(0, SrcGEPOperands[0]);
9849         GEP.setOperand(1, Sum);
9850         return &GEP;
9851       } else {
9852         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9853                        SrcGEPOperands.end()-1);
9854         Indices.push_back(Sum);
9855         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9856       }
9857     } else if (isa<Constant>(*GEP.idx_begin()) &&
9858                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9859                SrcGEPOperands.size() != 1) {
9860       // Otherwise we can do the fold if the first index of the GEP is a zero
9861       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9862                      SrcGEPOperands.end());
9863       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9864     }
9865
9866     if (!Indices.empty())
9867       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9868                                        Indices.end(), GEP.getName());
9869
9870   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9871     // GEP of global variable.  If all of the indices for this GEP are
9872     // constants, we can promote this to a constexpr instead of an instruction.
9873
9874     // Scan for nonconstants...
9875     SmallVector<Constant*, 8> Indices;
9876     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9877     for (; I != E && isa<Constant>(*I); ++I)
9878       Indices.push_back(cast<Constant>(*I));
9879
9880     if (I == E) {  // If they are all constants...
9881       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9882                                                     &Indices[0],Indices.size());
9883
9884       // Replace all uses of the GEP with the new constexpr...
9885       return ReplaceInstUsesWith(GEP, CE);
9886     }
9887   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9888     if (!isa<PointerType>(X->getType())) {
9889       // Not interesting.  Source pointer must be a cast from pointer.
9890     } else if (HasZeroPointerIndex) {
9891       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9892       // into     : GEP [10 x i8]* X, i32 0, ...
9893       //
9894       // This occurs when the program declares an array extern like "int X[];"
9895       //
9896       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9897       const PointerType *XTy = cast<PointerType>(X->getType());
9898       if (const ArrayType *XATy =
9899           dyn_cast<ArrayType>(XTy->getElementType()))
9900         if (const ArrayType *CATy =
9901             dyn_cast<ArrayType>(CPTy->getElementType()))
9902           if (CATy->getElementType() == XATy->getElementType()) {
9903             // At this point, we know that the cast source type is a pointer
9904             // to an array of the same type as the destination pointer
9905             // array.  Because the array type is never stepped over (there
9906             // is a leading zero) we can fold the cast into this GEP.
9907             GEP.setOperand(0, X);
9908             return &GEP;
9909           }
9910     } else if (GEP.getNumOperands() == 2) {
9911       // Transform things like:
9912       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9913       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9914       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9915       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9916       if (isa<ArrayType>(SrcElTy) &&
9917           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9918           TD->getABITypeSize(ResElTy)) {
9919         Value *Idx[2];
9920         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9921         Idx[1] = GEP.getOperand(1);
9922         Value *V = InsertNewInstBefore(
9923                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9924         // V and GEP are both pointer types --> BitCast
9925         return new BitCastInst(V, GEP.getType());
9926       }
9927       
9928       // Transform things like:
9929       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9930       //   (where tmp = 8*tmp2) into:
9931       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9932       
9933       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9934         uint64_t ArrayEltSize =
9935             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9936         
9937         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9938         // allow either a mul, shift, or constant here.
9939         Value *NewIdx = 0;
9940         ConstantInt *Scale = 0;
9941         if (ArrayEltSize == 1) {
9942           NewIdx = GEP.getOperand(1);
9943           Scale = ConstantInt::get(NewIdx->getType(), 1);
9944         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9945           NewIdx = ConstantInt::get(CI->getType(), 1);
9946           Scale = CI;
9947         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9948           if (Inst->getOpcode() == Instruction::Shl &&
9949               isa<ConstantInt>(Inst->getOperand(1))) {
9950             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9951             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9952             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9953             NewIdx = Inst->getOperand(0);
9954           } else if (Inst->getOpcode() == Instruction::Mul &&
9955                      isa<ConstantInt>(Inst->getOperand(1))) {
9956             Scale = cast<ConstantInt>(Inst->getOperand(1));
9957             NewIdx = Inst->getOperand(0);
9958           }
9959         }
9960         
9961         // If the index will be to exactly the right offset with the scale taken
9962         // out, perform the transformation. Note, we don't know whether Scale is
9963         // signed or not. We'll use unsigned version of division/modulo
9964         // operation after making sure Scale doesn't have the sign bit set.
9965         if (Scale && Scale->getSExtValue() >= 0LL &&
9966             Scale->getZExtValue() % ArrayEltSize == 0) {
9967           Scale = ConstantInt::get(Scale->getType(),
9968                                    Scale->getZExtValue() / ArrayEltSize);
9969           if (Scale->getZExtValue() != 1) {
9970             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9971                                                        false /*ZExt*/);
9972             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9973             NewIdx = InsertNewInstBefore(Sc, GEP);
9974           }
9975
9976           // Insert the new GEP instruction.
9977           Value *Idx[2];
9978           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9979           Idx[1] = NewIdx;
9980           Instruction *NewGEP =
9981             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9982           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9983           // The NewGEP must be pointer typed, so must the old one -> BitCast
9984           return new BitCastInst(NewGEP, GEP.getType());
9985         }
9986       }
9987     }
9988   }
9989
9990   return 0;
9991 }
9992
9993 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9994   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9995   if (AI.isArrayAllocation()) {  // Check C != 1
9996     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9997       const Type *NewTy = 
9998         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9999       AllocationInst *New = 0;
10000
10001       // Create and insert the replacement instruction...
10002       if (isa<MallocInst>(AI))
10003         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10004       else {
10005         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10006         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10007       }
10008
10009       InsertNewInstBefore(New, AI);
10010
10011       // Scan to the end of the allocation instructions, to skip over a block of
10012       // allocas if possible...
10013       //
10014       BasicBlock::iterator It = New;
10015       while (isa<AllocationInst>(*It)) ++It;
10016
10017       // Now that I is pointing to the first non-allocation-inst in the block,
10018       // insert our getelementptr instruction...
10019       //
10020       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10021       Value *Idx[2];
10022       Idx[0] = NullIdx;
10023       Idx[1] = NullIdx;
10024       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10025                                            New->getName()+".sub", It);
10026
10027       // Now make everything use the getelementptr instead of the original
10028       // allocation.
10029       return ReplaceInstUsesWith(AI, V);
10030     } else if (isa<UndefValue>(AI.getArraySize())) {
10031       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10032     }
10033   }
10034
10035   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10036   // Note that we only do this for alloca's, because malloc should allocate and
10037   // return a unique pointer, even for a zero byte allocation.
10038   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10039       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10040     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10041
10042   return 0;
10043 }
10044
10045 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10046   Value *Op = FI.getOperand(0);
10047
10048   // free undef -> unreachable.
10049   if (isa<UndefValue>(Op)) {
10050     // Insert a new store to null because we cannot modify the CFG here.
10051     new StoreInst(ConstantInt::getTrue(),
10052                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10053     return EraseInstFromFunction(FI);
10054   }
10055   
10056   // If we have 'free null' delete the instruction.  This can happen in stl code
10057   // when lots of inlining happens.
10058   if (isa<ConstantPointerNull>(Op))
10059     return EraseInstFromFunction(FI);
10060   
10061   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10062   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10063     FI.setOperand(0, CI->getOperand(0));
10064     return &FI;
10065   }
10066   
10067   // Change free (gep X, 0,0,0,0) into free(X)
10068   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10069     if (GEPI->hasAllZeroIndices()) {
10070       AddToWorkList(GEPI);
10071       FI.setOperand(0, GEPI->getOperand(0));
10072       return &FI;
10073     }
10074   }
10075   
10076   // Change free(malloc) into nothing, if the malloc has a single use.
10077   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10078     if (MI->hasOneUse()) {
10079       EraseInstFromFunction(FI);
10080       return EraseInstFromFunction(*MI);
10081     }
10082
10083   return 0;
10084 }
10085
10086
10087 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10088 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10089                                         const TargetData *TD) {
10090   User *CI = cast<User>(LI.getOperand(0));
10091   Value *CastOp = CI->getOperand(0);
10092
10093   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10094     // Instead of loading constant c string, use corresponding integer value
10095     // directly if string length is small enough.
10096     std::string Str;
10097     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10098       unsigned len = Str.length();
10099       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10100       unsigned numBits = Ty->getPrimitiveSizeInBits();
10101       // Replace LI with immediate integer store.
10102       if ((numBits >> 3) == len + 1) {
10103         APInt StrVal(numBits, 0);
10104         APInt SingleChar(numBits, 0);
10105         if (TD->isLittleEndian()) {
10106           for (signed i = len-1; i >= 0; i--) {
10107             SingleChar = (uint64_t) Str[i];
10108             StrVal = (StrVal << 8) | SingleChar;
10109           }
10110         } else {
10111           for (unsigned i = 0; i < len; i++) {
10112             SingleChar = (uint64_t) Str[i];
10113             StrVal = (StrVal << 8) | SingleChar;
10114           }
10115           // Append NULL at the end.
10116           SingleChar = 0;
10117           StrVal = (StrVal << 8) | SingleChar;
10118         }
10119         Value *NL = ConstantInt::get(StrVal);
10120         return IC.ReplaceInstUsesWith(LI, NL);
10121       }
10122     }
10123   }
10124
10125   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10126   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10127     const Type *SrcPTy = SrcTy->getElementType();
10128
10129     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10130          isa<VectorType>(DestPTy)) {
10131       // If the source is an array, the code below will not succeed.  Check to
10132       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10133       // constants.
10134       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10135         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10136           if (ASrcTy->getNumElements() != 0) {
10137             Value *Idxs[2];
10138             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10139             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10140             SrcTy = cast<PointerType>(CastOp->getType());
10141             SrcPTy = SrcTy->getElementType();
10142           }
10143
10144       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10145             isa<VectorType>(SrcPTy)) &&
10146           // Do not allow turning this into a load of an integer, which is then
10147           // casted to a pointer, this pessimizes pointer analysis a lot.
10148           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10149           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10150                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10151
10152         // Okay, we are casting from one integer or pointer type to another of
10153         // the same size.  Instead of casting the pointer before the load, cast
10154         // the result of the loaded value.
10155         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10156                                                              CI->getName(),
10157                                                          LI.isVolatile()),LI);
10158         // Now cast the result of the load.
10159         return new BitCastInst(NewLoad, LI.getType());
10160       }
10161     }
10162   }
10163   return 0;
10164 }
10165
10166 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10167 /// from this value cannot trap.  If it is not obviously safe to load from the
10168 /// specified pointer, we do a quick local scan of the basic block containing
10169 /// ScanFrom, to determine if the address is already accessed.
10170 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10171   // If it is an alloca it is always safe to load from.
10172   if (isa<AllocaInst>(V)) return true;
10173
10174   // If it is a global variable it is mostly safe to load from.
10175   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10176     // Don't try to evaluate aliases.  External weak GV can be null.
10177     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10178
10179   // Otherwise, be a little bit agressive by scanning the local block where we
10180   // want to check to see if the pointer is already being loaded or stored
10181   // from/to.  If so, the previous load or store would have already trapped,
10182   // so there is no harm doing an extra load (also, CSE will later eliminate
10183   // the load entirely).
10184   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10185
10186   while (BBI != E) {
10187     --BBI;
10188
10189     // If we see a free or a call (which might do a free) the pointer could be
10190     // marked invalid.
10191     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10192       return false;
10193     
10194     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10195       if (LI->getOperand(0) == V) return true;
10196     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10197       if (SI->getOperand(1) == V) return true;
10198     }
10199
10200   }
10201   return false;
10202 }
10203
10204 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10205 /// until we find the underlying object a pointer is referring to or something
10206 /// we don't understand.  Note that the returned pointer may be offset from the
10207 /// input, because we ignore GEP indices.
10208 static Value *GetUnderlyingObject(Value *Ptr) {
10209   while (1) {
10210     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10211       if (CE->getOpcode() == Instruction::BitCast ||
10212           CE->getOpcode() == Instruction::GetElementPtr)
10213         Ptr = CE->getOperand(0);
10214       else
10215         return Ptr;
10216     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10217       Ptr = BCI->getOperand(0);
10218     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10219       Ptr = GEP->getOperand(0);
10220     } else {
10221       return Ptr;
10222     }
10223   }
10224 }
10225
10226 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10227   Value *Op = LI.getOperand(0);
10228
10229   // Attempt to improve the alignment.
10230   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10231   if (KnownAlign >
10232       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10233                                 LI.getAlignment()))
10234     LI.setAlignment(KnownAlign);
10235
10236   // load (cast X) --> cast (load X) iff safe
10237   if (isa<CastInst>(Op))
10238     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10239       return Res;
10240
10241   // None of the following transforms are legal for volatile loads.
10242   if (LI.isVolatile()) return 0;
10243   
10244   if (&LI.getParent()->front() != &LI) {
10245     BasicBlock::iterator BBI = &LI; --BBI;
10246     // If the instruction immediately before this is a store to the same
10247     // address, do a simple form of store->load forwarding.
10248     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10249       if (SI->getOperand(1) == LI.getOperand(0))
10250         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10251     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10252       if (LIB->getOperand(0) == LI.getOperand(0))
10253         return ReplaceInstUsesWith(LI, LIB);
10254   }
10255
10256   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10257     const Value *GEPI0 = GEPI->getOperand(0);
10258     // TODO: Consider a target hook for valid address spaces for this xform.
10259     if (isa<ConstantPointerNull>(GEPI0) &&
10260         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10261       // Insert a new store to null instruction before the load to indicate
10262       // that this code is not reachable.  We do this instead of inserting
10263       // an unreachable instruction directly because we cannot modify the
10264       // CFG.
10265       new StoreInst(UndefValue::get(LI.getType()),
10266                     Constant::getNullValue(Op->getType()), &LI);
10267       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10268     }
10269   } 
10270
10271   if (Constant *C = dyn_cast<Constant>(Op)) {
10272     // load null/undef -> undef
10273     // TODO: Consider a target hook for valid address spaces for this xform.
10274     if (isa<UndefValue>(C) || (C->isNullValue() && 
10275         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10276       // Insert a new store to null instruction before the load to indicate that
10277       // this code is not reachable.  We do this instead of inserting an
10278       // unreachable instruction directly because we cannot modify the CFG.
10279       new StoreInst(UndefValue::get(LI.getType()),
10280                     Constant::getNullValue(Op->getType()), &LI);
10281       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10282     }
10283
10284     // Instcombine load (constant global) into the value loaded.
10285     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10286       if (GV->isConstant() && !GV->isDeclaration())
10287         return ReplaceInstUsesWith(LI, GV->getInitializer());
10288
10289     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10290     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10291       if (CE->getOpcode() == Instruction::GetElementPtr) {
10292         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10293           if (GV->isConstant() && !GV->isDeclaration())
10294             if (Constant *V = 
10295                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10296               return ReplaceInstUsesWith(LI, V);
10297         if (CE->getOperand(0)->isNullValue()) {
10298           // Insert a new store to null instruction before the load to indicate
10299           // that this code is not reachable.  We do this instead of inserting
10300           // an unreachable instruction directly because we cannot modify the
10301           // CFG.
10302           new StoreInst(UndefValue::get(LI.getType()),
10303                         Constant::getNullValue(Op->getType()), &LI);
10304           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10305         }
10306
10307       } else if (CE->isCast()) {
10308         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10309           return Res;
10310       }
10311     }
10312   }
10313     
10314   // If this load comes from anywhere in a constant global, and if the global
10315   // is all undef or zero, we know what it loads.
10316   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10317     if (GV->isConstant() && GV->hasInitializer()) {
10318       if (GV->getInitializer()->isNullValue())
10319         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10320       else if (isa<UndefValue>(GV->getInitializer()))
10321         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10322     }
10323   }
10324
10325   if (Op->hasOneUse()) {
10326     // Change select and PHI nodes to select values instead of addresses: this
10327     // helps alias analysis out a lot, allows many others simplifications, and
10328     // exposes redundancy in the code.
10329     //
10330     // Note that we cannot do the transformation unless we know that the
10331     // introduced loads cannot trap!  Something like this is valid as long as
10332     // the condition is always false: load (select bool %C, int* null, int* %G),
10333     // but it would not be valid if we transformed it to load from null
10334     // unconditionally.
10335     //
10336     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10337       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10338       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10339           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10340         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10341                                      SI->getOperand(1)->getName()+".val"), LI);
10342         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10343                                      SI->getOperand(2)->getName()+".val"), LI);
10344         return SelectInst::Create(SI->getCondition(), V1, V2);
10345       }
10346
10347       // load (select (cond, null, P)) -> load P
10348       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10349         if (C->isNullValue()) {
10350           LI.setOperand(0, SI->getOperand(2));
10351           return &LI;
10352         }
10353
10354       // load (select (cond, P, null)) -> load P
10355       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10356         if (C->isNullValue()) {
10357           LI.setOperand(0, SI->getOperand(1));
10358           return &LI;
10359         }
10360     }
10361   }
10362   return 0;
10363 }
10364
10365 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10366 /// when possible.
10367 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10368   User *CI = cast<User>(SI.getOperand(1));
10369   Value *CastOp = CI->getOperand(0);
10370
10371   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10372   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10373     const Type *SrcPTy = SrcTy->getElementType();
10374
10375     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10376       // If the source is an array, the code below will not succeed.  Check to
10377       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10378       // constants.
10379       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10380         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10381           if (ASrcTy->getNumElements() != 0) {
10382             Value* Idxs[2];
10383             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10384             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10385             SrcTy = cast<PointerType>(CastOp->getType());
10386             SrcPTy = SrcTy->getElementType();
10387           }
10388
10389       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10390           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10391                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10392
10393         // Okay, we are casting from one integer or pointer type to another of
10394         // the same size.  Instead of casting the pointer before 
10395         // the store, cast the value to be stored.
10396         Value *NewCast;
10397         Value *SIOp0 = SI.getOperand(0);
10398         Instruction::CastOps opcode = Instruction::BitCast;
10399         const Type* CastSrcTy = SIOp0->getType();
10400         const Type* CastDstTy = SrcPTy;
10401         if (isa<PointerType>(CastDstTy)) {
10402           if (CastSrcTy->isInteger())
10403             opcode = Instruction::IntToPtr;
10404         } else if (isa<IntegerType>(CastDstTy)) {
10405           if (isa<PointerType>(SIOp0->getType()))
10406             opcode = Instruction::PtrToInt;
10407         }
10408         if (Constant *C = dyn_cast<Constant>(SIOp0))
10409           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10410         else
10411           NewCast = IC.InsertNewInstBefore(
10412             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10413             SI);
10414         return new StoreInst(NewCast, CastOp);
10415       }
10416     }
10417   }
10418   return 0;
10419 }
10420
10421 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10422   Value *Val = SI.getOperand(0);
10423   Value *Ptr = SI.getOperand(1);
10424
10425   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10426     EraseInstFromFunction(SI);
10427     ++NumCombined;
10428     return 0;
10429   }
10430   
10431   // If the RHS is an alloca with a single use, zapify the store, making the
10432   // alloca dead.
10433   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10434     if (isa<AllocaInst>(Ptr)) {
10435       EraseInstFromFunction(SI);
10436       ++NumCombined;
10437       return 0;
10438     }
10439     
10440     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10441       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10442           GEP->getOperand(0)->hasOneUse()) {
10443         EraseInstFromFunction(SI);
10444         ++NumCombined;
10445         return 0;
10446       }
10447   }
10448
10449   // Attempt to improve the alignment.
10450   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10451   if (KnownAlign >
10452       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10453                                 SI.getAlignment()))
10454     SI.setAlignment(KnownAlign);
10455
10456   // Do really simple DSE, to catch cases where there are several consequtive
10457   // stores to the same location, separated by a few arithmetic operations. This
10458   // situation often occurs with bitfield accesses.
10459   BasicBlock::iterator BBI = &SI;
10460   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10461        --ScanInsts) {
10462     --BBI;
10463     
10464     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10465       // Prev store isn't volatile, and stores to the same location?
10466       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10467         ++NumDeadStore;
10468         ++BBI;
10469         EraseInstFromFunction(*PrevSI);
10470         continue;
10471       }
10472       break;
10473     }
10474     
10475     // If this is a load, we have to stop.  However, if the loaded value is from
10476     // the pointer we're loading and is producing the pointer we're storing,
10477     // then *this* store is dead (X = load P; store X -> P).
10478     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10479       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10480         EraseInstFromFunction(SI);
10481         ++NumCombined;
10482         return 0;
10483       }
10484       // Otherwise, this is a load from some other location.  Stores before it
10485       // may not be dead.
10486       break;
10487     }
10488     
10489     // Don't skip over loads or things that can modify memory.
10490     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10491       break;
10492   }
10493   
10494   
10495   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10496
10497   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10498   if (isa<ConstantPointerNull>(Ptr)) {
10499     if (!isa<UndefValue>(Val)) {
10500       SI.setOperand(0, UndefValue::get(Val->getType()));
10501       if (Instruction *U = dyn_cast<Instruction>(Val))
10502         AddToWorkList(U);  // Dropped a use.
10503       ++NumCombined;
10504     }
10505     return 0;  // Do not modify these!
10506   }
10507
10508   // store undef, Ptr -> noop
10509   if (isa<UndefValue>(Val)) {
10510     EraseInstFromFunction(SI);
10511     ++NumCombined;
10512     return 0;
10513   }
10514
10515   // If the pointer destination is a cast, see if we can fold the cast into the
10516   // source instead.
10517   if (isa<CastInst>(Ptr))
10518     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10519       return Res;
10520   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10521     if (CE->isCast())
10522       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10523         return Res;
10524
10525   
10526   // If this store is the last instruction in the basic block, and if the block
10527   // ends with an unconditional branch, try to move it to the successor block.
10528   BBI = &SI; ++BBI;
10529   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10530     if (BI->isUnconditional())
10531       if (SimplifyStoreAtEndOfBlock(SI))
10532         return 0;  // xform done!
10533   
10534   return 0;
10535 }
10536
10537 /// SimplifyStoreAtEndOfBlock - Turn things like:
10538 ///   if () { *P = v1; } else { *P = v2 }
10539 /// into a phi node with a store in the successor.
10540 ///
10541 /// Simplify things like:
10542 ///   *P = v1; if () { *P = v2; }
10543 /// into a phi node with a store in the successor.
10544 ///
10545 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10546   BasicBlock *StoreBB = SI.getParent();
10547   
10548   // Check to see if the successor block has exactly two incoming edges.  If
10549   // so, see if the other predecessor contains a store to the same location.
10550   // if so, insert a PHI node (if needed) and move the stores down.
10551   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10552   
10553   // Determine whether Dest has exactly two predecessors and, if so, compute
10554   // the other predecessor.
10555   pred_iterator PI = pred_begin(DestBB);
10556   BasicBlock *OtherBB = 0;
10557   if (*PI != StoreBB)
10558     OtherBB = *PI;
10559   ++PI;
10560   if (PI == pred_end(DestBB))
10561     return false;
10562   
10563   if (*PI != StoreBB) {
10564     if (OtherBB)
10565       return false;
10566     OtherBB = *PI;
10567   }
10568   if (++PI != pred_end(DestBB))
10569     return false;
10570
10571   // Bail out if all the relevant blocks aren't distinct (this can happen,
10572   // for example, if SI is in an infinite loop)
10573   if (StoreBB == DestBB || OtherBB == DestBB)
10574     return false;
10575
10576   // Verify that the other block ends in a branch and is not otherwise empty.
10577   BasicBlock::iterator BBI = OtherBB->getTerminator();
10578   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10579   if (!OtherBr || BBI == OtherBB->begin())
10580     return false;
10581   
10582   // If the other block ends in an unconditional branch, check for the 'if then
10583   // else' case.  there is an instruction before the branch.
10584   StoreInst *OtherStore = 0;
10585   if (OtherBr->isUnconditional()) {
10586     // If this isn't a store, or isn't a store to the same location, bail out.
10587     --BBI;
10588     OtherStore = dyn_cast<StoreInst>(BBI);
10589     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10590       return false;
10591   } else {
10592     // Otherwise, the other block ended with a conditional branch. If one of the
10593     // destinations is StoreBB, then we have the if/then case.
10594     if (OtherBr->getSuccessor(0) != StoreBB && 
10595         OtherBr->getSuccessor(1) != StoreBB)
10596       return false;
10597     
10598     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10599     // if/then triangle.  See if there is a store to the same ptr as SI that
10600     // lives in OtherBB.
10601     for (;; --BBI) {
10602       // Check to see if we find the matching store.
10603       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10604         if (OtherStore->getOperand(1) != SI.getOperand(1))
10605           return false;
10606         break;
10607       }
10608       // If we find something that may be using or overwriting the stored
10609       // value, or if we run out of instructions, we can't do the xform.
10610       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10611           BBI == OtherBB->begin())
10612         return false;
10613     }
10614     
10615     // In order to eliminate the store in OtherBr, we have to
10616     // make sure nothing reads or overwrites the stored value in
10617     // StoreBB.
10618     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10619       // FIXME: This should really be AA driven.
10620       if (I->mayReadFromMemory() || I->mayWriteToMemory())
10621         return false;
10622     }
10623   }
10624   
10625   // Insert a PHI node now if we need it.
10626   Value *MergedVal = OtherStore->getOperand(0);
10627   if (MergedVal != SI.getOperand(0)) {
10628     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10629     PN->reserveOperandSpace(2);
10630     PN->addIncoming(SI.getOperand(0), SI.getParent());
10631     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10632     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10633   }
10634   
10635   // Advance to a place where it is safe to insert the new store and
10636   // insert it.
10637   BBI = DestBB->getFirstNonPHI();
10638   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10639                                     OtherStore->isVolatile()), *BBI);
10640   
10641   // Nuke the old stores.
10642   EraseInstFromFunction(SI);
10643   EraseInstFromFunction(*OtherStore);
10644   ++NumCombined;
10645   return true;
10646 }
10647
10648
10649 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10650   // Change br (not X), label True, label False to: br X, label False, True
10651   Value *X = 0;
10652   BasicBlock *TrueDest;
10653   BasicBlock *FalseDest;
10654   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10655       !isa<Constant>(X)) {
10656     // Swap Destinations and condition...
10657     BI.setCondition(X);
10658     BI.setSuccessor(0, FalseDest);
10659     BI.setSuccessor(1, TrueDest);
10660     return &BI;
10661   }
10662
10663   // Cannonicalize fcmp_one -> fcmp_oeq
10664   FCmpInst::Predicate FPred; Value *Y;
10665   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10666                              TrueDest, FalseDest)))
10667     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10668          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10669       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10670       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10671       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10672       NewSCC->takeName(I);
10673       // Swap Destinations and condition...
10674       BI.setCondition(NewSCC);
10675       BI.setSuccessor(0, FalseDest);
10676       BI.setSuccessor(1, TrueDest);
10677       RemoveFromWorkList(I);
10678       I->eraseFromParent();
10679       AddToWorkList(NewSCC);
10680       return &BI;
10681     }
10682
10683   // Cannonicalize icmp_ne -> icmp_eq
10684   ICmpInst::Predicate IPred;
10685   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10686                       TrueDest, FalseDest)))
10687     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10688          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10689          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10690       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10691       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10692       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10693       NewSCC->takeName(I);
10694       // Swap Destinations and condition...
10695       BI.setCondition(NewSCC);
10696       BI.setSuccessor(0, FalseDest);
10697       BI.setSuccessor(1, TrueDest);
10698       RemoveFromWorkList(I);
10699       I->eraseFromParent();;
10700       AddToWorkList(NewSCC);
10701       return &BI;
10702     }
10703
10704   return 0;
10705 }
10706
10707 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10708   Value *Cond = SI.getCondition();
10709   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10710     if (I->getOpcode() == Instruction::Add)
10711       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10712         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10713         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10714           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10715                                                 AddRHS));
10716         SI.setOperand(0, I->getOperand(0));
10717         AddToWorkList(I);
10718         return &SI;
10719       }
10720   }
10721   return 0;
10722 }
10723
10724 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10725   Value *Agg = EV.getAggregateOperand();
10726
10727   if (!EV.hasIndices())
10728     return ReplaceInstUsesWith(EV, Agg);
10729
10730   if (Constant *C = dyn_cast<Constant>(Agg)) {
10731     if (isa<UndefValue>(C))
10732       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
10733       
10734     if (isa<ConstantAggregateZero>(C))
10735       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
10736
10737     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
10738       // Extract the element indexed by the first index out of the constant
10739       Value *V = C->getOperand(*EV.idx_begin());
10740       if (EV.getNumIndices() > 1)
10741         // Extract the remaining indices out of the constant indexed by the
10742         // first index
10743         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
10744       else
10745         return ReplaceInstUsesWith(EV, V);
10746     }
10747     return 0; // Can't handle other constants
10748   } 
10749   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
10750     // We're extracting from an insertvalue instruction, compare the indices
10751     const unsigned *exti, *exte, *insi, *inse;
10752     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
10753          exte = EV.idx_end(), inse = IV->idx_end();
10754          exti != exte && insi != inse;
10755          ++exti, ++insi) {
10756       if (*insi != *exti)
10757         // The insert and extract both reference distinctly different elements.
10758         // This means the extract is not influenced by the insert, and we can
10759         // replace the aggregate operand of the extract with the aggregate
10760         // operand of the insert. i.e., replace
10761         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10762         // %E = extractvalue { i32, { i32 } } %I, 0
10763         // with
10764         // %E = extractvalue { i32, { i32 } } %A, 0
10765         return ExtractValueInst::Create(IV->getAggregateOperand(),
10766                                         EV.idx_begin(), EV.idx_end());
10767     }
10768     if (exti == exte && insi == inse)
10769       // Both iterators are at the end: Index lists are identical. Replace
10770       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10771       // %C = extractvalue { i32, { i32 } } %B, 1, 0
10772       // with "i32 42"
10773       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
10774     if (exti == exte) {
10775       // The extract list is a prefix of the insert list. i.e. replace
10776       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10777       // %E = extractvalue { i32, { i32 } } %I, 1
10778       // with
10779       // %X = extractvalue { i32, { i32 } } %A, 1
10780       // %E = insertvalue { i32 } %X, i32 42, 0
10781       // by switching the order of the insert and extract (though the
10782       // insertvalue should be left in, since it may have other uses).
10783       Value *NewEV = InsertNewInstBefore(
10784         ExtractValueInst::Create(IV->getAggregateOperand(),
10785                                  EV.idx_begin(), EV.idx_end()),
10786         EV);
10787       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
10788                                      insi, inse);
10789     }
10790     if (insi == inse)
10791       // The insert list is a prefix of the extract list
10792       // We can simply remove the common indices from the extract and make it
10793       // operate on the inserted value instead of the insertvalue result.
10794       // i.e., replace
10795       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10796       // %E = extractvalue { i32, { i32 } } %I, 1, 0
10797       // with
10798       // %E extractvalue { i32 } { i32 42 }, 0
10799       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
10800                                       exti, exte);
10801   }
10802   // Can't simplify extracts from other values. Note that nested extracts are
10803   // already simplified implicitely by the above (extract ( extract (insert) )
10804   // will be translated into extract ( insert ( extract ) ) first and then just
10805   // the value inserted, if appropriate).
10806   return 0;
10807 }
10808
10809 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10810 /// is to leave as a vector operation.
10811 static bool CheapToScalarize(Value *V, bool isConstant) {
10812   if (isa<ConstantAggregateZero>(V)) 
10813     return true;
10814   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10815     if (isConstant) return true;
10816     // If all elts are the same, we can extract.
10817     Constant *Op0 = C->getOperand(0);
10818     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10819       if (C->getOperand(i) != Op0)
10820         return false;
10821     return true;
10822   }
10823   Instruction *I = dyn_cast<Instruction>(V);
10824   if (!I) return false;
10825   
10826   // Insert element gets simplified to the inserted element or is deleted if
10827   // this is constant idx extract element and its a constant idx insertelt.
10828   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10829       isa<ConstantInt>(I->getOperand(2)))
10830     return true;
10831   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10832     return true;
10833   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10834     if (BO->hasOneUse() &&
10835         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10836          CheapToScalarize(BO->getOperand(1), isConstant)))
10837       return true;
10838   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10839     if (CI->hasOneUse() &&
10840         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10841          CheapToScalarize(CI->getOperand(1), isConstant)))
10842       return true;
10843   
10844   return false;
10845 }
10846
10847 /// Read and decode a shufflevector mask.
10848 ///
10849 /// It turns undef elements into values that are larger than the number of
10850 /// elements in the input.
10851 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10852   unsigned NElts = SVI->getType()->getNumElements();
10853   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10854     return std::vector<unsigned>(NElts, 0);
10855   if (isa<UndefValue>(SVI->getOperand(2)))
10856     return std::vector<unsigned>(NElts, 2*NElts);
10857
10858   std::vector<unsigned> Result;
10859   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10860   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10861     if (isa<UndefValue>(*i))
10862       Result.push_back(NElts*2);  // undef -> 8
10863     else
10864       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10865   return Result;
10866 }
10867
10868 /// FindScalarElement - Given a vector and an element number, see if the scalar
10869 /// value is already around as a register, for example if it were inserted then
10870 /// extracted from the vector.
10871 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10872   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10873   const VectorType *PTy = cast<VectorType>(V->getType());
10874   unsigned Width = PTy->getNumElements();
10875   if (EltNo >= Width)  // Out of range access.
10876     return UndefValue::get(PTy->getElementType());
10877   
10878   if (isa<UndefValue>(V))
10879     return UndefValue::get(PTy->getElementType());
10880   else if (isa<ConstantAggregateZero>(V))
10881     return Constant::getNullValue(PTy->getElementType());
10882   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10883     return CP->getOperand(EltNo);
10884   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10885     // If this is an insert to a variable element, we don't know what it is.
10886     if (!isa<ConstantInt>(III->getOperand(2))) 
10887       return 0;
10888     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10889     
10890     // If this is an insert to the element we are looking for, return the
10891     // inserted value.
10892     if (EltNo == IIElt) 
10893       return III->getOperand(1);
10894     
10895     // Otherwise, the insertelement doesn't modify the value, recurse on its
10896     // vector input.
10897     return FindScalarElement(III->getOperand(0), EltNo);
10898   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10899     unsigned InEl = getShuffleMask(SVI)[EltNo];
10900     if (InEl < Width)
10901       return FindScalarElement(SVI->getOperand(0), InEl);
10902     else if (InEl < Width*2)
10903       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10904     else
10905       return UndefValue::get(PTy->getElementType());
10906   }
10907   
10908   // Otherwise, we don't know.
10909   return 0;
10910 }
10911
10912 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10913   // If vector val is undef, replace extract with scalar undef.
10914   if (isa<UndefValue>(EI.getOperand(0)))
10915     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10916
10917   // If vector val is constant 0, replace extract with scalar 0.
10918   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10919     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10920   
10921   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10922     // If vector val is constant with all elements the same, replace EI with
10923     // that element. When the elements are not identical, we cannot replace yet
10924     // (we do that below, but only when the index is constant).
10925     Constant *op0 = C->getOperand(0);
10926     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10927       if (C->getOperand(i) != op0) {
10928         op0 = 0; 
10929         break;
10930       }
10931     if (op0)
10932       return ReplaceInstUsesWith(EI, op0);
10933   }
10934   
10935   // If extracting a specified index from the vector, see if we can recursively
10936   // find a previously computed scalar that was inserted into the vector.
10937   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10938     unsigned IndexVal = IdxC->getZExtValue();
10939     unsigned VectorWidth = 
10940       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10941       
10942     // If this is extracting an invalid index, turn this into undef, to avoid
10943     // crashing the code below.
10944     if (IndexVal >= VectorWidth)
10945       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10946     
10947     // This instruction only demands the single element from the input vector.
10948     // If the input vector has a single use, simplify it based on this use
10949     // property.
10950     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10951       uint64_t UndefElts;
10952       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10953                                                 1 << IndexVal,
10954                                                 UndefElts)) {
10955         EI.setOperand(0, V);
10956         return &EI;
10957       }
10958     }
10959     
10960     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10961       return ReplaceInstUsesWith(EI, Elt);
10962     
10963     // If the this extractelement is directly using a bitcast from a vector of
10964     // the same number of elements, see if we can find the source element from
10965     // it.  In this case, we will end up needing to bitcast the scalars.
10966     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10967       if (const VectorType *VT = 
10968               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10969         if (VT->getNumElements() == VectorWidth)
10970           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10971             return new BitCastInst(Elt, EI.getType());
10972     }
10973   }
10974   
10975   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10976     if (I->hasOneUse()) {
10977       // Push extractelement into predecessor operation if legal and
10978       // profitable to do so
10979       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10980         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10981         if (CheapToScalarize(BO, isConstantElt)) {
10982           ExtractElementInst *newEI0 = 
10983             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10984                                    EI.getName()+".lhs");
10985           ExtractElementInst *newEI1 =
10986             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10987                                    EI.getName()+".rhs");
10988           InsertNewInstBefore(newEI0, EI);
10989           InsertNewInstBefore(newEI1, EI);
10990           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10991         }
10992       } else if (isa<LoadInst>(I)) {
10993         unsigned AS = 
10994           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10995         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10996                                          PointerType::get(EI.getType(), AS),EI);
10997         GetElementPtrInst *GEP =
10998           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10999         InsertNewInstBefore(GEP, EI);
11000         return new LoadInst(GEP);
11001       }
11002     }
11003     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11004       // Extracting the inserted element?
11005       if (IE->getOperand(2) == EI.getOperand(1))
11006         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11007       // If the inserted and extracted elements are constants, they must not
11008       // be the same value, extract from the pre-inserted value instead.
11009       if (isa<Constant>(IE->getOperand(2)) &&
11010           isa<Constant>(EI.getOperand(1))) {
11011         AddUsesToWorkList(EI);
11012         EI.setOperand(0, IE->getOperand(0));
11013         return &EI;
11014       }
11015     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11016       // If this is extracting an element from a shufflevector, figure out where
11017       // it came from and extract from the appropriate input element instead.
11018       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11019         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11020         Value *Src;
11021         if (SrcIdx < SVI->getType()->getNumElements())
11022           Src = SVI->getOperand(0);
11023         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11024           SrcIdx -= SVI->getType()->getNumElements();
11025           Src = SVI->getOperand(1);
11026         } else {
11027           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11028         }
11029         return new ExtractElementInst(Src, SrcIdx);
11030       }
11031     }
11032   }
11033   return 0;
11034 }
11035
11036 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11037 /// elements from either LHS or RHS, return the shuffle mask and true. 
11038 /// Otherwise, return false.
11039 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11040                                          std::vector<Constant*> &Mask) {
11041   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11042          "Invalid CollectSingleShuffleElements");
11043   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11044
11045   if (isa<UndefValue>(V)) {
11046     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11047     return true;
11048   } else if (V == LHS) {
11049     for (unsigned i = 0; i != NumElts; ++i)
11050       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11051     return true;
11052   } else if (V == RHS) {
11053     for (unsigned i = 0; i != NumElts; ++i)
11054       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11055     return true;
11056   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11057     // If this is an insert of an extract from some other vector, include it.
11058     Value *VecOp    = IEI->getOperand(0);
11059     Value *ScalarOp = IEI->getOperand(1);
11060     Value *IdxOp    = IEI->getOperand(2);
11061     
11062     if (!isa<ConstantInt>(IdxOp))
11063       return false;
11064     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11065     
11066     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11067       // Okay, we can handle this if the vector we are insertinting into is
11068       // transitively ok.
11069       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11070         // If so, update the mask to reflect the inserted undef.
11071         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11072         return true;
11073       }      
11074     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11075       if (isa<ConstantInt>(EI->getOperand(1)) &&
11076           EI->getOperand(0)->getType() == V->getType()) {
11077         unsigned ExtractedIdx =
11078           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11079         
11080         // This must be extracting from either LHS or RHS.
11081         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11082           // Okay, we can handle this if the vector we are insertinting into is
11083           // transitively ok.
11084           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11085             // If so, update the mask to reflect the inserted value.
11086             if (EI->getOperand(0) == LHS) {
11087               Mask[InsertedIdx & (NumElts-1)] = 
11088                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11089             } else {
11090               assert(EI->getOperand(0) == RHS);
11091               Mask[InsertedIdx & (NumElts-1)] = 
11092                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11093               
11094             }
11095             return true;
11096           }
11097         }
11098       }
11099     }
11100   }
11101   // TODO: Handle shufflevector here!
11102   
11103   return false;
11104 }
11105
11106 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11107 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11108 /// that computes V and the LHS value of the shuffle.
11109 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11110                                      Value *&RHS) {
11111   assert(isa<VectorType>(V->getType()) && 
11112          (RHS == 0 || V->getType() == RHS->getType()) &&
11113          "Invalid shuffle!");
11114   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11115
11116   if (isa<UndefValue>(V)) {
11117     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11118     return V;
11119   } else if (isa<ConstantAggregateZero>(V)) {
11120     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11121     return V;
11122   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11123     // If this is an insert of an extract from some other vector, include it.
11124     Value *VecOp    = IEI->getOperand(0);
11125     Value *ScalarOp = IEI->getOperand(1);
11126     Value *IdxOp    = IEI->getOperand(2);
11127     
11128     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11129       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11130           EI->getOperand(0)->getType() == V->getType()) {
11131         unsigned ExtractedIdx =
11132           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11133         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11134         
11135         // Either the extracted from or inserted into vector must be RHSVec,
11136         // otherwise we'd end up with a shuffle of three inputs.
11137         if (EI->getOperand(0) == RHS || RHS == 0) {
11138           RHS = EI->getOperand(0);
11139           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11140           Mask[InsertedIdx & (NumElts-1)] = 
11141             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11142           return V;
11143         }
11144         
11145         if (VecOp == RHS) {
11146           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11147           // Everything but the extracted element is replaced with the RHS.
11148           for (unsigned i = 0; i != NumElts; ++i) {
11149             if (i != InsertedIdx)
11150               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11151           }
11152           return V;
11153         }
11154         
11155         // If this insertelement is a chain that comes from exactly these two
11156         // vectors, return the vector and the effective shuffle.
11157         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11158           return EI->getOperand(0);
11159         
11160       }
11161     }
11162   }
11163   // TODO: Handle shufflevector here!
11164   
11165   // Otherwise, can't do anything fancy.  Return an identity vector.
11166   for (unsigned i = 0; i != NumElts; ++i)
11167     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11168   return V;
11169 }
11170
11171 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11172   Value *VecOp    = IE.getOperand(0);
11173   Value *ScalarOp = IE.getOperand(1);
11174   Value *IdxOp    = IE.getOperand(2);
11175   
11176   // Inserting an undef or into an undefined place, remove this.
11177   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11178     ReplaceInstUsesWith(IE, VecOp);
11179   
11180   // If the inserted element was extracted from some other vector, and if the 
11181   // indexes are constant, try to turn this into a shufflevector operation.
11182   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11183     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11184         EI->getOperand(0)->getType() == IE.getType()) {
11185       unsigned NumVectorElts = IE.getType()->getNumElements();
11186       unsigned ExtractedIdx =
11187         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11188       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11189       
11190       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11191         return ReplaceInstUsesWith(IE, VecOp);
11192       
11193       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11194         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11195       
11196       // If we are extracting a value from a vector, then inserting it right
11197       // back into the same place, just use the input vector.
11198       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11199         return ReplaceInstUsesWith(IE, VecOp);      
11200       
11201       // We could theoretically do this for ANY input.  However, doing so could
11202       // turn chains of insertelement instructions into a chain of shufflevector
11203       // instructions, and right now we do not merge shufflevectors.  As such,
11204       // only do this in a situation where it is clear that there is benefit.
11205       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11206         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11207         // the values of VecOp, except then one read from EIOp0.
11208         // Build a new shuffle mask.
11209         std::vector<Constant*> Mask;
11210         if (isa<UndefValue>(VecOp))
11211           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11212         else {
11213           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11214           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11215                                                        NumVectorElts));
11216         } 
11217         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11218         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11219                                      ConstantVector::get(Mask));
11220       }
11221       
11222       // If this insertelement isn't used by some other insertelement, turn it
11223       // (and any insertelements it points to), into one big shuffle.
11224       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11225         std::vector<Constant*> Mask;
11226         Value *RHS = 0;
11227         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11228         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11229         // We now have a shuffle of LHS, RHS, Mask.
11230         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11231       }
11232     }
11233   }
11234
11235   return 0;
11236 }
11237
11238
11239 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11240   Value *LHS = SVI.getOperand(0);
11241   Value *RHS = SVI.getOperand(1);
11242   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11243
11244   bool MadeChange = false;
11245   
11246   // Undefined shuffle mask -> undefined value.
11247   if (isa<UndefValue>(SVI.getOperand(2)))
11248     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11249   
11250   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11251   // the undef, change them to undefs.
11252   if (isa<UndefValue>(SVI.getOperand(1))) {
11253     // Scan to see if there are any references to the RHS.  If so, replace them
11254     // with undef element refs and set MadeChange to true.
11255     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11256       if (Mask[i] >= e && Mask[i] != 2*e) {
11257         Mask[i] = 2*e;
11258         MadeChange = true;
11259       }
11260     }
11261     
11262     if (MadeChange) {
11263       // Remap any references to RHS to use LHS.
11264       std::vector<Constant*> Elts;
11265       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11266         if (Mask[i] == 2*e)
11267           Elts.push_back(UndefValue::get(Type::Int32Ty));
11268         else
11269           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11270       }
11271       SVI.setOperand(2, ConstantVector::get(Elts));
11272     }
11273   }
11274   
11275   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11276   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11277   if (LHS == RHS || isa<UndefValue>(LHS)) {
11278     if (isa<UndefValue>(LHS) && LHS == RHS) {
11279       // shuffle(undef,undef,mask) -> undef.
11280       return ReplaceInstUsesWith(SVI, LHS);
11281     }
11282     
11283     // Remap any references to RHS to use LHS.
11284     std::vector<Constant*> Elts;
11285     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11286       if (Mask[i] >= 2*e)
11287         Elts.push_back(UndefValue::get(Type::Int32Ty));
11288       else {
11289         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11290             (Mask[i] <  e && isa<UndefValue>(LHS))) {
11291           Mask[i] = 2*e;     // Turn into undef.
11292           Elts.push_back(UndefValue::get(Type::Int32Ty));
11293         } else {
11294           Mask[i] &= (e-1);  // Force to LHS.
11295           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11296         }
11297       }
11298     }
11299     SVI.setOperand(0, SVI.getOperand(1));
11300     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11301     SVI.setOperand(2, ConstantVector::get(Elts));
11302     LHS = SVI.getOperand(0);
11303     RHS = SVI.getOperand(1);
11304     MadeChange = true;
11305   }
11306   
11307   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11308   bool isLHSID = true, isRHSID = true;
11309     
11310   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11311     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11312     // Is this an identity shuffle of the LHS value?
11313     isLHSID &= (Mask[i] == i);
11314       
11315     // Is this an identity shuffle of the RHS value?
11316     isRHSID &= (Mask[i]-e == i);
11317   }
11318
11319   // Eliminate identity shuffles.
11320   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11321   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11322   
11323   // If the LHS is a shufflevector itself, see if we can combine it with this
11324   // one without producing an unusual shuffle.  Here we are really conservative:
11325   // we are absolutely afraid of producing a shuffle mask not in the input
11326   // program, because the code gen may not be smart enough to turn a merged
11327   // shuffle into two specific shuffles: it may produce worse code.  As such,
11328   // we only merge two shuffles if the result is one of the two input shuffle
11329   // masks.  In this case, merging the shuffles just removes one instruction,
11330   // which we know is safe.  This is good for things like turning:
11331   // (splat(splat)) -> splat.
11332   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11333     if (isa<UndefValue>(RHS)) {
11334       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11335
11336       std::vector<unsigned> NewMask;
11337       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11338         if (Mask[i] >= 2*e)
11339           NewMask.push_back(2*e);
11340         else
11341           NewMask.push_back(LHSMask[Mask[i]]);
11342       
11343       // If the result mask is equal to the src shuffle or this shuffle mask, do
11344       // the replacement.
11345       if (NewMask == LHSMask || NewMask == Mask) {
11346         std::vector<Constant*> Elts;
11347         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11348           if (NewMask[i] >= e*2) {
11349             Elts.push_back(UndefValue::get(Type::Int32Ty));
11350           } else {
11351             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11352           }
11353         }
11354         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11355                                      LHSSVI->getOperand(1),
11356                                      ConstantVector::get(Elts));
11357       }
11358     }
11359   }
11360
11361   return MadeChange ? &SVI : 0;
11362 }
11363
11364
11365
11366
11367 /// TryToSinkInstruction - Try to move the specified instruction from its
11368 /// current block into the beginning of DestBlock, which can only happen if it's
11369 /// safe to move the instruction past all of the instructions between it and the
11370 /// end of its block.
11371 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11372   assert(I->hasOneUse() && "Invariants didn't hold!");
11373
11374   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11375   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11376     return false;
11377
11378   // Do not sink alloca instructions out of the entry block.
11379   if (isa<AllocaInst>(I) && I->getParent() ==
11380         &DestBlock->getParent()->getEntryBlock())
11381     return false;
11382
11383   // We can only sink load instructions if there is nothing between the load and
11384   // the end of block that could change the value.
11385   if (I->mayReadFromMemory()) {
11386     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11387          Scan != E; ++Scan)
11388       if (Scan->mayWriteToMemory())
11389         return false;
11390   }
11391
11392   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11393
11394   I->moveBefore(InsertPos);
11395   ++NumSunkInst;
11396   return true;
11397 }
11398
11399
11400 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11401 /// all reachable code to the worklist.
11402 ///
11403 /// This has a couple of tricks to make the code faster and more powerful.  In
11404 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11405 /// them to the worklist (this significantly speeds up instcombine on code where
11406 /// many instructions are dead or constant).  Additionally, if we find a branch
11407 /// whose condition is a known constant, we only visit the reachable successors.
11408 ///
11409 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11410                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11411                                        InstCombiner &IC,
11412                                        const TargetData *TD) {
11413   SmallVector<BasicBlock*, 256> Worklist;
11414   Worklist.push_back(BB);
11415
11416   while (!Worklist.empty()) {
11417     BB = Worklist.back();
11418     Worklist.pop_back();
11419     
11420     // We have now visited this block!  If we've already been here, ignore it.
11421     if (!Visited.insert(BB)) continue;
11422     
11423     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11424       Instruction *Inst = BBI++;
11425       
11426       // DCE instruction if trivially dead.
11427       if (isInstructionTriviallyDead(Inst)) {
11428         ++NumDeadInst;
11429         DOUT << "IC: DCE: " << *Inst;
11430         Inst->eraseFromParent();
11431         continue;
11432       }
11433       
11434       // ConstantProp instruction if trivially constant.
11435       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11436         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11437         Inst->replaceAllUsesWith(C);
11438         ++NumConstProp;
11439         Inst->eraseFromParent();
11440         continue;
11441       }
11442      
11443       IC.AddToWorkList(Inst);
11444     }
11445
11446     // Recursively visit successors.  If this is a branch or switch on a
11447     // constant, only visit the reachable successor.
11448     TerminatorInst *TI = BB->getTerminator();
11449     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11450       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11451         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11452         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11453         Worklist.push_back(ReachableBB);
11454         continue;
11455       }
11456     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11457       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11458         // See if this is an explicit destination.
11459         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11460           if (SI->getCaseValue(i) == Cond) {
11461             BasicBlock *ReachableBB = SI->getSuccessor(i);
11462             Worklist.push_back(ReachableBB);
11463             continue;
11464           }
11465         
11466         // Otherwise it is the default destination.
11467         Worklist.push_back(SI->getSuccessor(0));
11468         continue;
11469       }
11470     }
11471     
11472     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11473       Worklist.push_back(TI->getSuccessor(i));
11474   }
11475 }
11476
11477 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11478   bool Changed = false;
11479   TD = &getAnalysis<TargetData>();
11480   
11481   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11482              << F.getNameStr() << "\n");
11483
11484   {
11485     // Do a depth-first traversal of the function, populate the worklist with
11486     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11487     // track of which blocks we visit.
11488     SmallPtrSet<BasicBlock*, 64> Visited;
11489     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11490
11491     // Do a quick scan over the function.  If we find any blocks that are
11492     // unreachable, remove any instructions inside of them.  This prevents
11493     // the instcombine code from having to deal with some bad special cases.
11494     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11495       if (!Visited.count(BB)) {
11496         Instruction *Term = BB->getTerminator();
11497         while (Term != BB->begin()) {   // Remove instrs bottom-up
11498           BasicBlock::iterator I = Term; --I;
11499
11500           DOUT << "IC: DCE: " << *I;
11501           ++NumDeadInst;
11502
11503           if (!I->use_empty())
11504             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11505           I->eraseFromParent();
11506         }
11507       }
11508   }
11509
11510   while (!Worklist.empty()) {
11511     Instruction *I = RemoveOneFromWorkList();
11512     if (I == 0) continue;  // skip null values.
11513
11514     // Check to see if we can DCE the instruction.
11515     if (isInstructionTriviallyDead(I)) {
11516       // Add operands to the worklist.
11517       if (I->getNumOperands() < 4)
11518         AddUsesToWorkList(*I);
11519       ++NumDeadInst;
11520
11521       DOUT << "IC: DCE: " << *I;
11522
11523       I->eraseFromParent();
11524       RemoveFromWorkList(I);
11525       continue;
11526     }
11527
11528     // Instruction isn't dead, see if we can constant propagate it.
11529     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11530       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11531
11532       // Add operands to the worklist.
11533       AddUsesToWorkList(*I);
11534       ReplaceInstUsesWith(*I, C);
11535
11536       ++NumConstProp;
11537       I->eraseFromParent();
11538       RemoveFromWorkList(I);
11539       continue;
11540     }
11541
11542     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11543       // See if we can constant fold its operands.
11544       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11545         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11546           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11547             i->set(NewC);
11548         }
11549       }
11550     }
11551
11552     // See if we can trivially sink this instruction to a successor basic block.
11553     if (I->hasOneUse()) {
11554       BasicBlock *BB = I->getParent();
11555       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11556       if (UserParent != BB) {
11557         bool UserIsSuccessor = false;
11558         // See if the user is one of our successors.
11559         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11560           if (*SI == UserParent) {
11561             UserIsSuccessor = true;
11562             break;
11563           }
11564
11565         // If the user is one of our immediate successors, and if that successor
11566         // only has us as a predecessors (we'd have to split the critical edge
11567         // otherwise), we can keep going.
11568         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11569             next(pred_begin(UserParent)) == pred_end(UserParent))
11570           // Okay, the CFG is simple enough, try to sink this instruction.
11571           Changed |= TryToSinkInstruction(I, UserParent);
11572       }
11573     }
11574
11575     // Now that we have an instruction, try combining it to simplify it...
11576 #ifndef NDEBUG
11577     std::string OrigI;
11578 #endif
11579     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11580     if (Instruction *Result = visit(*I)) {
11581       ++NumCombined;
11582       // Should we replace the old instruction with a new one?
11583       if (Result != I) {
11584         DOUT << "IC: Old = " << *I
11585              << "    New = " << *Result;
11586
11587         // Everything uses the new instruction now.
11588         I->replaceAllUsesWith(Result);
11589
11590         // Push the new instruction and any users onto the worklist.
11591         AddToWorkList(Result);
11592         AddUsersToWorkList(*Result);
11593
11594         // Move the name to the new instruction first.
11595         Result->takeName(I);
11596
11597         // Insert the new instruction into the basic block...
11598         BasicBlock *InstParent = I->getParent();
11599         BasicBlock::iterator InsertPos = I;
11600
11601         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11602           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11603             ++InsertPos;
11604
11605         InstParent->getInstList().insert(InsertPos, Result);
11606
11607         // Make sure that we reprocess all operands now that we reduced their
11608         // use counts.
11609         AddUsesToWorkList(*I);
11610
11611         // Instructions can end up on the worklist more than once.  Make sure
11612         // we do not process an instruction that has been deleted.
11613         RemoveFromWorkList(I);
11614
11615         // Erase the old instruction.
11616         InstParent->getInstList().erase(I);
11617       } else {
11618 #ifndef NDEBUG
11619         DOUT << "IC: Mod = " << OrigI
11620              << "    New = " << *I;
11621 #endif
11622
11623         // If the instruction was modified, it's possible that it is now dead.
11624         // if so, remove it.
11625         if (isInstructionTriviallyDead(I)) {
11626           // Make sure we process all operands now that we are reducing their
11627           // use counts.
11628           AddUsesToWorkList(*I);
11629
11630           // Instructions may end up in the worklist more than once.  Erase all
11631           // occurrences of this instruction.
11632           RemoveFromWorkList(I);
11633           I->eraseFromParent();
11634         } else {
11635           AddToWorkList(I);
11636           AddUsersToWorkList(*I);
11637         }
11638       }
11639       Changed = true;
11640     }
11641   }
11642
11643   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11644     
11645   // Do an explicit clear, this shrinks the map if needed.
11646   WorklistMap.clear();
11647   return Changed;
11648 }
11649
11650
11651 bool InstCombiner::runOnFunction(Function &F) {
11652   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11653   
11654   bool EverMadeChange = false;
11655
11656   // Iterate while there is work to do.
11657   unsigned Iteration = 0;
11658   while (DoOneIteration(F, Iteration++))
11659     EverMadeChange = true;
11660   return EverMadeChange;
11661 }
11662
11663 FunctionPass *llvm::createInstructionCombiningPass() {
11664   return new InstCombiner();
11665 }
11666
11667